From eb94e706dfa6732041c6dda7edb3897dc946a0ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=80=9D=E6=B5=B7?= <1464576565@qq.com> Date: Fri, 5 Sep 2025 19:46:39 +0800 Subject: [PATCH] modify --- Editor/CoreEditor.meta | 8 + Editor/CoreEditor/Runtime.meta | 8 + .../CoreEditor/Runtime/CheckUnityVersion.cs | 16 + .../Runtime/CheckUnityVersion.cs.meta | 3 + Editor/CoreEditor/Runtime/FantasyStartup.cs | 49 + .../CoreEditor/Runtime/FantasyStartup.cs.meta | 3 + Editor/CoreEditor/Runtime/LinkXmlGenerator.cs | 52 + .../Runtime/LinkXmlGenerator.cs.meta | 3 + Editor/CoreEditor/Runtime/Settings.meta | 3 + .../Runtime/Settings/FantasySettings.cs | 13 + .../Runtime/Settings/FantasySettings.cs.meta | 3 + .../Settings/FantasySettingsProvider.cs | 102 + .../Settings/FantasySettingsProvider.cs.meta | 3 + .../FantasySettingsScriptableObject.cs | 25 + .../FantasySettingsScriptableObject.cs.meta | 3 + .../Settings/ScriptableObjectSingleton.cs | 100 + .../ScriptableObjectSingleton.cs.meta | 3 + Editor/CoreEditor/Runtime/WSocket.meta | 8 + .../Runtime/WSocket/SettingsWindow.cs | 229 ++ .../Runtime/WSocket/SettingsWindow.cs.meta | 11 + Runtime/CoreRuntime.meta | 8 + Runtime/CoreRuntime/Core.meta | 8 + Runtime/CoreRuntime/Core/Assembly.meta | 8 + .../CoreRuntime/Core/Assembly/AssemblyInfo.cs | 89 + .../Core/Assembly/AssemblyInfo.cs.meta | 11 + .../Core/Assembly/AssemblySystem.cs | 285 +++ .../Core/Assembly/AssemblySystem.cs.meta | 11 + .../CoreRuntime/Core/Assembly/IAssembly.cs | 27 + .../Core/Assembly/IAssembly.cs.meta | 11 + Runtime/CoreRuntime/Core/Benchmark.meta | 8 + .../CoreRuntime/Core/Benchmark/Handler.meta | 8 + .../Handler/BenchmarkRequestHandler.cs | 25 + .../Handler/BenchmarkRequestHandler.cs.meta | 11 + Runtime/CoreRuntime/Core/DataBase.meta | 8 + .../CoreRuntime/Core/DataBase/DataBaseType.cs | 20 + .../Core/DataBase/DataBaseType.cs.meta | 11 + .../CoreRuntime/Core/DataBase/IDataBase.cs | 210 ++ .../Core/DataBase/IDataBase.cs.meta | 11 + .../Core/DataBase/MongoDataBase.cs | 1081 ++++++++ .../Core/DataBase/MongoDataBase.cs.meta | 11 + Runtime/CoreRuntime/Core/DataBase/World.cs | 77 + .../CoreRuntime/Core/DataBase/World.cs.meta | 11 + Runtime/CoreRuntime/Core/DataStructure.meta | 8 + .../Core/DataStructure/Collection.meta | 8 + .../Collection/CircularBuffer.cs | 346 +++ .../Collection/CircularBuffer.cs.meta | 11 + .../Collection/ConcurrentOneToManyListPool.cs | 197 ++ .../ConcurrentOneToManyListPool.cs.meta | 11 + .../ConcurrentOneToManyQueuePool.cs | 194 ++ .../ConcurrentOneToManyQueuePool.cs.meta | 11 + .../DataStructure/Collection/HashSetPool.cs | 134 + .../Collection/HashSetPool.cs.meta | 11 + .../Core/DataStructure/Collection/ListPool.cs | 101 + .../DataStructure/Collection/ListPool.cs.meta | 11 + .../Collection/OneToManyHashSetPool.cs | 208 ++ .../Collection/OneToManyHashSetPool.cs.meta | 11 + .../Collection/OneToManyListPool.cs | 232 ++ .../Collection/OneToManyListPool.cs.meta | 11 + .../Collection/OneToManyQueuePool.cs | 204 ++ .../Collection/OneToManyQueuePool.cs.meta | 11 + .../DataStructure/Collection/ReuseList.cs | 69 + .../Collection/ReuseList.cs.meta | 11 + .../SortedConcurrentOneToManyListPool.cs | 226 ++ .../SortedConcurrentOneToManyListPool.cs.meta | 11 + .../Collection/SortedOneToManyHashSetPool.cs | 192 ++ .../SortedOneToManyHashSetPool.cs.meta | 11 + .../Collection/SortedOneToManyListPool.cs | 217 ++ .../SortedOneToManyListPool.cs.meta | 11 + .../Core/DataStructure/Dictionary.meta | 8 + .../Dictionary/DictionaryExtensions.cs | 31 + .../Dictionary/DictionaryExtensions.cs.meta | 11 + .../Dictionary/DictionaryPool.cs | 70 + .../Dictionary/DictionaryPool.cs.meta | 11 + .../Dictionary/DoubleMapDictionaryPool.cs | 289 +++ .../DoubleMapDictionaryPool.cs.meta | 11 + .../Dictionary/EntityDictionary.cs | 91 + .../Dictionary/EntityDictionary.cs.meta | 11 + .../Dictionary/OneToManyDictionaryPool.cs | 247 ++ .../OneToManyDictionaryPool.cs.meta | 11 + .../OneToManySortedDictionaryPool.cs | 250 ++ .../OneToManySortedDictionaryPool.cs.meta | 11 + .../Dictionary/ReuseDictionary.cs | 70 + .../Dictionary/ReuseDictionary.cs.meta | 11 + .../Dictionary/SortedDictionaryPool.cs | 70 + .../Dictionary/SortedDictionaryPool.cs.meta | 11 + .../Core/DataStructure/NativeCollections.meta | 8 + .../Core/DataStructure/PriorityQueue.meta | 8 + .../PriorityQueue/PriorityQueueGenerics.cs | 121 + .../PriorityQueueGenerics.cs.meta | 11 + .../PriorityQueue/PriorityQueueItem.cs | 30 + .../PriorityQueue/PriorityQueueItem.cs.meta | 11 + .../PriorityQueue/PriorityQueueSimple.cs | 116 + .../PriorityQueue/PriorityQueueSimple.cs.meta | 11 + .../Core/DataStructure/SkipTable.meta | 8 + .../Core/DataStructure/SkipTable/SkipTable.cs | 190 ++ .../DataStructure/SkipTable/SkipTable.cs.meta | 11 + .../DataStructure/SkipTable/SkipTableBase.cs | 282 +++ .../SkipTable/SkipTableBase.cs.meta | 11 + .../DataStructure/SkipTable/SkipTableDesc.cs | 188 ++ .../SkipTable/SkipTableDesc.cs.meta | 11 + .../DataStructure/SkipTable/SkipTableNode.cs | 68 + .../SkipTable/SkipTableNode.cs.meta | 11 + Runtime/CoreRuntime/Core/Entitas.meta | 8 + .../CoreRuntime/Core/Entitas/Component.meta | 8 + .../Core/Entitas/Component/CoroutineLock.meta | 8 + .../Component/CoroutineLock/CoroutineLock.cs | 140 ++ .../CoroutineLock/CoroutineLock.cs.meta | 11 + .../CoroutineLock/CoroutineLockComponent.cs | 100 + .../CoroutineLockComponent.cs.meta | 11 + .../CoroutineLock/CoroutineLockQueue.cs | 35 + .../CoroutineLock/CoroutineLockQueue.cs.meta | 11 + .../CoroutineLock/WaitCoroutineLock.cs | 146 ++ .../CoroutineLock/WaitCoroutineLock.cs.meta | 11 + .../Core/Entitas/Component/EntityComponent.cs | 523 ++++ .../Entitas/Component/EntityComponent.cs.meta | 11 + .../Entitas/Component/EventComponent.meta | 8 + .../EventComponent/EventComponent.cs | 252 ++ .../EventComponent/EventComponent.cs.meta | 11 + .../Component/EventComponent/Interface.meta | 8 + .../EventComponent/Interface/IEvent.cs | 112 + .../EventComponent/Interface/IEvent.cs.meta | 11 + .../Entitas/Component/MessagePoolComponent.cs | 139 ++ .../Component/MessagePoolComponent.cs.meta | 11 + .../Component/SingleCollectionComponent.meta | 8 + .../SingleCollectionComponent.cs | 167 ++ .../SingleCollectionComponent.cs.meta | 11 + .../Entitas/Component/TimerComponent.meta | 8 + .../Component/TimerComponent/Interface.meta | 8 + .../TimerComponent/Interface/TimerHandler.cs | 10 + .../Interface/TimerHandler.cs.meta | 11 + .../Component/TimerComponent/TimeWheel.meta | 8 + .../TimerComponent/TimeWheel/ScheduledTask.cs | 49 + .../TimeWheel/ScheduledTask.cs.meta | 11 + .../TimerComponent/TimeWheel/TimeWheel.cs | 134 + .../TimeWheel/TimeWheel.cs.meta | 11 + .../Component/TimerComponent/TimerAction.cs | 27 + .../TimerComponent/TimerAction.cs.meta | 11 + .../TimerComponent/TimerComponent.cs | 52 + .../TimerComponent/TimerComponent.cs.meta | 11 + .../TimerComponent/TimerScheduler.meta | 8 + .../TimerScheduler/TimerSchedulerNet.cs | 390 +++ .../TimerScheduler/TimerSchedulerNet.cs.meta | 11 + .../TimerScheduler/TimerSchedulerNetUnity.cs | 372 +++ .../TimerSchedulerNetUnity.cs.meta | 11 + .../Component/TimerComponent/TimerType.cs | 25 + .../TimerComponent/TimerType.cs.meta | 11 + Runtime/CoreRuntime/Core/Entitas/Entity.cs | 1066 ++++++++ .../CoreRuntime/Core/Entitas/Entity.cs.meta | 11 + .../CoreRuntime/Core/Entitas/EntityPool.cs | 66 + .../Core/Entitas/EntityPool.cs.meta | 11 + .../Core/Entitas/EntityReference.cs | 59 + .../Core/Entitas/EntityReference.cs.meta | 11 + .../CoreRuntime/Core/Entitas/Interface.meta | 8 + .../Core/Entitas/Interface/Supported.meta | 8 + .../Supported/ISingleCollectionRoot.cs | 17 + .../Supported/ISingleCollectionRoot.cs.meta | 11 + .../Interface/Supported/ISupportedDataBase.cs | 19 + .../Supported/ISupportedDataBase.cs.meta | 11 + .../Supported/ISupportedMultiEntity.cs | 20 + .../Supported/ISupportedMultiEntity.cs.meta | 11 + .../Supported/ISupportedSingleCollection.cs | 47 + .../ISupportedSingleCollection.cs.meta | 11 + .../Interface/Supported/ISupportedTransfer.cs | 19 + .../Supported/ISupportedTransfer.cs.meta | 11 + .../Core/Entitas/Interface/System.meta | 8 + .../Entitas/Interface/System/IAwakeSystem.cs | 32 + .../Interface/System/IAwakeSystem.cs.meta | 11 + .../Interface/System/ICustomEntitiesSystem.cs | 59 + .../System/ICustomEntitiesSystem.cs.meta | 11 + .../Interface/System/IDeserializeSystem.cs | 32 + .../System/IDeserializeSystem.cs.meta | 11 + .../Interface/System/IDestroySystem.cs | 32 + .../Interface/System/IDestroySystem.cs.meta | 11 + .../Interface/System/IEntitiesSystem.cs | 22 + .../Interface/System/IEntitiesSystem.cs.meta | 11 + .../Interface/System/ILateUpdateSystem.cs | 36 + .../System/ILateUpdateSystem.cs.meta | 11 + .../Entitas/Interface/System/IUpdateSystem.cs | 31 + .../Interface/System/IUpdateSystem.cs.meta | 11 + Runtime/CoreRuntime/Core/FTask.meta | 8 + Runtime/CoreRuntime/Core/FTask/Builder.meta | 8 + .../AsyncFTaskCompletedMethodBuilder.cs | 52 + .../AsyncFTaskCompletedMethodBuilder.cs.meta | 11 + .../FTask/Builder/AsyncFTaskMethodBuilder.cs | 140 ++ .../Builder/AsyncFTaskMethodBuilder.cs.meta | 11 + .../FTask/Builder/AsyncFVoidMethodBuilder.cs | 62 + .../Builder/AsyncFVoidMethodBuilder.cs.meta | 11 + .../Core/FTask/FCancellationToken.meta | 8 + .../FCancellationToken/FCancellationToken.cs | 121 + .../FCancellationToken.cs.meta | 11 + .../Core/FTask/FTask.Extension.meta | 8 + .../FTask/FTask.Extension/FTask.Factory.cs | 115 + .../FTask.Extension/FTask.Factory.cs.meta | 11 + .../Core/FTask/FTask.Extension/FTask.Tools.cs | 345 +++ .../FTask/FTask.Extension/FTask.Tools.cs.meta | 11 + Runtime/CoreRuntime/Core/FTask/Task.meta | 8 + Runtime/CoreRuntime/Core/FTask/Task/FTask.cs | 263 ++ .../CoreRuntime/Core/FTask/Task/FTask.cs.meta | 11 + .../Core/FTask/Task/FTaskCompleted.cs | 31 + .../Core/FTask/Task/FTaskCompleted.cs.meta | 11 + Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs | 29 + .../CoreRuntime/Core/FTask/Task/FVoid.cs.meta | 11 + Runtime/CoreRuntime/Core/Helper.meta | 8 + Runtime/CoreRuntime/Core/Helper/ByteHelper.cs | 801 ++++++ .../Core/Helper/ByteHelper.cs.meta | 11 + Runtime/CoreRuntime/Core/Helper/Download.meta | 8 + .../Core/Helper/Download/ADownload.cs | 50 + .../Core/Helper/Download/ADownload.cs.meta | 3 + .../Core/Helper/Download/Download.cs | 72 + .../Core/Helper/Download/Download.cs.meta | 3 + .../Helper/Download/DownloadAssetBundle.cs | 54 + .../Download/DownloadAssetBundle.cs.meta | 3 + .../Core/Helper/Download/DownloadAudioClip.cs | 54 + .../Helper/Download/DownloadAudioClip.cs.meta | 3 + .../Core/Helper/Download/DownloadByte.cs | 52 + .../Core/Helper/Download/DownloadByte.cs.meta | 3 + .../Core/Helper/Download/DownloadSprite.cs | 55 + .../Helper/Download/DownloadSprite.cs.meta | 3 + .../Core/Helper/Download/DownloadText.cs | 52 + .../Core/Helper/Download/DownloadText.cs.meta | 3 + .../Core/Helper/Download/DownloadTexture.cs | 54 + .../Helper/Download/DownloadTexture.cs.meta | 3 + .../CoreRuntime/Core/Helper/EncryptHelper.cs | 63 + .../Core/Helper/EncryptHelper.cs.meta | 11 + Runtime/CoreRuntime/Core/Helper/FileHelper.cs | 187 ++ .../Core/Helper/FileHelper.cs.meta | 11 + .../CoreRuntime/Core/Helper/HashCodeHelper.cs | 336 +++ .../Core/Helper/HashCodeHelper.cs.meta | 11 + .../CoreRuntime/Core/Helper/HttpClient.meta | 8 + .../Helper/HttpClient/HttpClientHelper.cs | 144 ++ .../HttpClient/HttpClientHelper.cs.meta | 3 + .../Core/Helper/HttpClient/HttpClientPool.cs | 44 + .../Helper/HttpClient/HttpClientPool.cs.meta | 3 + .../Core/Helper/HttpClient/IJsonRpcRequest.cs | 20 + .../Helper/HttpClient/IJsonRpcRequest.cs.meta | 3 + Runtime/CoreRuntime/Core/Helper/JsonHelper.cs | 57 + .../Core/Helper/JsonHelper.cs.meta | 11 + .../CoreRuntime/Core/Helper/NetworkHelper.cs | 438 ++++ .../Core/Helper/NetworkHelper.cs.meta | 11 + .../CoreRuntime/Core/Helper/RandomHelper.cs | 415 ++++ .../Core/Helper/RandomHelper.cs.meta | 11 + .../Core/Helper/RandomHelperWebgl.cs | 295 +++ .../Core/Helper/RandomHelperWebgl.cs.meta | 11 + .../CoreRuntime/Core/Helper/SocketHelper.cs | 74 + .../Core/Helper/SocketHelper.cs.meta | 11 + Runtime/CoreRuntime/Core/Helper/TimeHelper.cs | 83 + .../Core/Helper/TimeHelper.cs.meta | 11 + .../Core/Helper/UnityWebRequest.meta | 8 + .../UnityWebRequest/UnityWebRequestHelper.cs | 244 ++ .../UnityWebRequestHelper.cs.meta | 3 + .../Core/Helper/WebSocketHelper.cs | 38 + .../Core/Helper/WebSocketHelper.cs.meta | 11 + Runtime/CoreRuntime/Core/Helper/WinPeriod.cs | 24 + .../CoreRuntime/Core/Helper/WinPeriod.cs.meta | 11 + Runtime/CoreRuntime/Core/IdFactory.meta | 8 + .../CoreRuntime/Core/IdFactory/Default.meta | 8 + .../Core/IdFactory/Default/EntityIdStruct.cs | 136 ++ .../IdFactory/Default/EntityIdStruct.cs.meta | 11 + .../Core/IdFactory/Default/RuntimeIdStruct.cs | 137 ++ .../IdFactory/Default/RuntimeIdStruct.cs.meta | 11 + .../Core/IdFactory/IdFactoryHelper.cs | 132 + .../Core/IdFactory/IdFactoryHelper.cs.meta | 11 + .../Core/IdFactory/IdFactoryType.cs | 23 + .../Core/IdFactory/IdFactoryType.cs.meta | 11 + .../CoreRuntime/Core/IdFactory/Interface.meta | 8 + .../Core/IdFactory/Interface/IIdFactory.cs | 24 + .../IdFactory/Interface/IIdFactory.cs.meta | 11 + .../IdFactory/Interface/IIdFactoryTool.cs | 27 + .../Interface/IIdFactoryTool.cs.meta | 11 + Runtime/CoreRuntime/Core/IdFactory/World.meta | 8 + .../IdFactory/World/WorldEntityIdFactory.cs | 153 ++ .../World/WorldEntityIdFactory.cs.meta | 11 + .../IdFactory/World/WorldRuntimeIdFactory.cs | 155 ++ .../World/WorldRuntimeIdFactory.cs.meta | 11 + Runtime/CoreRuntime/Core/InnerErrorCode.cs | 66 + .../CoreRuntime/Core/InnerErrorCode.cs.meta | 11 + Runtime/CoreRuntime/Core/Log.meta | 8 + Runtime/CoreRuntime/Core/Log/ConsoleLog.cs | 144 ++ .../CoreRuntime/Core/Log/ConsoleLog.cs.meta | 11 + Runtime/CoreRuntime/Core/Log/ILog.cs | 74 + Runtime/CoreRuntime/Core/Log/ILog.cs.meta | 11 + Runtime/CoreRuntime/Core/Log/Log.cs | 189 ++ Runtime/CoreRuntime/Core/Log/Log.cs.meta | 11 + Runtime/CoreRuntime/Core/Log/UnityLog.cs | 74 + Runtime/CoreRuntime/Core/Log/UnityLog.cs.meta | 11 + Runtime/CoreRuntime/Core/Network.meta | 8 + .../CoreRuntime/Core/Network/Addressable.meta | 8 + .../Network/Addressable/AddressableHelper.cs | 141 ++ .../Addressable/AddressableHelper.cs.meta | 11 + .../Addressable/AddressableManageComponent.cs | 144 ++ .../AddressableManageComponent.cs.meta | 11 + .../AddressableMessageComponent.cs | 91 + .../AddressableMessageComponent.cs.meta | 11 + .../Addressable/AddressableRouteComponent.cs | 218 ++ .../AddressableRouteComponent.cs.meta | 11 + .../Network/Addressable/AddressableScene.cs | 31 + .../Addressable/AddressableScene.cs.meta | 11 + .../Core/Network/Addressable/Handler.meta | 8 + .../Handler/I_AddressableAddHandler.cs | 26 + .../Handler/I_AddressableAddHandler.cs.meta | 11 + .../Handler/I_AddressableGetHandler.cs | 26 + .../Handler/I_AddressableGetHandler.cs.meta | 11 + .../Handler/I_AddressableLockHandler.cs | 26 + .../Handler/I_AddressableLockHandler.cs.meta | 11 + .../Handler/I_AddressableRemoveHandler.cs | 26 + .../I_AddressableRemoveHandler.cs.meta | 11 + .../Handler/I_AddressableUnLockHandler.cs | 27 + .../I_AddressableUnLockHandler.cs.meta | 11 + .../Core/Network/MemoryStreamBufferPool.cs | 96 + .../Network/MemoryStreamBufferPool.cs.meta | 11 + Runtime/CoreRuntime/Core/Network/Message.meta | 8 + .../Core/Network/Message/Dispatcher.meta | 8 + .../Network/Message/Dispatcher/Interface.meta | 8 + .../Dispatcher/Interface/IMessageHandler.cs | 220 ++ .../Interface/IMessageHandler.cs.meta | 11 + .../Interface/IRouteMessageHandler.cs | 490 ++++ .../Interface/IRouteMessageHandler.cs.meta | 11 + .../Dispatcher/MessageDispatcherComponent.cs | 426 ++++ .../MessageDispatcherComponent.cs.meta | 11 + .../Core/Network/Message/IMessage.cs | 95 + .../Core/Network/Message/IMessage.cs.meta | 11 + .../Core/Network/Message/InnerMessage.cs | 319 +++ .../Core/Network/Message/InnerMessage.cs.meta | 11 + .../Core/Network/Message/PacketParser.meta | 8 + .../Network/Message/PacketParser/Handler.meta | 8 + .../Handler/BufferPacketParser.cs | 392 +++ .../Handler/BufferPacketParser.cs.meta | 11 + .../Handler/CircularBufferPacketParser.cs | 170 ++ .../CircularBufferPacketParser.cs.meta | 11 + .../Handler/OuterBufferPacketParserHelper.cs | 73 + .../OuterBufferPacketParserHelper.cs.meta | 11 + .../Handler/ReadOnlyMemoryPacketParser.cs | 376 +++ .../ReadOnlyMemoryPacketParser.cs.meta | 11 + .../Message/PacketParser/Interface.meta | 8 + .../PacketParser/Interface/APackInfo.cs | 61 + .../PacketParser/Interface/APackInfo.cs.meta | 11 + .../PacketParser/Interface/APacketParser.cs | 30 + .../Interface/APacketParser.cs.meta | 11 + .../Network/Message/PacketParser/OpCode.cs | 125 + .../Message/PacketParser/OpCode.cs.meta | 11 + .../Network/Message/PacketParser/Pack.meta | 8 + .../PacketParser/Pack/InnerPackInfo.cs | 79 + .../PacketParser/Pack/InnerPackInfo.cs.meta | 11 + .../PacketParser/Pack/OuterPackInfo.cs | 73 + .../PacketParser/Pack/OuterPackInfo.cs.meta | 11 + .../PacketParser/Pack/ProcessPackInfo.cs | 160 ++ .../PacketParser/Pack/ProcessPackInfo.cs.meta | 11 + .../Network/Message/PacketParser/Packet.cs | 49 + .../Message/PacketParser/Packet.cs.meta | 11 + .../PacketParser/PacketParserFactory.cs | 173 ++ .../PacketParser/PacketParserFactory.cs.meta | 11 + .../Core/Network/Message/Scheduler.meta | 8 + .../Scheduler/ClientMessageScheduler.cs | 96 + .../Scheduler/ClientMessageScheduler.cs.meta | 11 + .../Scheduler/InnerMessageScheduler.cs | 211 ++ .../Scheduler/InnerMessageScheduler.cs.meta | 11 + .../Network/Message/Scheduler/Interface.meta | 8 + .../Interface/ANetworkMessageScheduler.cs | 30 + .../ANetworkMessageScheduler.cs.meta | 11 + .../Message/Scheduler/MessageHelper.meta | 8 + .../Scheduler/MessageHelper/MessageSender.cs | 107 + .../MessageHelper/MessageSender.cs.meta | 11 + .../NetworkMessagingComponent.cs | 273 +++ .../NetworkMessagingComponent.cs.meta | 11 + .../OnNetworkMessageUpdateCheckTimeout.cs | 60 + ...OnNetworkMessageUpdateCheckTimeout.cs.meta | 11 + .../Scheduler/OuterMessageScheduler.cs | 366 +++ .../Scheduler/OuterMessageScheduler.cs.meta | 11 + .../CoreRuntime/Core/Network/Protocol.meta | 8 + .../Core/Network/Protocol/Exception.meta | 8 + .../Protocol/Exception/ScanException.cs | 21 + .../Protocol/Exception/ScanException.cs.meta | 11 + .../Core/Network/Protocol/HTTP.meta | 8 + .../Protocol/HTTP/HTTPServerNetwork.cs | 128 + .../Protocol/HTTP/HTTPServerNetwork.cs.meta | 11 + .../Protocol/HTTP/SceneContextFilter.cs | 54 + .../Protocol/HTTP/SceneContextFilter.cs.meta | 11 + .../Core/Network/Protocol/Interface.meta | 8 + .../Protocol/Interface/AClientNetwork.cs | 38 + .../Protocol/Interface/AClientNetwork.cs.meta | 11 + .../Network/Protocol/Interface/ANetwork.cs | 149 ++ .../Protocol/Interface/ANetwork.cs.meta | 11 + .../Interface/ANetworkServerChannel.cs | 55 + .../Interface/ANetworkServerChannel.cs.meta | 11 + .../Protocol/Interface/INetworkChannel.cs | 14 + .../Interface/INetworkChannel.cs.meta | 11 + .../Core/Network/Protocol/KCP.meta | 8 + .../Core/Network/Protocol/KCP/Base.meta | 8 + .../Core/Network/Protocol/KCP/Base/Kcp.cs | 451 ++++ .../Network/Protocol/KCP/Base/Kcp.cs.meta | 11 + .../Core/Network/Protocol/KCP/Base/c.meta | 8 + .../Core/Network/Protocol/KCP/Base/c/kcp.cs | 1367 +++++++++++ .../Network/Protocol/KCP/Base/c/kcp.cs.meta | 11 + .../Network/Protocol/KCP/Base/define.meta | 8 + .../Protocol/KCP/Base/define/system.cs | 41 + .../Protocol/KCP/Base/define/system.cs.meta | 11 + .../Network/Protocol/KCP/Base/include.meta | 8 + .../Network/Protocol/KCP/Base/include/kcp.cs | 127 + .../Protocol/KCP/Base/include/kcp.cs.meta | 11 + .../Core/Network/Protocol/KCP/Client.meta | 8 + .../Protocol/KCP/Client/KCPClientNetwork.cs | 697 ++++++ .../KCP/Client/KCPClientNetwork.cs.meta | 11 + .../Core/Network/Protocol/KCP/KCPSettings.cs | 91 + .../Network/Protocol/KCP/KCPSettings.cs.meta | 11 + .../Core/Network/Protocol/KCP/KcpHeader.cs | 14 + .../Network/Protocol/KCP/KcpHeader.cs.meta | 11 + .../Core/Network/Protocol/KCP/Server.meta | 8 + .../KCP/Server/KCPServerNetworkByArrayPool.cs | 575 +++++ .../KCPServerNetworkByArrayPool.cs.meta | 11 + .../KCP/Server/KCPServerNetworkByPipe.cs | 619 +++++ .../KCP/Server/KCPServerNetworkByPipe.cs.meta | 11 + .../KCP/Server/KCPServerNetworkChannel.cs | 165 ++ .../Server/KCPServerNetworkChannel.cs.meta | 11 + .../Protocol/NetworkProtocolFactory.cs | 95 + .../Protocol/NetworkProtocolFactory.cs.meta | 11 + .../Network/Protocol/NetworkProtocolType.cs | 69 + .../Protocol/NetworkProtocolType.cs.meta | 11 + .../Protocol/NetworkThreadComponent.cs | 100 + .../Protocol/NetworkThreadComponent.cs.meta | 11 + .../Core/Network/Protocol/TCP.meta | 8 + .../Core/Network/Protocol/TCP/Client.meta | 8 + .../Protocol/TCP/Client/TCPClientNetwork.cs | 413 ++++ .../TCP/Client/TCPClientNetwork.cs.meta | 11 + .../Core/Network/Protocol/TCP/Server.meta | 8 + .../Protocol/TCP/Server/TCPServerNetwork.cs | 161 ++ .../TCP/Server/TCPServerNetwork.cs.meta | 11 + .../TCP/Server/TCPServerNetworkChannel.cs | 294 +++ .../Server/TCPServerNetworkChannel.cs.meta | 11 + .../Core/Network/Protocol/WebSocket.meta | 8 + .../Network/Protocol/WebSocket/Client.meta | 8 + .../Client/WebSocketClientNetwork.cs | 345 +++ .../Client/WebSocketClientNetwork.cs.meta | 11 + .../Client/WebSocketClientNetworkWebgl.cs | 190 ++ .../WebSocketClientNetworkWebgl.cs.meta | 11 + .../Network/Protocol/WebSocket/Server.meta | 8 + .../Server/WebSocketServerNetwork.cs | 112 + .../Server/WebSocketServerNetwork.cs.meta | 11 + .../Server/WebSocketServerNetworkChannel.cs | 253 ++ .../WebSocketServerNetworkChannel.cs.meta | 11 + Runtime/CoreRuntime/Core/Network/Roaming.meta | 8 + .../Core/Network/Roaming/Component.meta | 8 + .../Roaming/Component/RoamingComponent.cs | 254 ++ .../Component/RoamingComponent.cs.meta | 11 + .../Component/SessionRoamingComponent.cs | 390 +++ .../Component/SessionRoamingComponent.cs.meta | 11 + .../Component/SessionRoamingFlgComponent.cs | 23 + .../SessionRoamingFlgComponent.cs.meta | 11 + .../Roaming/Component/TerminusComponent.cs | 138 ++ .../Component/TerminusComponent.cs.meta | 11 + .../Core/Network/Roaming/Entity.meta | 8 + .../Core/Network/Roaming/Entity/Roaming.cs | 132 + .../Network/Roaming/Entity/Roaming.cs.meta | 11 + .../Core/Network/Roaming/Entity/Terminus.cs | 338 +++ .../Network/Roaming/Entity/Terminus.cs.meta | 11 + .../Core/Network/Roaming/Handler.meta | 8 + .../Handler/I_GetTerminusIdRequestHandler.cs | 32 + .../I_GetTerminusIdRequestHandler.cs.meta | 11 + .../Handler/I_LinkRoamingRequestHandler.cs | 26 + .../I_LinkRoamingRequestHandler.cs.meta | 11 + .../Handler/I_LockTerminusIdRequestHandler.cs | 35 + .../I_LockTerminusIdRequestHandler.cs.meta | 11 + .../I_TransferTerminusRequestHandler.cs | 22 + .../I_TransferTerminusRequestHandler.cs.meta | 11 + .../Handler/I_UnLinkRoamingRequestHandler.cs | 16 + .../I_UnLinkRoamingRequestHandler.cs.meta | 11 + .../I_UnLockTerminusIdRequestHandler.cs | 36 + .../I_UnLockTerminusIdRequestHandler.cs.meta | 11 + Runtime/CoreRuntime/Core/Network/Route.meta | 8 + .../Core/Network/Route/RouteComponent.cs | 82 + .../Core/Network/Route/RouteComponent.cs.meta | 11 + Runtime/CoreRuntime/Core/Network/Session.meta | 8 + .../Core/Network/Session/Component.meta | 8 + .../ConsoleSessionHeartbeatComponent.cs | 156 ++ .../ConsoleSessionHeartbeatComponent.cs.meta | 11 + .../Component/SessionIdleCheckerComponent.cs | 116 + .../SessionIdleCheckerComponent.cs.meta | 11 + .../UnitySessionHeartbeatComponent.cs | 188 ++ .../UnitySessionHeartbeatComponent.cs.meta | 11 + .../Core/Network/Session/ProcessSession.meta | 8 + .../ProcessSession/ProcessScheduler.cs | 269 ++ .../ProcessSession/ProcessScheduler.cs.meta | 11 + .../Session/ProcessSession/ProcessSession.cs | 124 + .../ProcessSession/ProcessSession.cs.meta | 11 + .../ProcessSession/ProcessSessionInfo.cs | 17 + .../ProcessSession/ProcessSessionInfo.cs.meta | 11 + .../Core/Network/Session/Session.cs | 272 +++ .../Core/Network/Session/Session.cs.meta | 11 + Runtime/CoreRuntime/Core/Platform.meta | 8 + .../CoreRuntime/Core/Platform/Console.meta | 8 + .../Core/Platform/Console/Entry.cs | 101 + .../Core/Platform/Console/Entry.cs.meta | 11 + .../Console/ThreadSynchronizationContext.cs | 38 + .../ThreadSynchronizationContext.cs.meta | 11 + Runtime/CoreRuntime/Core/Platform/Define.cs | 7 + .../CoreRuntime/Core/Platform/Define.cs.meta | 11 + Runtime/CoreRuntime/Core/Platform/Net.meta | 8 + .../Core/Platform/Net/ConfigTable.meta | 8 + .../Platform/Net/ConfigTable/MachineConfig.cs | 88 + .../Net/ConfigTable/MachineConfig.cs.meta | 11 + .../Platform/Net/ConfigTable/ProcessConfig.cs | 100 + .../Net/ConfigTable/ProcessConfig.cs.meta | 11 + .../Platform/Net/ConfigTable/SceneConfig.cs | 196 ++ .../Net/ConfigTable/SceneConfig.cs.meta | 11 + .../Platform/Net/ConfigTable/WorldConfig.cs | 93 + .../Net/ConfigTable/WorldConfig.cs.meta | 11 + .../CoreRuntime/Core/Platform/Net/Entry.cs | 121 + .../Core/Platform/Net/Entry.cs.meta | 11 + .../CoreRuntime/Core/Platform/Net/Process.cs | 156 ++ .../Core/Platform/Net/Process.cs.meta | 11 + .../Core/Platform/Net/ProcessDefine.cs | 99 + .../Core/Platform/Net/ProcessDefine.cs.meta | 11 + .../Net/ThreadSynchronizationContext.cs | 52 + .../Net/ThreadSynchronizationContext.cs.meta | 11 + Runtime/CoreRuntime/Core/Platform/Unity.meta | 8 + .../Core/Platform/Unity/AppDefine.cs | 19 + .../Core/Platform/Unity/AppDefine.cs.meta | 11 + .../Core/Platform/Unity/Attributes.meta | 8 + .../Attributes/BsonDefaultValueAttribute.cs | 11 + .../BsonDefaultValueAttribute.cs.meta | 11 + .../Unity/Attributes/BsonElementAttribute.cs | 13 + .../Attributes/BsonElementAttribute.cs.meta | 11 + .../Unity/Attributes/BsonIdAttribute.cs | 11 + .../Unity/Attributes/BsonIdAttribute.cs.meta | 11 + .../Unity/Attributes/BsonIgnoreAttribute.cs | 11 + .../Attributes/BsonIgnoreAttribute.cs.meta | 11 + .../BsonIgnoreIfDefaultAttribute.cs | 13 + .../BsonIgnoreIfDefaultAttribute.cs.meta | 11 + .../Attributes/BsonIgnoreIfNullAttribute.cs | 11 + .../BsonIgnoreIfNullAttribute.cs.meta | 11 + .../CoreRuntime/Core/Platform/Unity/Entry.cs | 109 + .../Core/Platform/Unity/Entry.cs.meta | 11 + .../CoreRuntime/Core/Platform/Unity/Temp.cs | 108 + .../Core/Platform/Unity/Temp.cs.meta | 11 + .../Unity/ThreadSynchronizationContext.cs | 104 + .../ThreadSynchronizationContext.cs.meta | 11 + Runtime/CoreRuntime/Core/Pool.meta | 8 + Runtime/CoreRuntime/Core/Pool/Concurrent.meta | 8 + .../Core/Pool/Concurrent/MultiThreadPool.cs | 37 + .../Pool/Concurrent/MultiThreadPool.cs.meta | 11 + .../Pool/Concurrent/MultiThreadPoolQueue.cs | 76 + .../Concurrent/MultiThreadPoolQueue.cs.meta | 11 + Runtime/CoreRuntime/Core/Pool/Interface.meta | 8 + .../CoreRuntime/Core/Pool/Interface/IPool.cs | 18 + .../Core/Pool/Interface/IPool.cs.meta | 11 + Runtime/CoreRuntime/Core/Pool/Normal.meta | 8 + Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs | 77 + .../CoreRuntime/Core/Pool/Normal/Pool.cs.meta | 11 + .../CoreRuntime/Core/Pool/Normal/PoolCore.cs | 203 ++ .../Core/Pool/Normal/PoolCore.cs.meta | 11 + .../Core/Pool/Normal/PoolWithDisposable.cs | 140 ++ .../Pool/Normal/PoolWithDisposable.cs.meta | 11 + Runtime/CoreRuntime/Core/Pool/PoolHelper.cs | 79 + .../CoreRuntime/Core/Pool/PoolHelper.cs.meta | 11 + Runtime/CoreRuntime/Core/Scene.meta | 8 + .../CoreRuntime/Core/Scene/ISceneUpdate.cs | 31 + .../Core/Scene/ISceneUpdate.cs.meta | 11 + Runtime/CoreRuntime/Core/Scene/Scene.cs | 645 +++++ Runtime/CoreRuntime/Core/Scene/Scene.cs.meta | 11 + .../Core/Scene/SceneRuntimeMode.cs | 21 + .../Core/Scene/SceneRuntimeMode.cs.meta | 11 + .../Core/Scene/SceneRuntimeType.cs | 21 + .../Core/Scene/SceneRuntimeType.cs.meta | 11 + Runtime/CoreRuntime/Core/Scene/Scheduler.meta | 8 + .../Core/Scene/Scheduler/ISceneScheduler.cs | 11 + .../Scene/Scheduler/ISceneScheduler.cs.meta | 11 + .../Core/Scene/Scheduler/MainScheduler.cs | 105 + .../Scene/Scheduler/MainScheduler.cs.meta | 11 + .../Scene/Scheduler/MultiThreadScheduler.cs | 103 + .../Scheduler/MultiThreadScheduler.cs.meta | 11 + .../Scene/Scheduler/ThreadPoolScheduler.cs | 138 ++ .../Scheduler/ThreadPoolScheduler.cs.meta | 11 + .../Core/Scene/Scheduler/ThreadScheduler.cs | 73 + .../Scene/Scheduler/ThreadScheduler.cs.meta | 11 + Runtime/CoreRuntime/Core/Scene/SubScene.cs | 174 ++ .../CoreRuntime/Core/Scene/SubScene.cs.meta | 11 + Runtime/CoreRuntime/Core/Serialize.meta | 8 + .../CoreRuntime/Core/Serialize/BsonPack.meta | 8 + .../Serialize/BsonPack/BsonPackHelperNet.cs | 311 +++ .../BsonPack/BsonPackHelperNet.cs.meta | 11 + .../Serialize/BsonPack/BsonPackHelperUnity.cs | 70 + .../BsonPack/BsonPackHelperUnity.cs.meta | 11 + .../Serialize/BsonPack/StructBsonSerialize.cs | 65 + .../BsonPack/StructBsonSerialize.cs.meta | 11 + .../BsonPack/SupportInitializeChecker.cs | 17 + .../BsonPack/SupportInitializeChecker.cs.meta | 11 + .../CoreRuntime/Core/Serialize/Interface.meta | 8 + .../Core/Serialize/Interface/ASerialize.cs | 60 + .../Serialize/Interface/ASerialize.cs.meta | 11 + .../Core/Serialize/Interface/ISerialize.cs | 100 + .../Serialize/Interface/ISerialize.cs.meta | 11 + .../Core/Serialize/MemoryStreamBuffer.cs | 73 + .../Core/Serialize/MemoryStreamBuffer.cs.meta | 11 + .../Core/Serialize/ProtoBufPackHelper.meta | 8 + .../Serialize/ProtoBufPackHelper/IProto.cs | 9 + .../ProtoBufPackHelper/IProto.cs.meta | 11 + .../ProtoBufPackHelperNet.cs | 234 ++ .../ProtoBufPackHelperNet.cs.meta | 11 + .../ProtoBufPackHelperUnity.cs | 225 ++ .../ProtoBufPackHelperUnity.cs.meta | 11 + .../Core/Serialize/SerializerManager.cs | 154 ++ .../Core/Serialize/SerializerManager.cs.meta | 11 + Runtime/CoreRuntime/Plugins.meta | 8 + Runtime/CoreRuntime/Plugins/Other.meta | 8 + .../Other/System.Collections.Immutable.dll | Bin 0 -> 252680 bytes .../System.Collections.Immutable.dll.meta | 35 + .../Plugins/Other/System.IO.Pipelines.dll | Bin 0 -> 84744 bytes .../Other/System.IO.Pipelines.dll.meta | 92 + ...System.Runtime.CompilerServices.Unsafe.dll | Bin 0 -> 18024 bytes ...m.Runtime.CompilerServices.Unsafe.dll.meta | 35 + Runtime/CoreRuntime/Plugins/Protobuf-net.meta | 8 + .../Plugins/Protobuf-net/BclHelpers.cs | 712 ++++++ .../Plugins/Protobuf-net/BclHelpers.cs.meta | 11 + .../Plugins/Protobuf-net/BufferExtension.cs | 78 + .../Protobuf-net/BufferExtension.cs.meta | 11 + .../Plugins/Protobuf-net/BufferPool.cs | 149 ++ .../Plugins/Protobuf-net/BufferPool.cs.meta | 11 + .../Protobuf-net/CallbackAttributes.cs | 33 + .../Protobuf-net/CallbackAttributes.cs.meta | 11 + .../Plugins/Protobuf-net/Compiler.meta | 8 + .../Protobuf-net/Compiler/CompilerContext.cs | 1435 +++++++++++ .../Compiler/CompilerContext.cs.meta | 11 + .../Compiler/CompilerDelegates.cs | 7 + .../Compiler/CompilerDelegates.cs.meta | 11 + .../Plugins/Protobuf-net/Compiler/Local.cs | 58 + .../Protobuf-net/Compiler/Local.cs.meta | 11 + .../Plugins/Protobuf-net/DataFormat.cs | 49 + .../Plugins/Protobuf-net/DataFormat.cs.meta | 11 + .../DiscriminatedUnion.Serializable.cs | 176 ++ .../DiscriminatedUnion.Serializable.cs.meta | 11 + .../Protobuf-net/DiscriminatedUnion.cs | 416 ++++ .../Protobuf-net/DiscriminatedUnion.cs.meta | 11 + .../Plugins/Protobuf-net/Extensible.cs | 284 +++ .../Plugins/Protobuf-net/Extensible.cs.meta | 11 + .../Plugins/Protobuf-net/ExtensibleUtil.cs | 118 + .../Protobuf-net/ExtensibleUtil.cs.meta | 11 + .../Protobuf-net/GlobalSuppressions.cs | Bin 0 -> 2750 bytes .../Protobuf-net/GlobalSuppressions.cs.meta | 11 + .../Plugins/Protobuf-net/Helpers.cs | 638 +++++ .../Plugins/Protobuf-net/Helpers.cs.meta | 11 + .../Plugins/Protobuf-net/IExtensible.cs | 23 + .../Plugins/Protobuf-net/IExtensible.cs.meta | 11 + .../Plugins/Protobuf-net/IExtension.cs | 58 + .../Plugins/Protobuf-net/IExtension.cs.meta | 11 + .../Plugins/Protobuf-net/IProtoInputT.cs | 13 + .../Plugins/Protobuf-net/IProtoInputT.cs.meta | 11 + .../Plugins/Protobuf-net/IProtoOutputT.cs | 55 + .../Protobuf-net/IProtoOutputT.cs.meta | 11 + .../Plugins/Protobuf-net/ImplicitFields.cs | 29 + .../Protobuf-net/ImplicitFields.cs.meta | 11 + .../Plugins/Protobuf-net/KeyValuePairProxy.cs | 44 + .../Protobuf-net/KeyValuePairProxy.cs.meta | 11 + .../Plugins/Protobuf-net/Meta.meta | 8 + .../Plugins/Protobuf-net/Meta/AttributeMap.cs | 108 + .../Protobuf-net/Meta/AttributeMap.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/BasicList.cs | 267 ++ .../Protobuf-net/Meta/BasicList.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/CallbackSet.cs | 110 + .../Protobuf-net/Meta/CallbackSet.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/MetaType.cs | 2171 +++++++++++++++++ .../Protobuf-net/Meta/MetaType.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/ProtoSyntax.cs | 17 + .../Protobuf-net/Meta/ProtoSyntax.cs.meta | 11 + .../Protobuf-net/Meta/RuntimeTypeModel.cs | 2036 ++++++++++++++++ .../Meta/RuntimeTypeModel.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/SubType.cs | 97 + .../Plugins/Protobuf-net/Meta/SubType.cs.meta | 11 + .../Protobuf-net/Meta/TypeAddedEventArgs.cs | 33 + .../Meta/TypeAddedEventArgs.cs.meta | 11 + .../Protobuf-net/Meta/TypeFormatEventArgs.cs | 64 + .../Meta/TypeFormatEventArgs.cs.meta | 11 + .../Meta/TypeModel.InputOutput.cs | 45 + .../Meta/TypeModel.InputOutput.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/TypeModel.cs | 1696 +++++++++++++ .../Protobuf-net/Meta/TypeModel.cs.meta | 11 + .../Plugins/Protobuf-net/Meta/ValueMember.cs | 855 +++++++ .../Protobuf-net/Meta/ValueMember.cs.meta | 11 + .../Plugins/Protobuf-net/NetObjectCache.cs | 190 ++ .../Protobuf-net/NetObjectCache.cs.meta | 11 + .../Plugins/Protobuf-net/PrefixStyle.cs | 26 + .../Plugins/Protobuf-net/PrefixStyle.cs.meta | 11 + .../Protobuf-net/ProtoContractAttribute.cs | 175 ++ .../ProtoContractAttribute.cs.meta | 11 + .../Protobuf-net/ProtoConverterAttribute.cs | 13 + .../ProtoConverterAttribute.cs.meta | 11 + .../Protobuf-net/ProtoEnumAttribute.cs | 36 + .../Protobuf-net/ProtoEnumAttribute.cs.meta | 11 + .../Plugins/Protobuf-net/ProtoException.cs | 30 + .../Protobuf-net/ProtoException.cs.meta | 11 + .../Protobuf-net/ProtoIgnoreAttribute.cs | 40 + .../Protobuf-net/ProtoIgnoreAttribute.cs.meta | 11 + .../Protobuf-net/ProtoIncludeAttribute.cs | 60 + .../ProtoIncludeAttribute.cs.meta | 11 + .../Plugins/Protobuf-net/ProtoMapAttribute.cs | 29 + .../Protobuf-net/ProtoMapAttribute.cs.meta | 11 + .../Protobuf-net/ProtoMemberAttribute.cs | 228 ++ .../Protobuf-net/ProtoMemberAttribute.cs.meta | 11 + .../Plugins/Protobuf-net/ProtoReader.cs | 1444 +++++++++++ .../Plugins/Protobuf-net/ProtoReader.cs.meta | 11 + .../Plugins/Protobuf-net/ProtoWriter.cs | 1003 ++++++++ .../Plugins/Protobuf-net/ProtoWriter.cs.meta | 11 + .../Protobuf-net/SerializationContext.cs | 76 + .../Protobuf-net/SerializationContext.cs.meta | 11 + .../Plugins/Protobuf-net/Serializer.cs | 514 ++++ .../Plugins/Protobuf-net/Serializer.cs.meta | 11 + .../Plugins/Protobuf-net/Serializers.meta | 8 + .../Serializers/ArrayDecorator.cs | 310 +++ .../Serializers/ArrayDecorator.cs.meta | 11 + .../Serializers/BlobSerializer.cs | 59 + .../Serializers/BlobSerializer.cs.meta | 11 + .../Serializers/BooleanSerializer.cs | 41 + .../Serializers/BooleanSerializer.cs.meta | 11 + .../Serializers/ByteSerializer.cs | 42 + .../Serializers/ByteSerializer.cs.meta | 11 + .../Serializers/CharSerializer.cs | 32 + .../Serializers/CharSerializer.cs.meta | 11 + .../Serializers/CompiledSerializer.cs | 88 + .../Serializers/CompiledSerializer.cs.meta | 11 + .../Serializers/DateTimeSerializer.cs | 65 + .../Serializers/DateTimeSerializer.cs.meta | 11 + .../Serializers/DecimalSerializer.cs | 42 + .../Serializers/DecimalSerializer.cs.meta | 11 + .../Serializers/DefaultValueDecorator.cs | 259 ++ .../Serializers/DefaultValueDecorator.cs.meta | 11 + .../Serializers/DoubleSerializer.cs | 42 + .../Serializers/DoubleSerializer.cs.meta | 11 + .../Serializers/EnumSerializer.cs | 267 ++ .../Serializers/EnumSerializer.cs.meta | 11 + .../Serializers/FieldDecorator.cs | 104 + .../Serializers/FieldDecorator.cs.meta | 11 + .../Serializers/GuidSerializer.cs | 43 + .../Serializers/GuidSerializer.cs.meta | 11 + .../Serializers/IProtoSerializer.cs | 64 + .../Serializers/IProtoSerializer.cs.meta | 11 + .../Serializers/IProtoTypeSerializer.cs | 20 + .../Serializers/IProtoTypeSerializer.cs.meta | 11 + .../Serializers/ISerializerProxy.cs | 10 + .../Serializers/ISerializerProxy.cs.meta | 11 + .../ImmutableCollectionDecorator.cs | 304 +++ .../ImmutableCollectionDecorator.cs.meta | 11 + .../Serializers/Int16Serializer.cs | 42 + .../Serializers/Int16Serializer.cs.meta | 11 + .../Serializers/Int32Serializer.cs | 42 + .../Serializers/Int32Serializer.cs.meta | 11 + .../Serializers/Int64Serializer.cs | 41 + .../Serializers/Int64Serializer.cs.meta | 11 + .../Protobuf-net/Serializers/ListDecorator.cs | 579 +++++ .../Serializers/ListDecorator.cs.meta | 11 + .../Protobuf-net/Serializers/MapDecorator.cs | 298 +++ .../Serializers/MapDecorator.cs.meta | 11 + .../Serializers/MemberSpecifiedDecorator.cs | 76 + .../MemberSpecifiedDecorator.cs.meta | 11 + .../Serializers/NetObjectSerializer.cs | 64 + .../Serializers/NetObjectSerializer.cs.meta | 11 + .../Protobuf-net/Serializers/NullDecorator.cs | 167 ++ .../Serializers/NullDecorator.cs.meta | 11 + .../Serializers/ParseableSerializer.cs | 111 + .../Serializers/ParseableSerializer.cs.meta | 11 + .../Serializers/PropertyDecorator.cs | 167 ++ .../Serializers/PropertyDecorator.cs.meta | 11 + .../Serializers/ProtoDecoratorBase.cs | 24 + .../Serializers/ProtoDecoratorBase.cs.meta | 11 + .../Serializers/ReflectedUriDecorator.cs | 90 + .../Serializers/ReflectedUriDecorator.cs.meta | 11 + .../Serializers/SByteSerializer.cs | 45 + .../Serializers/SByteSerializer.cs.meta | 11 + .../Serializers/SingleSerializer.cs | 45 + .../Serializers/SingleSerializer.cs.meta | 11 + .../Serializers/StringSerializer.cs | 41 + .../Serializers/StringSerializer.cs.meta | 11 + .../Serializers/SubItemSerializer.cs | 138 ++ .../Serializers/SubItemSerializer.cs.meta | 11 + .../Serializers/SurrogateSerializer.cs | 157 ++ .../Serializers/SurrogateSerializer.cs.meta | 11 + .../Serializers/SystemTypeSerializer.cs | 46 + .../Serializers/SystemTypeSerializer.cs.meta | 11 + .../Protobuf-net/Serializers/TagDecorator.cs | 108 + .../Serializers/TagDecorator.cs.meta | 11 + .../Serializers/TimeSpanSerializer.cs | 63 + .../Serializers/TimeSpanSerializer.cs.meta | 11 + .../Serializers/TupleSerializer.cs | 339 +++ .../Serializers/TupleSerializer.cs.meta | 11 + .../Serializers/TypeSerializer.cs | 798 ++++++ .../Serializers/TypeSerializer.cs.meta | 11 + .../Serializers/UInt16Serializer.cs | 43 + .../Serializers/UInt16Serializer.cs.meta | 11 + .../Serializers/UInt32Serializer.cs | 43 + .../Serializers/UInt32Serializer.cs.meta | 11 + .../Serializers/UInt64Serializer.cs | 43 + .../Serializers/UInt64Serializer.cs.meta | 11 + .../Protobuf-net/Serializers/UriDecorator.cs | 62 + .../Serializers/UriDecorator.cs.meta | 11 + .../Plugins/Protobuf-net/ServiceModel.meta | 8 + .../ServiceModel/ProtoBehaviorAttribute.cs | 35 + .../ProtoBehaviorAttribute.cs.meta | 11 + .../ProtoBehaviorExtensionElement.cs | 29 + .../ProtoBehaviorExtensionElement.cs.meta | 11 + .../ServiceModel/ProtoEndpointBehavior.cs | 82 + .../ProtoEndpointBehavior.cs.meta | 11 + .../ServiceModel/ProtoOperationBehavior.cs | 52 + .../ProtoOperationBehavior.cs.meta | 11 + .../ServiceModel/XmlProtoSerializer.cs | 208 ++ .../ServiceModel/XmlProtoSerializer.cs.meta | 11 + .../Plugins/Protobuf-net/SubItemToken.cs | 16 + .../Plugins/Protobuf-net/SubItemToken.cs.meta | 11 + .../Plugins/Protobuf-net/WireType.cs | 50 + .../Plugins/Protobuf-net/WireType.cs.meta | 11 + .../Plugins/Protobuf-net/protobuf-net.csproj | 86 + .../Protobuf-net/protobuf-net.csproj.meta | 7 + Runtime/CoreRuntime/Plugins/WSocket.meta | 8 + Runtime/CoreRuntime/Plugins/WSocket/Core.meta | 8 + .../Plugins/WSocket/Core/CloseEventArgs.cs | 89 + .../WSocket/Core/CloseEventArgs.cs.meta | 11 + .../Plugins/WSocket/Core/CloseStatusCode.cs | 91 + .../WSocket/Core/CloseStatusCode.cs.meta | 11 + .../Plugins/WSocket/Core/ErrorEventArgs.cs | 59 + .../WSocket/Core/ErrorEventArgs.cs.meta | 11 + .../Plugins/WSocket/Core/IWebSocket.cs | 143 ++ .../Plugins/WSocket/Core/IWebSocket.cs.meta | 11 + .../Plugins/WSocket/Core/MessageEventArgs.cs | 115 + .../WSocket/Core/MessageEventArgs.cs.meta | 11 + .../Plugins/WSocket/Core/Opcode.cs | 26 + .../Plugins/WSocket/Core/Opcode.cs.meta | 11 + .../Plugins/WSocket/Core/OpenEventArgs.cs | 11 + .../WSocket/Core/OpenEventArgs.cs.meta | 11 + .../Plugins/WSocket/Core/Settings.cs | 12 + .../Plugins/WSocket/Core/Settings.cs.meta | 11 + .../Plugins/WSocket/Core/WebSocketState.cs | 36 + .../WSocket/Core/WebSocketState.cs.meta | 11 + .../Plugins/WSocket/Implementation.meta | 8 + .../WSocket/Implementation/NoWebGL.meta | 8 + .../Implementation/NoWebGL/WebSocket.cs | 345 +++ .../Implementation/NoWebGL/WebSocket.cs.meta | 11 + .../NoWebGL/WebSocketManager.cs | 72 + .../NoWebGL/WebSocketManager.cs.meta | 11 + .../Plugins/WSocket/Implementation/WebGL.meta | 8 + .../WSocket/Implementation/WebGL/WebSocket.cs | 154 ++ .../Implementation/WebGL/WebSocket.cs.meta | 12 + .../Implementation/WebGL/WebSocketManager.cs | 159 ++ .../WebGL/WebSocketManager.cs.meta | 11 + Runtime/CoreRuntime/Plugins/WebGL.meta | 8 + .../CoreRuntime/Plugins/WebGL/WebSocket.jslib | 392 +++ .../Plugins/WebGL/WebSocket.jslib.meta | 42 + Runtime/{Network.meta => Manager.meta} | 0 Runtime/{Network => Manager}/EConnectState.cs | 0 .../EConnectState.cs.meta | 0 .../{Network => Manager}/INetworkModule.cs | 0 .../INetworkModule.cs.meta | 0 .../{Network => Manager}/NetworkComponent.cs | 0 .../NetworkComponent.cs.meta | 0 Runtime/{Network => Manager}/NetworkModule.cs | 0 .../NetworkModule.cs.meta | 0 csc.rsp | 2 + csc.rsp.meta | 7 + package.json | 3 + 854 files changed, 64984 insertions(+) create mode 100644 Editor/CoreEditor.meta create mode 100644 Editor/CoreEditor/Runtime.meta create mode 100644 Editor/CoreEditor/Runtime/CheckUnityVersion.cs create mode 100644 Editor/CoreEditor/Runtime/CheckUnityVersion.cs.meta create mode 100644 Editor/CoreEditor/Runtime/FantasyStartup.cs create mode 100644 Editor/CoreEditor/Runtime/FantasyStartup.cs.meta create mode 100644 Editor/CoreEditor/Runtime/LinkXmlGenerator.cs create mode 100644 Editor/CoreEditor/Runtime/LinkXmlGenerator.cs.meta create mode 100644 Editor/CoreEditor/Runtime/Settings.meta create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettings.cs create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettings.cs.meta create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs.meta create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs create mode 100644 Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta create mode 100644 Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs create mode 100644 Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs.meta create mode 100644 Editor/CoreEditor/Runtime/WSocket.meta create mode 100644 Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs create mode 100644 Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs.meta create mode 100644 Runtime/CoreRuntime.meta create mode 100644 Runtime/CoreRuntime/Core.meta create mode 100644 Runtime/CoreRuntime/Core/Assembly.meta create mode 100644 Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs create mode 100644 Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Assembly/IAssembly.cs create mode 100644 Runtime/CoreRuntime/Core/Assembly/IAssembly.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Benchmark.meta create mode 100644 Runtime/CoreRuntime/Core/Benchmark/Handler.meta create mode 100644 Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataBase.meta create mode 100644 Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs create mode 100644 Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataBase/IDataBase.cs create mode 100644 Runtime/CoreRuntime/Core/DataBase/IDataBase.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs create mode 100644 Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataBase/World.cs create mode 100644 Runtime/CoreRuntime/Core/DataBase/World.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/NativeCollections.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs create mode 100644 Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Entity.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Entity.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/EntityPool.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/EntityPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/EntityReference.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/EntityReference.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs create mode 100644 Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/FCancellationToken.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/FTask.Extension.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Task.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FTask.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FTask.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs.meta create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs create mode 100644 Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/ByteHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/ByteHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/Download.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/Download.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/FileHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/FileHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/JsonHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/JsonHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/RandomHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/RandomHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/SocketHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/SocketHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/TimeHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/TimeHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/UnityWebRequest.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Helper/WinPeriod.cs create mode 100644 Runtime/CoreRuntime/Core/Helper/WinPeriod.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Default.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/World.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs create mode 100644 Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/InnerErrorCode.cs create mode 100644 Runtime/CoreRuntime/Core/InnerErrorCode.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Log.meta create mode 100644 Runtime/CoreRuntime/Core/Log/ConsoleLog.cs create mode 100644 Runtime/CoreRuntime/Core/Log/ConsoleLog.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Log/ILog.cs create mode 100644 Runtime/CoreRuntime/Core/Log/ILog.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Log/Log.cs create mode 100644 Runtime/CoreRuntime/Core/Log/Log.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Log/UnityLog.cs create mode 100644 Runtime/CoreRuntime/Core/Log/UnityLog.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs create mode 100644 Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/IMessage.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/IMessage.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Exception.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/HTTP.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Entity.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Route.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Session.cs create mode 100644 Runtime/CoreRuntime/Core/Network/Session/Session.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Console.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Console/Entry.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Console/Entry.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Define.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Define.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/Entry.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/Entry.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/Process.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/Process.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs create mode 100644 Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Concurrent.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Pool/PoolHelper.cs create mode 100644 Runtime/CoreRuntime/Core/Pool/PoolHelper.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scene.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scene.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Scene/SubScene.cs create mode 100644 Runtime/CoreRuntime/Core/Scene/SubScene.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/Interface.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta create mode 100644 Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs create mode 100644 Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins.meta create mode 100644 Runtime/CoreRuntime/Plugins/Other.meta create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll.meta create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.IO.Pipelines.dll create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.IO.Pipelines.dll.meta create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll create mode 100644 Runtime/CoreRuntime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BclHelpers.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BclHelpers.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/GlobalSuppressions.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/GlobalSuppressions.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Helpers.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Helpers.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj create mode 100644 Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs create mode 100644 Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta create mode 100644 Runtime/CoreRuntime/Plugins/WebGL.meta create mode 100644 Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib create mode 100644 Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib.meta rename Runtime/{Network.meta => Manager.meta} (100%) rename Runtime/{Network => Manager}/EConnectState.cs (100%) rename Runtime/{Network => Manager}/EConnectState.cs.meta (100%) rename Runtime/{Network => Manager}/INetworkModule.cs (100%) rename Runtime/{Network => Manager}/INetworkModule.cs.meta (100%) rename Runtime/{Network => Manager}/NetworkComponent.cs (100%) rename Runtime/{Network => Manager}/NetworkComponent.cs.meta (100%) rename Runtime/{Network => Manager}/NetworkModule.cs (100%) rename Runtime/{Network => Manager}/NetworkModule.cs.meta (100%) create mode 100644 csc.rsp create mode 100644 csc.rsp.meta diff --git a/Editor/CoreEditor.meta b/Editor/CoreEditor.meta new file mode 100644 index 0000000..1956489 --- /dev/null +++ b/Editor/CoreEditor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 77313bd6dcc91f645a147a10abedadc3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CoreEditor/Runtime.meta b/Editor/CoreEditor/Runtime.meta new file mode 100644 index 0000000..de03432 --- /dev/null +++ b/Editor/CoreEditor/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e8ba5b17cffbb4ffea892f674fc8629f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CoreEditor/Runtime/CheckUnityVersion.cs b/Editor/CoreEditor/Runtime/CheckUnityVersion.cs new file mode 100644 index 0000000..34f112c --- /dev/null +++ b/Editor/CoreEditor/Runtime/CheckUnityVersion.cs @@ -0,0 +1,16 @@ +using System; +using UnityEditor; + +namespace Fantasy +{ + internal static class CheckUnityVersion + { + [InitializeOnLoadMethod] + private static void OnInitializeOnLoad() + { +#if !UNITY_2021_3_OR_NEWER + Debug.LogError("Fantasy支持的最低版本为Unity2021.3.14f1c1"); +#endif + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/CheckUnityVersion.cs.meta b/Editor/CoreEditor/Runtime/CheckUnityVersion.cs.meta new file mode 100644 index 0000000..1f13ace --- /dev/null +++ b/Editor/CoreEditor/Runtime/CheckUnityVersion.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 455f338921e74471841971fd6b79db01 +timeCreated: 1725943424 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/FantasyStartup.cs b/Editor/CoreEditor/Runtime/FantasyStartup.cs new file mode 100644 index 0000000..c541657 --- /dev/null +++ b/Editor/CoreEditor/Runtime/FantasyStartup.cs @@ -0,0 +1,49 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Fantasy +{ + [InitializeOnLoad] + public static class FantasyStartup + { + private const string ScriptAssemblies = "Library/ScriptAssemblies/"; + + static FantasyStartup() + { + if (!FantasySettingsScriptableObject.Instance.autoCopyAssembly) + { + return; + } + + var hotUpdatePath = FantasySettingsScriptableObject.Instance.hotUpdatePath; + + if (string.IsNullOrEmpty(hotUpdatePath)) + { + Debug.LogError("请先在菜单Fantasy-Fantasy Settings里设置HotUpdatePath目录位置"); + return; + } + + if (!Directory.Exists(hotUpdatePath)) + { + Directory.CreateDirectory(hotUpdatePath); + } + + // ReSharper disable once StringLastIndexOfIsCultureSpecific.1 + if (hotUpdatePath.LastIndexOf("/") != hotUpdatePath.Length - 1) + { + FantasySettingsScriptableObject.Instance.hotUpdatePath += "/"; + hotUpdatePath = FantasySettingsScriptableObject.Instance.hotUpdatePath; + } + + foreach (var instanceHotUpdateAssemblyDefinition in FantasySettingsScriptableObject.Instance.hotUpdateAssemblyDefinitions) + { + var dll = instanceHotUpdateAssemblyDefinition.name; + File.Copy($"{ScriptAssemblies}{dll}.dll", $"{hotUpdatePath}/{dll}.dll.bytes", true); + File.Copy($"{ScriptAssemblies}{dll}.pdb", $"{hotUpdatePath}/{dll}.pdb.bytes", true); + } + + AssetDatabase.Refresh(); + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/FantasyStartup.cs.meta b/Editor/CoreEditor/Runtime/FantasyStartup.cs.meta new file mode 100644 index 0000000..abcd77d --- /dev/null +++ b/Editor/CoreEditor/Runtime/FantasyStartup.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 42156ba2865a4aa4a3e1e57b3ac9b984 +timeCreated: 1688276977 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs b/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs new file mode 100644 index 0000000..155d0f8 --- /dev/null +++ b/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs @@ -0,0 +1,52 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Fantasy +{ + public class LinkXmlGenerator + { + private const string LinkPath = "Assets/link.xml"; + // 在Unity编辑器中运行该方法来生成link.xml文件 + [UnityEditor.MenuItem("Fantasy/Generate link.xml")] + public static void GenerateLinkXml() + { + using (var writer = new StreamWriter("Assets/link.xml")) + { + writer.WriteLine(""); + + foreach (var assembly in FantasySettingsScriptableObject.Instance.includeAssembly) + { + GenerateLinkXml(writer, assembly, LinkPath); + Debug.Log($"{assembly} Link generation completed"); + } + + if (FantasySettingsScriptableObject.Instance?.linkAssemblyDefinitions != null) + { + foreach (var linkAssembly in FantasySettingsScriptableObject.Instance.linkAssemblyDefinitions) + { + GenerateLinkXml(writer, linkAssembly.name, LinkPath); + Debug.Log($"{linkAssembly.name} Link generation completed"); + } + } + writer.WriteLine(""); + } + + AssetDatabase.Refresh(); + Debug.Log("link.xml generated successfully!"); + } + + private static void GenerateLinkXml(StreamWriter writer, string assemblyName, string outputPath) + { + var assembly = System.Reflection.Assembly.Load(assemblyName); + var types = assembly.GetTypes(); + writer.WriteLine($" "); + foreach (var type in types) + { + var typeName = type.FullName.Replace('<', '+').Replace('>', '+'); + writer.WriteLine($" "); + } + writer.WriteLine(" "); + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs.meta b/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs.meta new file mode 100644 index 0000000..dbab220 --- /dev/null +++ b/Editor/CoreEditor/Runtime/LinkXmlGenerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cda4c9403de946df9c31654416193a21 +timeCreated: 1722743236 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings.meta b/Editor/CoreEditor/Runtime/Settings.meta new file mode 100644 index 0000000..6b097c8 --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3a6997d946f3400e8c423fe1b9245f65 +timeCreated: 1688277110 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs b/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs new file mode 100644 index 0000000..4c85dc7 --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs @@ -0,0 +1,13 @@ +using UnityEditor; + +namespace Fantasy +{ + public class FantasySettings + { + [MenuItem("Fantasy/Fantasy Settings")] + public static void OpenFantasySettings() + { + SettingsService.OpenProjectSettings("Project/Fantasy Settings"); + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs.meta b/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs.meta new file mode 100644 index 0000000..852e825 --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 977a7c172c30403da60286ba39b7bc72 +timeCreated: 1686913667 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs b/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs new file mode 100644 index 0000000..11ae01c --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using UnityEngine.UIElements; + +namespace Fantasy +{ + public class FantasySettingsProvider : SettingsProvider + { + private SerializedObject _serializedObject; + private SerializedProperty _autoCopyAssembly; + private SerializedProperty _hotUpdatePath; + private SerializedProperty _hotUpdateAssemblyDefinitions; + private SerializedProperty _linkAssemblyDefinitions; + private SerializedProperty _includeAssembly; + public FantasySettingsProvider() : base("Project/Fantasy Settings", SettingsScope.Project) { } + + public override void OnActivate(string searchContext, VisualElement rootElement) + { + Init(); + base.OnActivate(searchContext, rootElement); + } + + public override void OnDeactivate() + { + base.OnDeactivate(); + FantasySettingsScriptableObject.Save(); + } + + private void Init() + { + _serializedObject?.Dispose(); + _serializedObject = new SerializedObject(FantasySettingsScriptableObject.Instance); + _autoCopyAssembly = _serializedObject.FindProperty("autoCopyAssembly"); + _hotUpdatePath = _serializedObject.FindProperty("hotUpdatePath"); + _hotUpdateAssemblyDefinitions = _serializedObject.FindProperty("hotUpdateAssemblyDefinitions"); + _linkAssemblyDefinitions = _serializedObject.FindProperty("linkAssemblyDefinitions"); + _includeAssembly = _serializedObject.FindProperty("includeAssembly"); + } + + public override void OnGUI(string searchContext) + { + if (_serializedObject == null || !_serializedObject.targetObject) + { + Init(); + } + + using (CreateSettingsWindowGUIScope()) + { + _serializedObject!.Update(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(_autoCopyAssembly); + EditorGUILayout.PropertyField(_hotUpdatePath); + EditorGUILayout.PropertyField(_hotUpdateAssemblyDefinitions); + EditorGUILayout.PropertyField(_includeAssembly); + EditorGUILayout.PropertyField(_linkAssemblyDefinitions); + // EditorGUILayout.HelpBox("默认包括Fantasy.Unity,所以不需要再次指定。", MessageType.Info); + + if (GUILayout.Button("GenerateLinkXml")) + { + LinkXmlGenerator.GenerateLinkXml(); + } + + if (EditorGUI.EndChangeCheck()) + { + _serializedObject.ApplyModifiedProperties(); + FantasySettingsScriptableObject.Save(); + EditorApplication.RepaintHierarchyWindow(); + } + + base.OnGUI(searchContext); + } + } + + private IDisposable CreateSettingsWindowGUIScope() + { + var unityEditorAssembly = System.Reflection.Assembly.GetAssembly(typeof(EditorWindow)); + var type = unityEditorAssembly.GetType("UnityEditor.SettingsWindow+GUIScope"); + return Activator.CreateInstance(type) as IDisposable; + } + + static FantasySettingsProvider _provider; + + [SettingsProvider] + public static SettingsProvider CreateMyCustomSettingsProvider() + { + if (FantasySettingsScriptableObject.Instance && _provider == null) + { + _provider = new FantasySettingsProvider(); + using (var so = new SerializedObject(FantasySettingsScriptableObject.Instance)) + { + _provider.keywords = GetSearchKeywordsFromSerializedObject(so); + } + } + return _provider; + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs.meta b/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs.meta new file mode 100644 index 0000000..72e475d --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettingsProvider.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 047b2f13e73f413fa000bf7be979fb4a +timeCreated: 1688380387 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs b/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs new file mode 100644 index 0000000..5d03955 --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs @@ -0,0 +1,25 @@ +using UnityEditor; +using UnityEditor.Compilation; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Fantasy +{ + [ScriptableObjectPath("ProjectSettings/FantasySettings.asset")] + public class FantasySettingsScriptableObject : ScriptableObjectSingleton, ISerializationCallbackReceiver + { + [FormerlySerializedAs("AutoCopyAssembly")] [Header("自动拷贝程序集到HotUpdatePath目录中")] + public bool autoCopyAssembly = false; + [FormerlySerializedAs("HotUpdatePath")] [Header("HotUpdate目录(Unity编译后会把所有HotUpdate程序集Copy一份到这个目录下)")] + public string hotUpdatePath; + [FormerlySerializedAs("HotUpdateAssemblyDefinitions")] [Header("HotUpdate程序集")] + public AssemblyDefinitionAsset[] hotUpdateAssemblyDefinitions; + [FormerlySerializedAs("LinkAssemblyDefinitions")] [Header("指定要生成Link.xml的程序集")] + public AssemblyDefinitionAsset[] linkAssemblyDefinitions; + [FormerlySerializedAs("IncludeAssembly")] [Header("生成Link.xml时候默认包含的程序集")] + public string[] includeAssembly = new[] { "Assembly-CSharp", "Fantasy.Unity" }; + public void OnBeforeSerialize() { } + public void OnAfterDeserialize() { } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta b/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta new file mode 100644 index 0000000..b5bae5a --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 27a37e930ca3454fb57bc895f50d2106 +timeCreated: 1688277120 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs b/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs new file mode 100644 index 0000000..6206676 --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +// ReSharper disable AssignNullToNotNullAttribute + +namespace Fantasy +{ + public class ScriptableObjectSingleton : ScriptableObject where T : ScriptableObject + { + private static T _instance; + + public static T Instance + { + get + { + if (_instance == null) + { + _instance = Load(); + } + + return _instance; + } + } + + private static T Load() + { + var scriptableObjectPath = GetScriptableObjectPath(); + + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + return null; + } + + var loadSerializedFileAndForget = InternalEditorUtility.LoadSerializedFileAndForget(scriptableObjectPath); + + if (loadSerializedFileAndForget.Length <= 0) + { + return CreateInstance(); + } + + return loadSerializedFileAndForget[0] as T; + } + + public static void Save(bool saveAsText = true) + { + if (_instance == null) + { + Debug.LogError("Cannot save ScriptableObjectSingleton: no instance!"); + return; + } + + var scriptableObjectPath = GetScriptableObjectPath(); + + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + return; + } + + var directoryName = Path.GetDirectoryName(scriptableObjectPath); + + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + + UnityEngine.Object[] obj = { _instance }; + InternalEditorUtility.SaveToSerializedFileAndForget(obj, scriptableObjectPath, saveAsText); + } + + private static string GetScriptableObjectPath() + { + var scriptableObjectPathAttribute = typeof(T).GetCustomAttribute(typeof(ScriptableObjectPathAttribute)) as ScriptableObjectPathAttribute; + return scriptableObjectPathAttribute?.ScriptableObjectPath; + } + } + + [AttributeUsage(AttributeTargets.Class, Inherited = false)] + public class ScriptableObjectPathAttribute : Attribute + { + internal readonly string ScriptableObjectPath; + + public ScriptableObjectPathAttribute(string scriptableObjectPath) + { + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + throw new ArgumentException("Invalid relative path (it is empty)"); + } + + if (scriptableObjectPath[0] == '/') + { + scriptableObjectPath = scriptableObjectPath.Substring(1); + } + + ScriptableObjectPath = scriptableObjectPath; + } + } +} \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs.meta b/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs.meta new file mode 100644 index 0000000..5105c6f --- /dev/null +++ b/Editor/CoreEditor/Runtime/Settings/ScriptableObjectSingleton.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3c77f5208dc14542ae7497d59321ef76 +timeCreated: 1688278016 \ No newline at end of file diff --git a/Editor/CoreEditor/Runtime/WSocket.meta b/Editor/CoreEditor/Runtime/WSocket.meta new file mode 100644 index 0000000..21883b6 --- /dev/null +++ b/Editor/CoreEditor/Runtime/WSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9e5c7d1436ec414fa3f69a23aaafc3b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs b/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs new file mode 100644 index 0000000..0313b0e --- /dev/null +++ b/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs @@ -0,0 +1,229 @@ +using UnityEngine; +using UnityEditor; +using UnityEngine.Networking; +using System.IO; +using System; + +namespace UnityWebSocket.Editor +{ + internal class SettingsWindow : EditorWindow + { + static SettingsWindow window = null; + [MenuItem("Tools/UnityWebSocket", priority = 100)] + internal static void Open() + { + if (window != null) + { + window.Close(); + } + + window = GetWindow(true, "UnityWebSocket"); + window.minSize = window.maxSize = new Vector2(600, 310); + window.Show(); + window.BeginCheck(); + } + + private void OnGUI() + { + DrawLogo(); + DrawVersion(); + DrawSeparator(80); + DrawSeparator(186); + DrawHelper(); + DrawFooter(); + } + + Texture2D logoTex = null; + private void DrawLogo() + { + if (logoTex == null) + { + logoTex = new Texture2D(66, 66); + logoTex.LoadImage(Convert.FromBase64String(LOGO_BASE64.VALUE)); + for (int i = 0; i < 66; i++) for (int j = 0; j < 15; j++) logoTex.SetPixel(i, j, Color.clear); + logoTex.Apply(); + } + + var logoPos = new Rect(10, 10, 66, 66); + GUI.DrawTexture(logoPos, logoTex); + var title = "UnityWebSocket"; + var titlePos = new Rect(80, 20, 500, 50); + GUI.Label(titlePos, title, TextStyle(24)); + } + + private void DrawSeparator(int y) + { + EditorGUI.DrawRect(new Rect(10, y, 580, 1), Color.white * 0.5f); + } + + private GUIStyle TextStyle(int fontSize = 10, TextAnchor alignment = TextAnchor.UpperLeft, float alpha = 0.85f) + { + var style = new GUIStyle(); + style.fontSize = fontSize; + style.normal.textColor = (EditorGUIUtility.isProSkin ? Color.white : Color.black) * alpha; + style.alignment = alignment; + style.richText = true; + return style; + } + + private void DrawVersion() + { + GUI.Label(new Rect(440, 10, 150, 10), "Current Version: " + Settings.VERSION, TextStyle(alignment: TextAnchor.MiddleLeft)); + if (string.IsNullOrEmpty(latestVersion)) + { + GUI.Label(new Rect(440, 30, 150, 10), "Checking for Updates...", TextStyle(alignment: TextAnchor.MiddleLeft)); + } + else if (latestVersion == "unknown") + { + + } + else + { + GUI.Label(new Rect(440, 30, 150, 10), "Latest Version: " + latestVersion, TextStyle(alignment: TextAnchor.MiddleLeft)); + if (Settings.VERSION == latestVersion) + { + if (GUI.Button(new Rect(440, 50, 150, 18), "Check Update")) + { + latestVersion = ""; + changeLog = ""; + BeginCheck(); + } + } + else + { + if (GUI.Button(new Rect(440, 50, 150, 18), "Update to | " + latestVersion)) + { + ShowUpdateDialog(); + } + } + } + } + + private void ShowUpdateDialog() + { + var isOK = EditorUtility.DisplayDialog("UnityWebSocket", + "Update UnityWebSocket now?\n" + changeLog, + "Update Now", "Cancel"); + + if (isOK) + { + UpdateVersion(); + } + } + + private void UpdateVersion() + { + Application.OpenURL(Settings.GITHUB + "/releases"); + } + + private void DrawHelper() + { + GUI.Label(new Rect(330, 200, 100, 18), "GitHub:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 200, 150, 18), "UnityWebSocket")) + { + Application.OpenURL(Settings.GITHUB); + } + + GUI.Label(new Rect(330, 225, 100, 18), "Report:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 225, 150, 18), "Report an Issue")) + { + Application.OpenURL(Settings.GITHUB + "/issues/new"); + } + + GUI.Label(new Rect(330, 250, 100, 18), "Email:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 250, 150, 18), Settings.EMAIL)) + { + var uri = new Uri(string.Format("mailto:{0}?subject={1}", Settings.EMAIL, "UnityWebSocket Feedback")); + Application.OpenURL(uri.AbsoluteUri); + } + + GUI.Label(new Rect(330, 275, 100, 18), "QQ群:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 275, 150, 18), Settings.QQ_GROUP)) + { + Application.OpenURL(Settings.QQ_GROUP_LINK); + } + } + + private void DrawFooter() + { + EditorGUI.DropShadowLabel(new Rect(10, 230, 400, 20), "Developed by " + Settings.AUHTOR); + EditorGUI.DropShadowLabel(new Rect(10, 250, 400, 20), "All rights reserved"); + } + + UnityWebRequest req; + string changeLog = ""; + string latestVersion = ""; + void BeginCheck() + { + EditorApplication.update -= VersionCheckUpdate; + EditorApplication.update += VersionCheckUpdate; + + req = UnityWebRequest.Get(Settings.GITHUB + "/releases/latest"); + req.SendWebRequest(); + } + + private void VersionCheckUpdate() + { +#if UNITY_2020_3_OR_NEWER + if (req == null + || req.result == UnityWebRequest.Result.ConnectionError + || req.result == UnityWebRequest.Result.DataProcessingError + || req.result == UnityWebRequest.Result.ProtocolError) +#elif UNITY_2018_1_OR_NEWER + if (req == null || req.isNetworkError || req.isHttpError) +#else + if (req == null || req.isError) +#endif + { + EditorApplication.update -= VersionCheckUpdate; + latestVersion = "unknown"; + return; + } + + if (req.isDone) + { + EditorApplication.update -= VersionCheckUpdate; + latestVersion = req.url.Substring(req.url.LastIndexOf("/") + 1).TrimStart('v'); + + if (Settings.VERSION != latestVersion) + { + var text = req.downloadHandler.text; + var st = text.IndexOf("content=\"" + latestVersion); + st = st > 0 ? text.IndexOf("\n", st) : -1; + var end = st > 0 ? text.IndexOf("\" />", st) : -1; + if (st > 0 && end > st) + { + changeLog = text.Substring(st + 1, end - st - 1).Trim(); + changeLog = changeLog.Replace("\r", ""); + changeLog = changeLog.Replace("\n", "\n- "); + changeLog = "\nCHANGE LOG: \n- " + changeLog + "\n"; + } + } + + Repaint(); + } + } + } + + internal static class LOGO_BASE64 + { + internal const string VALUE = "iVBORw0KGgoAAAANSUhEUgAAAEIAAABCCAMAAADUivDaAAAAq1BMVEUAAABKmtcvjtYzl" + + "9szmNszl9syl9k0mNs0mNwzmNs0mNszl9szl9s0mNs0mNwzmNw0mNwyltk0mNw0mNwzl9s0mNsymNs0mNszmNwzmNwzm" + + "NszmNs0mNwzl9w0mNwzmNw0mNs0mNs0mNwzl9wzmNs0mNwzmNs0mNwzl90zmNszmNszl9szmNsxmNszmNszmNw0mNwzm" + + "Nw0mNs2neM4pe41mt43ouo2oOY5qfM+UHlaAAAAMnRSTlMAAwXN3sgI+/069MSCK6M/MA74h9qfFHB8STWMJ9OS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GULvA0g4UFsb4VA0hAFcyo6cgLsAoT7uUtGAH5wQKQle0wuLyxLTaNyJEYwxw4wSljLK1TP8CAaOyhBMMEsj" + + "OBoXgo7VGElFkSWL+vef1RF2YNXeRWYzQBTpkhC8KaZHhuIogArkQLKClBZjU26B2IZgGz+cpZkHl8g3fYUaW/YP2kb2" + + "M/V97JY/vZN859n+QmO7XtC9Bf2jAAAAABJRU5ErkJggg=="; + } +} diff --git a/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs.meta b/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs.meta new file mode 100644 index 0000000..7412468 --- /dev/null +++ b/Editor/CoreEditor/Runtime/WSocket/SettingsWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 902614e06186a482f9e816e1d1984547 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime.meta b/Runtime/CoreRuntime.meta new file mode 100644 index 0000000..ded1d9b --- /dev/null +++ b/Runtime/CoreRuntime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dcbd0e41955f82b45bab54ebc1183deb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core.meta b/Runtime/CoreRuntime/Core.meta new file mode 100644 index 0000000..112dbca --- /dev/null +++ b/Runtime/CoreRuntime/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4e4623e6f2b7ffd41b068edd3c9568d9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Assembly.meta b/Runtime/CoreRuntime/Core/Assembly.meta new file mode 100644 index 0000000..e0bc296 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5006194ae42edaa4bb33cb6172c123ab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs b/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs new file mode 100644 index 0000000..3957539 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Fantasy.DataStructure.Collection; + +// ReSharper disable CollectionNeverQueried.Global +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Assembly +{ + /// + /// AssemblyInfo提供有关程序集和类型的信息 + /// + public sealed class AssemblyInfo + { + /// + /// 唯一标识 + /// + public readonly long AssemblyIdentity; + /// + /// 获取或设置与此程序集相关联的 实例。 + /// + public System.Reflection.Assembly Assembly { get; private set; } + /// + /// 程序集类型集合,获取一个列表,包含从程序集加载的所有类型。 + /// + public readonly List AssemblyTypeList = new List(); + /// + /// 程序集类型分组集合,获取一个分组列表,将接口类型映射到实现这些接口的类型。 + /// + public readonly OneToManyList AssemblyTypeGroupList = new OneToManyList(); + + /// + /// 初始化 类的新实例。 + /// + /// + public AssemblyInfo(long assemblyIdentity) + { + AssemblyIdentity = assemblyIdentity; + } + + /// + /// 从指定的程序集加载类型信息并进行分类。 + /// + /// 要加载信息的程序集。 + public void Load(System.Reflection.Assembly assembly) + { + Assembly = assembly; + var assemblyTypes = assembly.GetTypes().ToList(); + + foreach (var type in assemblyTypes) + { + if (type.IsAbstract || type.IsInterface) + { + continue; + } + + var interfaces = type.GetInterfaces(); + + foreach (var interfaceType in interfaces) + { + AssemblyTypeGroupList.Add(interfaceType, type); + } + } + + AssemblyTypeList.AddRange(assemblyTypes); + } + + /// + /// 重新加载程序集的类型信息。 + /// + /// + public void ReLoad(System.Reflection.Assembly assembly) + { + Unload(); + Load(assembly); + } + + /// + /// 卸载程序集的类型信息。 + /// + public void Unload() + { + AssemblyTypeList.Clear(); + AssemblyTypeGroupList.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs.meta b/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs.meta new file mode 100644 index 0000000..f1bb2d8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c962fd73de88d64fa9d1ab97ed270b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs b/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs new file mode 100644 index 0000000..deb9da6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs @@ -0,0 +1,285 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using Fantasy.Async; +using Fantasy.Helper; +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8603 +#pragma warning disable CS8618 +namespace Fantasy.Assembly +{ + /// + /// 管理程序集加载和卸载的帮助类。 + /// + public static class AssemblySystem + { +#if FANTASY_WEBGL + private static readonly List AssemblySystems = new List(); + private static readonly Dictionary AssemblyList = new Dictionary(); +#else + private static readonly ConcurrentQueue AssemblySystems = new ConcurrentQueue(); + private static readonly ConcurrentDictionary AssemblyList = new ConcurrentDictionary(); +#endif + /// + /// 初始化 AssemblySystem。(仅限内部) + /// + /// + internal static async FTask InnerInitialize(params System.Reflection.Assembly[] assemblies) + { + await LoadAssembly(typeof(AssemblySystem).Assembly); + foreach (var assembly in assemblies) + { + await LoadAssembly(assembly); + } + } + + /// + /// 加载指定的程序集,并触发相应的事件。 + /// + /// 要加载的程序集。 + /// 如果当前Domain中已经存在同名的Assembly,使用Domain中的程序集。 + public static async FTask LoadAssembly(System.Reflection.Assembly assembly, bool isCurrentDomain = true) + { + if (isCurrentDomain) + { + var currentDomainAssemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + var currentAssembly = currentDomainAssemblies.FirstOrDefault(d => d.GetName().Name == assembly.GetName().Name); + if (currentAssembly != null) + { + assembly = currentAssembly; + } + } + + var assemblyIdentity = AssemblyIdentity(assembly); + + if (AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + assemblyInfo.ReLoad(assembly); + foreach (var assemblySystem in AssemblySystems) + { + await assemblySystem.ReLoad(assemblyIdentity); + } + } + else + { + assemblyInfo = new AssemblyInfo(assemblyIdentity); + assemblyInfo.Load(assembly); + AssemblyList.TryAdd(assemblyIdentity, assemblyInfo); + foreach (var assemblySystem in AssemblySystems) + { + await assemblySystem.Load(assemblyIdentity); + } + } + } + + /// + /// 卸载程序集 + /// + /// + public static async FTask UnLoadAssembly(System.Reflection.Assembly assembly) + { + var assemblyIdentity = AssemblyIdentity(assembly); + + if (!AssemblyList.Remove(assemblyIdentity, out var assemblyInfo)) + { + return; + } + + assemblyInfo.Unload(); + foreach (var assemblySystem in AssemblySystems) + { + await assemblySystem.OnUnLoad(assemblyIdentity); + } + } + + /// + /// 将AssemblySystem接口的object注册到程序集管理中心 + /// + /// + public static async FTask Register(object obj) + { + if (obj is not IAssembly assemblySystem) + { + return; + } +#if FANTASY_WEBGL + AssemblySystems.Add(assemblySystem); +#else + AssemblySystems.Enqueue(assemblySystem); +#endif + foreach (var (assemblyIdentity, _) in AssemblyList) + { + await assemblySystem.Load(assemblyIdentity); + } + } + + /// + /// 程序集管理中心卸载注册的Load、ReLoad、UnLoad的接口 + /// + /// + public static void UnRegister(object obj) + { + if (obj is not IAssembly assemblySystem) + { + return; + } +#if FANTASY_WEBGL + AssemblySystems.Remove(assemblySystem); +#else + var count = AssemblySystems.Count; + + for (var i = 0; i < count; i++) + { + if (!AssemblySystems.TryDequeue(out var removeAssemblySystem)) + { + continue; + } + + if (removeAssemblySystem == assemblySystem) + { + break; + } + + AssemblySystems.Enqueue(removeAssemblySystem); + } +#endif + } + + /// + /// 获取所有已加载程序集中的所有类型。 + /// + /// 所有已加载程序集中的类型。 + public static IEnumerable ForEach() + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + foreach (var type in assemblyInfo.AssemblyTypeList) + { + yield return type; + } + } + } + + /// + /// 获取指定程序集中的所有类型。 + /// + /// 程序集唯一标识。 + /// 指定程序集中的类型。 + public static IEnumerable ForEach(long assemblyIdentity) + { + if (!AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + yield break; + } + + foreach (var type in assemblyInfo.AssemblyTypeList) + { + yield return type; + } + } + + /// + /// 获取所有已加载程序集中实现指定类型的所有类型。 + /// + /// 要查找的基类或接口类型。 + /// 所有已加载程序集中实现指定类型的类型。 + public static IEnumerable ForEach(Type findType) + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + if (!assemblyInfo.AssemblyTypeGroupList.TryGetValue(findType, out var assemblyLoad)) + { + continue; + } + + foreach (var type in assemblyLoad) + { + yield return type; + } + } + } + + /// + /// 获取指定程序集中实现指定类型的所有类型。 + /// + /// 程序集唯一标识。 + /// 要查找的基类或接口类型。 + /// 指定程序集中实现指定类型的类型。 + public static IEnumerable ForEach(long assemblyIdentity, Type findType) + { + if (!AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + yield break; + } + + if (!assemblyInfo.AssemblyTypeGroupList.TryGetValue(findType, out var assemblyLoad)) + { + yield break; + } + + foreach (var type in assemblyLoad) + { + yield return type; + } + } + + /// + /// 获取指定程序集的实例。 + /// + /// 程序集名称。 + /// 指定程序集的实例,如果未加载则返回 null。 + public static System.Reflection.Assembly GetAssembly(long assemblyIdentity) + { + return !AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo) ? null : assemblyInfo.Assembly; + } + + /// + /// 获取当前框架注册的Assembly + /// + /// + public static IEnumerable ForEachAssembly + { + get + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + yield return assemblyInfo.Assembly; + } + } + } + + /// + /// 根据Assembly的强命名计算唯一标识。 + /// + /// + /// + private static long AssemblyIdentity(System.Reflection.Assembly assembly) + { + return HashCodeHelper.ComputeHash64(assembly.GetName().Name); + } + + /// + /// 释放资源,卸载所有加载的程序集。 + /// + public static void Dispose() + { + DisposeAsync().Coroutine(); + } + + private static async FTask DisposeAsync() + { + foreach (var (_, assemblyInfo) in AssemblyList.ToArray()) + { + await UnLoadAssembly(assemblyInfo.Assembly); + } + + AssemblyList.Clear(); + AssemblySystems.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs.meta b/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs.meta new file mode 100644 index 0000000..0252da6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/AssemblySystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 533740363a43b98499d20ddab704ae7b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs b/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs new file mode 100644 index 0000000..185e037 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs @@ -0,0 +1,27 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Assembly +{ + /// + /// 实现这个接口、会再程序集首次加载、卸载、重载的时候调用 + /// + public interface IAssembly : IDisposable + { + /// + /// 程序集加载时调用 + /// + /// 程序集标识 + public FTask Load(long assemblyIdentity); + /// + /// 程序集重新加载的时候调用 + /// + /// 程序集标识 + public FTask ReLoad(long assemblyIdentity); + /// + /// 卸载的时候调用 + /// + /// 程序集标识 + public FTask OnUnLoad(long assemblyIdentity); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs.meta b/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs.meta new file mode 100644 index 0000000..16313d1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Assembly/IAssembly.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2265dda8f756ced42b346d101b5c431c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Benchmark.meta b/Runtime/CoreRuntime/Core/Benchmark.meta new file mode 100644 index 0000000..ca50a8f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Benchmark.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9672ac65f515574a8e888c0baa4f5a2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Benchmark/Handler.meta b/Runtime/CoreRuntime/Core/Benchmark/Handler.meta new file mode 100644 index 0000000..92992e6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Benchmark/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dcf9f758978488e4d94d0aec6c151e3f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs b/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs new file mode 100644 index 0000000..8532547 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs @@ -0,0 +1,25 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Benchmark.Handler; + +/// +/// BenchmarkRequestHandler +/// +public sealed class BenchmarkRequestHandler : MessageRPC +{ + /// + /// Run方法 + /// + /// + /// + /// + /// + protected override async FTask Run(Session session, BenchmarkRequest request, BenchmarkResponse response, Action reply) + { + await FTask.CompletedTask; + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta new file mode 100644 index 0000000..8288de2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0584f8f7232c13e4a9043b14fcb00ba6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataBase.meta b/Runtime/CoreRuntime/Core/DataBase.meta new file mode 100644 index 0000000..ef8664a --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 158dbd1e6090fc6408b93c074e56a894 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs b/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs new file mode 100644 index 0000000..2fb03ec --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs @@ -0,0 +1,20 @@ +// ReSharper disable CheckNamespace +// ReSharper disable InconsistentNaming +#if FANTASY_NET +namespace Fantasy.DataBase; + +/// +/// 数据库类型 +/// +public enum DataBaseType +{ + /// + /// 默认 + /// + None = 0, + /// + /// MongoDB + /// + MongoDB = 1 +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs.meta b/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs.meta new file mode 100644 index 0000000..ad9a88d --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/DataBaseType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a76811d05f24f5449bdc0fe27e6f7b8e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs b/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs new file mode 100644 index 0000000..6a2fe8b --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs @@ -0,0 +1,210 @@ +#if FANTASY_NET +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using Fantasy.Async; +using Fantasy.Entitas; +using MongoDB.Driver; +// ReSharper disable InconsistentNaming +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +#pragma warning disable CS8625 + +namespace Fantasy.DataBase +{ + /// + /// 数据库设置助手 + /// + public static class DataBaseSetting + { + /// + /// 初始化自定义委托,当设置了这个委托后,就不会自动创建MongoClient,需要自己在委托里创建MongoClient。 + /// + public static Func? MongoDBCustomInitialize; + } + + /// + /// MongoDB自定义连接参数 + /// + public sealed class DataBaseCustomConfig + { + /// + /// 当前Scene + /// + public Scene Scene; + /// + /// 连接字符串 + /// + public string ConnectionString; + /// + /// 数据库名字 + /// + public string DBName; + } + + /// + /// 表示用于执行各种数据库操作的数据库接口。 + /// + public interface IDataBase : IDisposable + { + /// + /// 获得当前数据的类型 + /// + public DataBaseType GetDataBaseType { get;} + /// + /// 获得对应数据的操作实例 + /// + /// 如MongoDB就是IMongoDatabase + public object GetDataBaseInstance { get;} + /// + /// 初始化数据库连接。 + /// + IDataBase Initialize(Scene scene, string connectionString, string dbName); + /// + /// 在指定的集合中检索类型 的实体数量。 + /// + FTask Count(string collection = null) where T : Entity; + /// + /// 在指定的集合中检索满足给定筛选条件的类型 的实体数量。 + /// + FTask Count(Expression> filter, string collection = null) where T : Entity; + /// + /// 检查指定集合中是否存在类型 的实体。 + /// + FTask Exist(string collection = null) where T : Entity; + /// + /// 检查指定集合中是否存在满足给定筛选条件的类型 的实体。 + /// + FTask Exist(Expression> filter, string collection = null) where T : Entity; + /// + /// 从指定集合中检索指定 ID 的类型 的实体,不锁定。 + /// + FTask QueryNotLock(long id, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 从指定集合中检索指定 ID 的类型 的实体。 + /// + FTask Query(long id, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 按页查询满足给定筛选条件的类型 的实体数量和日期。 + /// + FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 按页查询满足给定筛选条件的类型 的实体数量和日期。 + /// + FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 分页查询指定集合中满足给定筛选条件的类型 的实体列表。 + /// + FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 分页查询指定集合中满足给定筛选条件的类型 的实体列表,仅返回指定列的数据。 + /// + FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表,按指定字段排序。 + /// + FTask> QueryByPageOrderBy(Expression> filter, int pageIndex, int pageSize, Expression> orderByExpression, bool isAsc = true, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 检索满足给定筛选条件的类型 的第一个实体,从指定集合中。 + /// + FTask First(Expression> filter, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 查询指定集合中满足给定 JSON 查询字符串的类型 的第一个实体,仅返回指定列的数据。 + /// + FTask First(string json, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表,按指定字段排序。 + /// + FTask> QueryOrderBy(Expression> filter, Expression> orderByExpression, bool isAsc = true, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表。 + /// + FTask> Query(Expression> filter, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 查询指定集合中满足给定筛选条件的类型 实体列表,仅返回指定字段的数据。 + /// + FTask> Query(Expression> filter, Expression>[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 查询指定 ID 的多个集合,将结果存储在给定的实体列表中。 + /// + FTask Query(long id, List collectionNames, List result, bool isDeserialize = false); + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表。 + /// + FTask> QueryJson(string json, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表,仅返回指定列的数据。 + /// + FTask> QueryJson(string json, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表,通过指定的任务 ID 进行标识。 + /// + FTask> QueryJson(long taskId, string json, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 查询指定集合中满足给定筛选条件的类型 实体列表,仅返回指定列的数据。 + /// + FTask> Query(Expression> filter, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity; + /// + /// 保存类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask Save(T entity, string collection = null) where T : Entity, new(); + /// + /// 保存一组实体到数据库中,根据实体列表的 ID 进行区分和存储。 + /// + FTask Save(long id, List entities); + /// + /// 通过事务会话将类型 实体保存到指定集合中,如果集合不存在将自动创建。 + /// + FTask Save(object transactionSession, T entity, string collection = null) where T : Entity; + /// + /// 向指定集合中插入一个类型 实体,如果集合不存在将自动创建。 + /// + FTask Insert(T entity, string collection = null) where T : Entity, new(); + /// + /// 批量插入一组类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask InsertBatch(IEnumerable list, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,批量插入一组类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask InsertBatch(object transactionSession, IEnumerable list, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,根据指定的 ID 从数据库中删除指定类型 实体。 + /// + FTask Remove(object transactionSession, long id, string collection = null) where T : Entity, new(); + /// + /// 根据指定的 ID 从数据库中删除指定类型 实体。 + /// + FTask Remove(long id, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,根据给定的筛选条件从数据库中删除指定类型 实体。 + /// + FTask Remove(long coroutineLockQueueKey, object transactionSession, Expression> filter, string collection = null) where T : Entity, new(); + /// + /// 根据给定的筛选条件从数据库中删除指定类型 实体。 + /// + FTask Remove(long coroutineLockQueueKey, Expression> filter, string collection = null) where T : Entity, new(); + /// + /// 根据给定的筛选条件计算指定集合中类型 实体某个属性的总和。 + /// + FTask Sum(Expression> filter, Expression> sumExpression, string collection = null) where T : Entity; + /// + /// 在指定的集合中创建索引,以提高类型 实体的查询性能。 + /// + FTask CreateIndex(string collection, params object[] keys) where T : Entity; + /// + /// 在默认集合中创建索引,以提高类型 实体的查询性能。 + /// + FTask CreateIndex(params object[] keys) where T : Entity; + /// + /// 创建指定类型 的数据库,用于存储实体。 + /// + FTask CreateDB() where T : Entity; + /// + /// 根据指定类型创建数据库,用于存储实体。 + /// + FTask CreateDB(Type type); + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs.meta b/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs.meta new file mode 100644 index 0000000..b01c0d5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/IDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1630d7e4e5e733d439ab42b7e57fee87 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs b/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs new file mode 100644 index 0000000..49948f4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs @@ -0,0 +1,1081 @@ +#if FANTASY_NET +using System.Linq.Expressions; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Helper; +using Fantasy.Serialize; +using MongoDB.Bson; +using MongoDB.Driver; +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.DataBase +{ + /// + /// 使用 MongoDB 数据库的实现。 + /// + public sealed class MongoDataBase : IDataBase + { + private const int DefaultTaskSize = 1024; + private Scene _scene; + private MongoClient _mongoClient; + private ISerialize _serializer; + private IMongoDatabase _mongoDatabase; + private CoroutineLock _dataBaseLock; + private readonly HashSet _collections = new HashSet(); + /// + /// 获得当前数据的类型 + /// + public DataBaseType GetDataBaseType { get; } = DataBaseType.MongoDB; + /// + /// 获得对应数据的操作实例 + /// + public object GetDataBaseInstance => _mongoDatabase; + /// + /// 初始化 MongoDB 数据库连接并记录所有集合名。 + /// + /// 场景对象。 + /// 数据库连接字符串。 + /// 数据库名称。 + /// 初始化后的数据库实例。 + public IDataBase Initialize(Scene scene, string connectionString, string dbName) + { + _scene = scene; + _mongoClient = DataBaseSetting.MongoDBCustomInitialize != null + ? DataBaseSetting.MongoDBCustomInitialize(new DataBaseCustomConfig() + { + Scene = scene, ConnectionString = connectionString, DBName = dbName + }) + : new MongoClient(connectionString); + _mongoDatabase = _mongoClient.GetDatabase(dbName); + _dataBaseLock = scene.CoroutineLockComponent.Create(GetType().TypeHandle.Value.ToInt64()); + // 记录所有集合名 + _collections.UnionWith(_mongoDatabase.ListCollectionNames().ToList()); + _serializer = SerializerManager.GetSerializer(FantasySerializerType.Bson); + return this; + } + + /// + /// 销毁释放资源。 + /// + public void Dispose() + { + // 优先释放协程锁。 + _dataBaseLock.Dispose(); + // 清理资源。 + _scene = null; + _serializer = null; + _mongoDatabase = null; + _dataBaseLock = null; + _collections.Clear(); + _mongoClient.Dispose(); + } + + #region Other + + /// + /// 对满足条件的文档中的某个数值字段进行求和操作。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 要对其进行求和的字段表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档中指定字段的求和结果。 + public async FTask Sum(Expression> filter, Expression> sumExpression, string collection = null) where T : Entity + { + var member = (MemberExpression)((UnaryExpression)sumExpression.Body).Operand; + var projection = new BsonDocument("_id", "null").Add("Result", new BsonDocument("$sum", $"${member.Member.Name}")); + var data = await GetCollection(collection).Aggregate().Match(filter).Group(projection).FirstOrDefaultAsync(); + return data == null ? 0 : Convert.ToInt64(data["Result"]); + } + + #endregion + + #region GetCollection + + /// + /// 获取指定集合中的 MongoDB 文档的 IMongoCollection 对象。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// IMongoCollection 对象。 + private IMongoCollection GetCollection(string collection = null) + { + return _mongoDatabase.GetCollection(collection ?? typeof(T).Name); + } + + /// + /// 获取指定集合中的 MongoDB 文档的 IMongoCollection 对象,其中实体类型为 Entity。 + /// + /// 集合名称。 + /// IMongoCollection 对象。 + private IMongoCollection GetCollection(string name) + { + return _mongoDatabase.GetCollection(name); + } + + #endregion + + #region Count + + /// + /// 统计指定集合中满足条件的文档数量。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档数量。 + public async FTask Count(string collection = null) where T : Entity + { + return await GetCollection(collection).CountDocumentsAsync(d => true); + } + + /// + /// 统计指定集合中满足条件的文档数量。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档数量。 + public async FTask Count(Expression> filter, string collection = null) where T : Entity + { + return await GetCollection(collection).CountDocumentsAsync(filter); + } + + #endregion + + #region Exist + + /// + /// 判断指定集合中是否存在文档。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 如果存在文档则返回 true,否则返回 false。 + public async FTask Exist(string collection = null) where T : Entity + { + return await Count(collection) > 0; + } + + /// + /// 判断指定集合中是否存在满足条件的文档。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 如果存在满足条件的文档则返回 true,否则返回 false。 + public async FTask Exist(Expression> filter, string collection = null) where T : Entity + { + return await Count(filter, collection) > 0; + } + + #endregion + + #region Query + + /// + /// 在不加数据库锁定的情况下,查询指定 ID 的文档。 + /// + /// 文档实体类型。 + /// 要查询的文档 ID。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 查询到的文档。 + public async FTask QueryNotLock(long id, bool isDeserialize = false, string collection = null) where T : Entity + { + var cursor = await GetCollection(collection).FindAsync(d => d.Id == id); + var v = await cursor.FirstOrDefaultAsync(); + + if (isDeserialize && v != null) + { + v.Deserialize(_scene); + } + + return v; + } + + /// + /// 查询指定 ID 的文档,并加数据库锁定以确保数据一致性。 + /// + /// 文档实体类型。 + /// 要查询的文档 ID。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 查询到的文档。 + public async FTask Query(long id, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(id)) + { + var cursor = await GetCollection(collection).FindAsync(d => d.Id == id); + var v = await cursor.FirstOrDefaultAsync(); + + if (isDeserialize && v != null) + { + v.Deserialize(_scene); + } + + return v; + } + } + + /// + /// 通过分页查询并返回满足条件的文档数量和日期列表(不加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档数量和日期列表。 + public async FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var count = await Count(filter); + var dates = await QueryByPage(filter, pageIndex, pageSize, isDeserialize, collection); + return ((int)count, dates); + } + } + + /// + /// 通过分页查询并返回满足条件的文档数量和日期列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档数量和日期列表。 + public async FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var count = await Count(filter); + var dates = await QueryByPage(filter, pageIndex, pageSize, cols, isDeserialize, collection); + return ((int)count, dates); + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表(不加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var list = await GetCollection(collection).Find(filter).Skip((pageIndex - 1) * pageSize) + .Limit(pageSize) + .ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + var list = await GetCollection(collection).Find(filter).Project(projection) + .Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表,并按指定表达式进行排序(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 排序表达式。 + /// 是否升序排序。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPageOrderBy(Expression> filter, int pageIndex, int pageSize, Expression> orderByExpression, bool isAsc = true, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + List list; + + if (isAsc) + { + list = await GetCollection(collection).Find(filter).SortBy(orderByExpression).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + } + else + { + list = await GetCollection(collection).Find(filter).SortByDescending(orderByExpression).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + } + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的第一个文档(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的第一个文档,如果未找到则为 null。 + public async FTask First(Expression> filter, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var cursor = await GetCollection(collection).FindAsync(filter); + var t = await cursor.FirstOrDefaultAsync(); + + if (isDeserialize && t != null) + { + t.Deserialize(_scene); + } + + return t; + } + } + + /// + /// 通过指定 JSON 格式查询并返回满足条件的第一个文档(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的第一个文档。 + public async FTask First(string json, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + var options = new FindOptions { Projection = projection }; + + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + + var cursor = await GetCollection(collection).FindAsync(filterDefinition, options); + var t = await cursor.FirstOrDefaultAsync(); + + if (isDeserialize && t != null) + { + t.Deserialize(_scene); + } + + return t; + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的文档列表,并按指定表达式进行排序(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 排序表达式。 + /// 是否升序排序。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryOrderBy(Expression> filter, Expression> orderByExpression, bool isAsc = true, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + List list; + + if (isAsc) + { + list = await GetCollection(collection).Find(filter).SortBy(orderByExpression).ToListAsync(); + } + else + { + list = await GetCollection(collection).Find(filter).SortByDescending(orderByExpression).ToListAsync(); + } + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> Query(Expression> filter, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var cursor = await GetCollection(collection).FindAsync(filter); + var list = await cursor.ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 根据指定 ID 加锁查询多个集合中的文档。 + /// + /// 文档 ID。 + /// 要查询的集合名称列表。 + /// 查询结果存储列表。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + public async FTask Query(long id, List? collectionNames, List result, bool isDeserialize = false) + { + using (await _dataBaseLock.Wait(id)) + { + if (collectionNames == null || collectionNames.Count == 0) + { + return; + } + + foreach (var collectionName in collectionNames) + { + var cursor = await GetCollection(collectionName).FindAsync(d => d.Id == id); + + var e = await cursor.FirstOrDefaultAsync(); + + if (e == null) + { + continue; + } + + if (isDeserialize) + { + e.Deserialize(_scene); + } + + result.Add(e); + } + } + } + + /// + /// 根据指定的 JSON 查询条件查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(string json, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + var cursor = await GetCollection(collection).FindAsync(filterDefinition); + var list = await cursor.ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 根据指定的 JSON 查询条件查询并返回满足条件的文档列表,并选择指定的列(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(string json, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + var options = new FindOptions { Projection = projection }; + + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + + var cursor = await GetCollection(collection).FindAsync(filterDefinition, options); + var list = await cursor.ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 根据指定的 JSON 查询条件和任务 ID 查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 任务 ID。 + /// JSON 查询条件。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(long taskId, string json, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(taskId)) + { + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + var cursor = await GetCollection(collection).FindAsync(filterDefinition); + var list = await cursor.ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 根据指定过滤条件查询并返回满足条件的文档列表,选择指定的列(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> Query(Expression> filter, string[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include("_id"); + + foreach (var t in cols) + { + projection = projection.Include(t); + } + + var list = await GetCollection(collection).Find(filter).Project(projection).ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + /// + /// 根据指定过滤条件查询并返回满足条件的文档列表,选择指定的列(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 要查询的列名称数组。 + /// 是否在查询后反序列化,执行反序列化后会自动将实体注册到框架系统中,并且能正常使用组件相关功能。 + /// 集合名称。 + /// + public async FTask> Query(Expression> filter, Expression>[] cols, bool isDeserialize = false, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include("_id"); + + foreach (var col in cols) + { + if (col.Body is not MemberExpression memberExpression) + { + throw new ArgumentException("Lambda expression must be a member access expression."); + } + + projection = projection.Include(memberExpression.Member.Name); + } + + var list = await GetCollection(collection).Find(filter).Project(projection).ToListAsync(); + + if (!isDeserialize || list is not { Count: > 0 }) + { + return list; + } + + foreach (var entity in list) + { + entity.Deserialize(_scene); + } + + return list; + } + } + + #endregion + + #region Save + + /// + /// 保存实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要保存的实体对象。 + /// 集合名称。 + public async FTask Save(object transactionSession, T? entity, string collection = null) where T : Entity + { + if (entity == null) + { + Log.Error($"save entity is null: {typeof(T).Name}"); + return; + } + + var clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(clone.Id)) + { + await GetCollection(collection).ReplaceOneAsync( + (IClientSessionHandle)transactionSession, d => d.Id == clone.Id, clone, + new ReplaceOptions { IsUpsert = true }); + } + } + + /// + /// 保存实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 要保存的实体对象。 + /// 集合名称。 + public async FTask Save(T? entity, string collection = null) where T : Entity, new() + { + if (entity == null) + { + Log.Error($"save entity is null: {typeof(T).Name}"); + + return; + } + + var clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(clone.Id)) + { + await GetCollection(collection).ReplaceOneAsync(d => d.Id == clone.Id, clone, new ReplaceOptions { IsUpsert = true }); + } + } + + /// + /// 保存实体对象到数据库(加锁)。 + /// + /// 保存的条件表达式。 + /// 实体类型。 + /// 集合名称。 + /// + public async FTask Save(Expression> filter, T? entity, string collection = null) where T : Entity, new() + { + if (entity == null) + { + Log.Error($"save entity is null: {typeof(T).Name}"); + return; + } + + T clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(clone.Id)) + { + await GetCollection(collection).ReplaceOneAsync(filter, clone, new ReplaceOptions { IsUpsert = true }); + } + } + + /// + /// 保存多个实体对象到数据库(加锁)。 + /// + /// 文档 ID。 + /// 要保存的实体对象列表。 + public async FTask Save(long id, List? entities) + { + if (entities == null || entities.Count == 0) + { + Log.Error("save entity is null"); + return; + } + + using var listPool = ListPool.Create(); + + foreach (var entity in entities) + { + listPool.Add(_serializer.Clone(entity)); + } + + using (await _dataBaseLock.Wait(id)) + { + foreach (var clone in listPool) + { + try + { + await GetCollection(clone.GetType().Name).ReplaceOneAsync(d => d.Id == clone.Id, clone, new ReplaceOptions { IsUpsert = true }); + } + catch (Exception e) + { + Log.Error($"Save List Entity Error: {clone.GetType().Name} {clone}\n{e}"); + } + } + } + } + + #endregion + + #region Insert + + /// + /// 插入单个实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 要插入的实体对象。 + /// 集合名称。 + public async FTask Insert(T? entity, string collection = null) where T : Entity, new() + { + if (entity == null) + { + Log.Error($"insert entity is null: {typeof(T).Name}"); + return; + } + + var clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(entity.Id)) + { + await GetCollection(collection).InsertOneAsync(clone); + } + } + + /// + /// 批量插入实体对象列表到数据库(加锁)。 + /// + /// 实体类型。 + /// 要插入的实体对象列表。 + /// 集合名称。 + public async FTask InsertBatch(IEnumerable list, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + await GetCollection(collection).InsertManyAsync(list); + } + } + + /// + /// 批量插入实体对象列表到数据库(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要插入的实体对象列表。 + /// 集合名称。 + public async FTask InsertBatch(object transactionSession, IEnumerable list, string collection = null) + where T : Entity, new() + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + await GetCollection(collection).InsertManyAsync((IClientSessionHandle)transactionSession, list); + } + } + + /// + /// 插入BsonDocument到数据库(加锁)。 + /// + /// + /// + /// + public async Task Insert(BsonDocument bsonDocument, long taskId) where T : Entity + { + using (await _dataBaseLock.Wait(taskId)) + { + await GetCollection(typeof(T).Name).InsertOneAsync(bsonDocument); + } + } + + #endregion + + #region Remove + + /// + /// 根据ID删除单个实体对象(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要删除的实体的ID。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(object transactionSession, long id, string collection = null) + where T : Entity, new() + { + using (await _dataBaseLock.Wait(id)) + { + var result = await GetCollection(collection) + .DeleteOneAsync((IClientSessionHandle)transactionSession, d => d.Id == id); + return result.DeletedCount; + } + } + + /// + /// 根据ID删除单个实体对象(加锁)。 + /// + /// 实体类型。 + /// 要删除的实体的ID。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long id, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(id)) + { + var result = await GetCollection(collection).DeleteOneAsync(d => d.Id == id); + return result.DeletedCount; + } + } + + /// + /// 根据ID和筛选条件删除多个实体对象(加锁)。 + /// + /// 实体类型。 + /// 异步锁Id。 + /// 事务会话对象。 + /// 筛选条件。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long coroutineLockQueueKey, object transactionSession, + Expression> filter, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(coroutineLockQueueKey)) + { + var result = await GetCollection(collection) + .DeleteManyAsync((IClientSessionHandle)transactionSession, filter); + return result.DeletedCount; + } + } + + /// + /// 根据ID和筛选条件删除多个实体对象(加锁)。 + /// + /// 实体类型。 + /// 异步锁Id。 + /// 筛选条件。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long coroutineLockQueueKey, Expression> filter, + string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(coroutineLockQueueKey)) + { + var result = await GetCollection(collection).DeleteManyAsync(filter); + return result.DeletedCount; + } + } + + #endregion + + #region Index + + /// + /// 创建数据库索引(加锁)。 + /// + /// + /// + /// + /// + /// 使用例子(可多个): + /// 1 : Builders.IndexKeys.Ascending(d=>d.Id) + /// 2 : Builders.IndexKeys.Descending(d=>d.Id).Ascending(d=>d.Name) + /// 3 : Builders.IndexKeys.Descending(d=>d.Id),Builders.IndexKeys.Descending(d=>d.Name) + /// + public async FTask CreateIndex(string collection, params object[]? keys) where T : Entity + { + if (keys == null || keys.Length <= 0) + { + return; + } + + var indexModels = new List>(); + + foreach (object key in keys) + { + IndexKeysDefinition indexKeysDefinition = (IndexKeysDefinition)key; + + indexModels.Add(new CreateIndexModel(indexKeysDefinition)); + } + + await GetCollection(collection).Indexes.CreateManyAsync(indexModels); + } + + /// + /// 创建数据库的索引(加锁)。 + /// + /// 实体类型。 + /// 索引键定义。 + public async FTask CreateIndex(params object[]? keys) where T : Entity + { + if (keys == null) + { + return; + } + + List> indexModels = new List>(); + + foreach (object key in keys) + { + IndexKeysDefinition indexKeysDefinition = (IndexKeysDefinition)key; + + indexModels.Add(new CreateIndexModel(indexKeysDefinition)); + } + + await GetCollection().Indexes.CreateManyAsync(indexModels); + } + + #endregion + + #region CreateDB + + /// + /// 创建数据库集合(如果不存在)。 + /// + /// 实体类型。 + public async FTask CreateDB() where T : Entity + { + // 已经存在数据库表 + string name = typeof(T).Name; + + if (_collections.Contains(name)) + { + return; + } + + await _mongoDatabase.CreateCollectionAsync(name); + + _collections.Add(name); + } + + /// + /// 创建数据库集合(如果不存在)。 + /// + /// 实体类型。 + public async FTask CreateDB(Type type) + { + string name = type.Name; + + if (_collections.Contains(name)) + { + return; + } + + await _mongoDatabase.CreateCollectionAsync(name); + + _collections.Add(name); + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs.meta b/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs.meta new file mode 100644 index 0000000..59139d7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/MongoDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 396ddd0da4230db44a504522fb7a19f1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataBase/World.cs b/Runtime/CoreRuntime/Core/DataBase/World.cs new file mode 100644 index 0000000..c53351f --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/World.cs @@ -0,0 +1,77 @@ +#pragma warning disable CS8603 // Possible null reference return. +#if FANTASY_NET +using Fantasy.Platform.Net; + +namespace Fantasy.DataBase +{ + /// + /// 表示一个游戏世界。 + /// + public sealed class World : IDisposable + { + /// + /// 获取游戏世界的唯一标识。 + /// + public byte Id { get; private init; } + /// + /// 获取游戏世界的数据库接口。 + /// + public IDataBase DataBase { get; private init; } + /// + /// 获取游戏世界的配置信息。 + /// + public WorldConfig Config => WorldConfigData.Instance.Get(Id); + + /// + /// 使用指定的配置信息创建一个游戏世界实例。 + /// + /// + /// + private World(Scene scene, byte worldConfigId) + { + Id = worldConfigId; + var worldConfig = Config; + var dbType = worldConfig.DbType.ToLower(); + + switch (dbType) + { + case "mongodb": + { + DataBase = new MongoDataBase(); + DataBase.Initialize(scene, worldConfig.DbConnection, worldConfig.DbName); + break; + } + default: + { + throw new Exception("No supported database"); + } + } + } + + /// + /// 创建一个指定唯一标识的游戏世界实例。 + /// + /// + /// 游戏世界的唯一标识。 + /// 游戏世界实例。 + internal static World Create(Scene scene, byte id) + { + if (!WorldConfigData.Instance.TryGet(id, out var worldConfigData)) + { + return null; + } + + return string.IsNullOrEmpty(worldConfigData.DbConnection) ? null : new World(scene, id); + } + + /// + /// 释放游戏世界资源。 + /// + public void Dispose() + { + DataBase.Dispose(); + } + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataBase/World.cs.meta b/Runtime/CoreRuntime/Core/DataBase/World.cs.meta new file mode 100644 index 0000000..8f7c0e1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataBase/World.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd87cec78544de449a1d55d76b07526f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure.meta b/Runtime/CoreRuntime/Core/DataStructure.meta new file mode 100644 index 0000000..79dff63 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ee2297376a867104f9df48c053f5324c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection.meta new file mode 100644 index 0000000..3923905 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9dfe758585a734d45a3b35ea954527e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs new file mode 100644 index 0000000..d80ec55 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using System.IO; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.DataStructure.Collection +{ + /// 环形缓存(自增式缓存,自动扩充、不会收缩缓存、所以不要用这个操作过大的IO流) + /// 1、环大小8192,溢出的会自动增加环的大小。 + /// 2、每个块都是一个环形缓存,当溢出的时候会自动添加到下一个环中。 + /// 3、当读取完成后用过的环会放在缓存中,不会销毁掉。 + /// + /// 自增式缓存类,继承自 Stream 和 IDisposable 接口。 + /// 环形缓存具有自动扩充的特性,但不会收缩,适用于操作不过大的 IO 流。 + /// + public sealed class CircularBuffer : Stream, IDisposable + { + private byte[] _lastBuffer; + /// + /// 环形缓存块的默认大小 + /// + public const int ChunkSize = 8192; + private readonly Queue _bufferCache = new Queue(); + private readonly Queue _bufferQueue = new Queue(); + /// + /// 获取或设置环形缓存的第一个索引位置 + /// + public int FirstIndex { get; set; } + /// + /// 获取或设置环形缓存的最后一个索引位置 + /// + public int LastIndex { get; set; } + /// + /// 获取环形缓存的总长度 + /// + public override long Length + { + get + { + if (_bufferQueue.Count == 0) + { + return 0; + } + + return (_bufferQueue.Count - 1) * ChunkSize + LastIndex - FirstIndex; + } + } + + /// + /// 获取环形缓存的第一个块 + /// + public byte[] First + { + get + { + if (_bufferQueue.Count == 0) + { + AddLast(); + } + + return _bufferQueue.Peek(); + } + } + + /// + /// 获取环形缓存的最后一个块 + /// + public byte[] Last + { + get + { + if (_bufferQueue.Count == 0) + { + AddLast(); + } + + return _lastBuffer; + } + } + /// + /// 向环形缓存中添加一个新的块 + /// + public void AddLast() + { + var buffer = _bufferCache.Count > 0 ? _bufferCache.Dequeue() : new byte[ChunkSize]; + _bufferQueue.Enqueue(buffer); + _lastBuffer = buffer; + } + /// + /// 从环形缓存中移除第一个块 + /// + public void RemoveFirst() + { + _bufferCache.Enqueue(_bufferQueue.Dequeue()); + } + + /// + /// 从流中读取指定数量的数据到缓存。 + /// + /// 源数据流。 + /// 要读取的字节数。 + public void Read(Stream stream, int count) + { + if (count > Length) + { + throw new Exception($"bufferList length < count, {Length} {count}"); + } + + var copyCount = 0; + while (copyCount < count) + { + var n = count - copyCount; + if (ChunkSize - FirstIndex > n) + { + stream.Write(First, FirstIndex, n); + FirstIndex += n; + copyCount += n; + } + else + { + stream.Write(First, FirstIndex, ChunkSize - FirstIndex); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + RemoveFirst(); + } + } + } + + /// + /// 从缓存中读取指定数量的数据到内存。 + /// + /// 目标内存。 + /// 要读取的字节数。 + public void Read(Memory memory, int count) + { + if (count > Length) + { + throw new Exception($"bufferList length < count, {Length} {count}"); + } + + var copyCount = 0; + while (copyCount < count) + { + var n = count - copyCount; + var asMemory = First.AsMemory(); + + if (ChunkSize - FirstIndex > n) + { + var slice = asMemory.Slice(FirstIndex, n); + slice.CopyTo(memory.Slice(copyCount, n)); + FirstIndex += n; + copyCount += n; + } + else + { + var length = ChunkSize - FirstIndex; + var slice = asMemory.Slice(FirstIndex, length); + slice.CopyTo(memory.Slice(copyCount, length)); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + RemoveFirst(); + } + } + } + + /// + /// 从自定义流中读取数据到指定的缓冲区。 + /// + /// 目标缓冲区,用于存储读取的数据。 + /// 目标缓冲区中的起始偏移量。 + /// 要读取的字节数。 + /// 实际读取的字节数。 + public override int Read(byte[] buffer, int offset, int count) + { + if (buffer.Length < offset + count) + { + throw new Exception($"buffer length < count, buffer length: {buffer.Length} {offset} {count}"); + } + + var length = Length; + if (length < count) + { + count = (int) length; + } + + var copyCount = 0; + + // 循环直到成功读取所需的字节数 + while (copyCount < count) + { + var copyLength = count - copyCount; + + if (ChunkSize - FirstIndex > copyLength) + { + // 将数据从当前块的缓冲区复制到目标缓冲区 + Array.Copy(First, FirstIndex, buffer, copyCount + offset, copyLength); + + FirstIndex += copyLength; + copyCount += copyLength; + continue; + } + + // 复制当前块中剩余的数据,并切换到下一个块 + Array.Copy(First, FirstIndex, buffer, copyCount + offset, ChunkSize - FirstIndex); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + + RemoveFirst(); + } + + return count; + } + + /// + /// 将数据从给定的字节数组写入流中。 + /// + /// 包含要写入的数据的字节数组。 + public void Write(byte[] buffer) + { + Write(buffer, 0, buffer.Length); + } + + /// + /// 将数据从给定的流写入流中。 + /// + /// 包含要写入的数据的流。 + public void Write(Stream stream) + { + var copyCount = 0; + var count = (int) (stream.Length - stream.Position); + + while (copyCount < count) + { + if (LastIndex == ChunkSize) + { + AddLast(); + LastIndex = 0; + } + + var n = count - copyCount; + + if (ChunkSize - LastIndex > n) + { + _ = stream.Read(Last, LastIndex, n); + LastIndex += count - copyCount; + copyCount += n; + } + else + { + _ = stream.Read(Last, LastIndex, ChunkSize - LastIndex); + copyCount += ChunkSize - LastIndex; + LastIndex = ChunkSize; + } + } + } + + /// + /// 将数据从给定的字节数组写入流中。 + /// + /// 包含要写入的数据的字节数组。 + /// 开始写入的缓冲区中的索引。 + /// 要写入的字节数。 + public override void Write(byte[] buffer, int offset, int count) + { + var copyCount = 0; + + while (copyCount < count) + { + if (ChunkSize == LastIndex) + { + AddLast(); + LastIndex = 0; + } + + var byteLength = count - copyCount; + + if (ChunkSize - LastIndex > byteLength) + { + Array.Copy(buffer, copyCount + offset, Last, LastIndex, byteLength); + LastIndex += byteLength; + copyCount += byteLength; + } + else + { + Array.Copy(buffer, copyCount + offset, Last, LastIndex, ChunkSize - LastIndex); + copyCount += ChunkSize - LastIndex; + LastIndex = ChunkSize; + } + } + } + + /// + /// 获取一个值,指示流是否支持读取操作。 + /// + public override bool CanRead { get; } = true; + /// + /// 获取一个值,指示流是否支持寻找操作。 + /// + public override bool CanSeek { get; } = false; + /// + /// 获取一个值,指示流是否支持写入操作。 + /// + public override bool CanWrite { get; } = true; + /// + /// 获取或设置流中的位置。 + /// + public override long Position { get; set; } + + /// + /// 刷新流(在此实现中引发未实现异常)。 + /// + public override void Flush() + { + throw new NotImplementedException(); + } + + /// + /// 在流中寻找特定位置(在此实现中引发未实现异常)。 + /// + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + /// + /// 设置流的长度(在此实现中引发未实现异常)。 + /// + public override void SetLength(long value) + { + throw new NotImplementedException(); + } + + /// + /// 释放 CustomStream 使用的所有资源。 + /// + public new void Dispose() + { + _bufferQueue.Clear(); + _lastBuffer = null; + FirstIndex = 0; + LastIndex = 0; + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs.meta new file mode 100644 index 0000000..1e6f91a --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/CircularBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edf0f604fb0ac08419b517354597a3a3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs new file mode 100644 index 0000000..e110a0b --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs @@ -0,0 +1,197 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 并发的一对多列表池,用于维护具有相同键的多个值的关联关系,实现了 接口。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyListPool : ConcurrentOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 创建的实例。 + public static ConcurrentOneToManyListPool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + // 清空实例的数据 + Clear(); + // 将实例返回到池中以便重用 + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 并发的一对多列表,用于维护具有相同键的多个值的关联关系。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyList : ConcurrentDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 初始化 类的新实例。 + /// + public ConcurrentOneToManyList() + { + } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public ConcurrentOneToManyList(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的列表是否包含指定值。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果列表包含值,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向指定键的列表中添加一个值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + + /// + /// 获取指定键的列表中的第一个值。 + /// + /// 要获取第一个值的键。 + /// 指定键的列表中的第一个值,如果不存在则为默认值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从指定键的列表中移除一个值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从字典中移除指定键以及其关联的列表。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryRemove(key, out var list)) return; + + Recycle(list); + } + + /// + /// 从队列中获取一个列表,如果队列为空则创建一个新的列表。 + /// + /// 获取的列表。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 将一个列表回收到队列中。 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前类的数据,包括从基类继承的数据以及自定义的数据队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta new file mode 100644 index 0000000..1f1bead --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d54ccbb980880d4491058a858d80bb7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs new file mode 100644 index 0000000..59c4367 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs @@ -0,0 +1,194 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 表示一个并发的一对多队列池,用于维护具有相同键的多个值的关联关系,实现了 接口。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyQueuePool : ConcurrentOneToManyQueue, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建并返回一个 的实例。 + /// + /// 创建的实例。 + public static ConcurrentOneToManyQueuePool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); + // 将实例返回到对象池中,以便重用 + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 表示一个并发的一对多队列,用于维护具有相同键的多个值的关联关系。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyQueue : ConcurrentDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public ConcurrentOneToManyQueue(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的队列是否包含指定值。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果队列包含值,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向指定键的队列中添加一个值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Enqueue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Enqueue(value); + TryAdd(key, list); + return; + } + + list.Enqueue(value); + } + + /// + /// 从指定键的队列中出队并返回一个值。 + /// + /// 要出队的键。 + /// 出队的值,如果队列为空则为默认值。 + public TValue Dequeue(TKey key) + { + if (!TryGetValue(key, out var list) || list.Count == 0) return default; + + var value = list.Dequeue(); + + if (list.Count == 0) RemoveKey(key); + + return value; + } + + /// + /// 尝试从指定键的队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值,如果队列为空则为默认值。 + /// 如果成功出队,则为 true;否则为 false。 + public bool TryDequeue(TKey key, out TValue value) + { + value = Dequeue(key); + + return value != null; + } + + /// + /// 从字典中移除指定键以及其关联的队列。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + TryRemove(key, out _); + Recycle(list); + } + + /// + /// 从队列中获取一个新的队列,如果队列为空则创建一个新的队列。 + /// + /// 获取的队列。 + private Queue Fetch() + { + return _queue.Count <= 0 ? new Queue() : _queue.Dequeue(); + } + + /// + /// 将一个队列回收到队列池中。 + /// + /// 要回收的队列。 + private void Recycle(Queue list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前类的数据,包括从基类继承的键值对字典中的数据以及自定义的队列池。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta new file mode 100644 index 0000000..f7b8eb2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 495d546594e267d478017eb02d4bc0c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs new file mode 100644 index 0000000..bb64ae8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可释放的哈希集合对象池。 + /// + /// 哈希集合中元素的类型。 + public sealed class HashSetPool : HashSet, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个 哈希集合池的实例。 + /// + /// 创建的实例。 + public static HashSetPool Create() + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); + list._isDispose = false; + list._isPool = true; + return list; +#else + var list = MultiThreadPool.Rent>(); + list._isDispose = false; + list._isPool = true; + return list; +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基本哈希集合对象池,他自持有实际的哈希集合。 + /// + /// 哈希集合中元素的类型。 + public sealed class HashSetBasePool : IDisposable, IPool + { + private bool _isPool; + + /// + /// 存储实际的哈希集合 + /// + public HashSet Set = new HashSet(); + + /// + /// 创建一个 基本哈希集合对象池的实例。 + /// + /// 创建的实例。 + public static HashSetBasePool Create() + { +#if FANTASY_WEBGL + var hashSetBasePool = Pool>.Rent(); + hashSetBasePool._isPool = true; + return hashSetBasePool; +#else + var hashSetBasePool = MultiThreadPool.Rent>(); + hashSetBasePool._isPool = true; + return hashSetBasePool; +#endif + } + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + Set.Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs.meta new file mode 100644 index 0000000..b683018 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/HashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5838abe5331703b418048351793b9f06 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs new file mode 100644 index 0000000..de70fe2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可释放的列表(List)对象池。 + /// + /// 列表中元素的类型。 + public sealed class ListPool : List, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 使用指定的元素创建一个 列表(List)对象池的实例。 + /// + /// 要添加到列表的元素。 + /// 创建的实例。 + public static ListPool Create(params T[] args) + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + + if (args != null) + { + list.AddRange(args); + } + + return list; + } + + /// + /// 使用指定的列表创建一个 列表(List)对象池的实例。 + /// + /// 要添加到列表的元素列表。 + /// 创建的实例。 + public static ListPool Create(List args) + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + + if (args != null) + { + list.AddRange(args); + } + + return list; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs.meta new file mode 100644 index 0000000..895665c --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 712cb2a78894b5640a8349e843c5e60a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs new file mode 100644 index 0000000..8a5766c --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 一对多哈希集合(OneToManyHashSet)对象池。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyHashSetPool : OneToManyHashSet, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多哈希集合(OneToManyHashSet)对象池的实例。 + /// + /// 创建的实例。 + public static OneToManyHashSetPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多哈希集合(OneToManyHashSet),用于创建和管理键对应多个值的集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyHashSet : Dictionary> where TKey : notnull + { + /// 用于回收和重用的空闲值集合队列。 + private readonly Queue> _queue = new Queue>(); + /// 设置最大回收限制,用于控制值集合的最大数量。 + private readonly int _recyclingLimit = 120; + /// 一个空的、不包含任何元素的哈希集合,用于在查找失败时返回。 + private static HashSet _empty = new HashSet(); + + /// + /// 初始化 类的新实例。 + /// + public OneToManyHashSet() { } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyHashSet(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定的键值对是否存在于集合中。 + /// + /// 键。 + /// 值。 + /// 如果存在则为 true,否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 添加指定的键值对到集合中。 + /// + /// 键。 + /// 值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 从集合中移除指定键对应的值。 + /// + /// 键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从集合中移除指定键及其对应的值集合。 + /// + /// 键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + Recycle(list); + } + + /// + /// 获取指定键对应的值集合,如果不存在则返回一个空的哈希集合。 + /// + /// 键。 + /// 对应的值集合或空的哈希集合。 + public HashSet GetValue(TKey key) + { + if (TryGetValue(key, out HashSet value)) + { + return value; + } + + return _empty; + } + + /// + /// 从队列中获取一个空闲的值集合,或者创建一个新的。 + /// + /// 值集合。 + private HashSet Fetch() + { + return _queue.Count <= 0 ? new HashSet() : _queue.Dequeue(); + } + + /// + /// 回收值集合到队列中,以便重复利用。 + /// + /// 要回收的值集合。 + private void Recycle(HashSet list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空集合中的数据并和队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta new file mode 100644 index 0000000..b6175b9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a56b47840004ebf449a2119174097b43 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs new file mode 100644 index 0000000..80568ef --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可回收的、一对多关系的列表池。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyListPool : OneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多关系的列表池的实例。 + /// + /// 创建的实例。 + public static OneToManyListPool Create() + { +#if FANTASY_WEBGL || FANTASY_EXPORTER + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + return list; + } + + /// + /// 释放当前对象所占用的资源,并将对象回收到对象池中。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL || FANTASY_EXPORTER + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多关系的列表字典。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyList : Dictionary> where TKey : notnull + { + private readonly int _recyclingLimit = 120; + private static readonly List Empty = new List(); + private readonly Queue> _queue = new Queue>(); + + /// + /// 初始化一个新的 实例。 + /// + public OneToManyList() { } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyList(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断给定的键和值是否存在于列表中。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果存在则为 ,否则为 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向列表中添加指定键和值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 获取指定键对应的列表中的第一个值。 + /// + /// 要获取值的键。 + /// 键对应的列表中的第一个值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从列表中移除指定键和值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + /// 如果成功移除则为 ,否则为 + public bool RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + return true; + } + + var isRemove = list.Remove(value); + + if (list.Count == 0) + { + isRemove = RemoveByKey(key); + } + + return isRemove; + } + + /// + /// 从列表中移除指定键及其关联的所有值。 + /// + /// 要移除的键。 + /// 如果成功移除则为 ,否则为 + public bool RemoveByKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return false; + } + + Remove(key); + Recycle(list); + return true; + } + + /// + /// 获取指定键关联的所有值的列表。 + /// + /// 要获取值的键。 + /// 键关联的所有值的列表。 + public List GetValues(TKey key) + { + if (TryGetValue(key, out List list)) + { + return list; + } + + return Empty; + } + + /// + /// 清除字典中的所有键值对,并回收相关的值集合。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) Recycle(keyValuePair.Value); + + base.Clear(); + } + + /// + /// 从空闲值集合队列中获取一个值集合,如果队列为空则创建一个新的值集合。 + /// + /// 从队列中获取的值集合。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 回收一个不再使用的值集合到空闲值集合队列中。 + /// + /// 要回收的值集合。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs.meta new file mode 100644 index 0000000..ac7625f --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93ee84e42c94b1b4cb02e01fe4e71e4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs new file mode 100644 index 0000000..222576e --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 支持一对多关系的队列池,用于存储具有相同键的值的队列集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyQueuePool : OneToManyQueue, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多关系的队列池的实例。 + /// + /// 创建的实例。 + public static OneToManyQueuePool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例所占用的资源,并将实例回收到对象池中。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 支持一对多关系的队列,用于存储具有相同键的值的队列集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyQueue : Dictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 创建一个 一对多关系的队列的实例。设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyQueue(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的值队列是否包含指定的值。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果存在,则为 true;否则为 false + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定的值添加到指定键的值队列中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Enqueue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Enqueue(value); + Add(key, list); + return; + } + + list.Enqueue(value); + } + + /// + /// 从指定键的值队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值。 + public TValue Dequeue(TKey key) + { + if (!TryGetValue(key, out var list) || list.Count == 0) + { + return default; + } + + var value = list.Dequeue(); + + if (list.Count == 0) + { + RemoveKey(key); + } + + return value; + } + + /// + /// 尝试从指定键的值队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值。 + /// 如果成功出队,则为 true;否则为 false + public bool TryDequeue(TKey key, out TValue value) + { + value = Dequeue(key); + + return value != null; + } + + /// + /// 从字典中移除指定键及其对应的值队列。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + Recycle(list); + } + + /// + /// 从队列池中获取一个值队列。如果队列池为空,则创建一个新的值队列。 + /// + /// 获取的值队列。 + private Queue Fetch() + { + return _queue.Count <= 0 ? new Queue() : _queue.Dequeue(); + } + + /// + /// 回收一个不再使用的值队列到队列池中,以便重用。 + /// + /// 要回收的值队列。 + private void Recycle(Queue list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前实例的数据,同时回收所有值队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta new file mode 100644 index 0000000..93d8b06 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d66f816fefb57054ebc073ab58b54d1f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs new file mode 100644 index 0000000..b4395e8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可重用的列表,继承自 类。该类支持通过对象池重用列表实例,以减少对象分配和释放的开销。 + /// + /// 列表中元素的类型。 + public sealed class ReuseList : List, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 可重用的列表的实例。 + /// + /// 创建的实例。 + public static ReuseList Create() + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + return list; + } + + /// + /// 释放该实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs.meta new file mode 100644 index 0000000..37b04ba --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/ReuseList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afa0d451378b33b45a4371cf99ade9a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs new file mode 100644 index 0000000..464ab58 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs @@ -0,0 +1,226 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典和并发集合实现的一对多映射列表的对象池包装类,继承自 类, + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 键的类型。 + /// 值的类型。 + public class SortedConcurrentOneToManyListPool : SortedConcurrentOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例,使用默认的参数设置。 + /// + /// 新创建的 实例。 + public static SortedConcurrentOneToManyListPool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典和并发集合实现的一多对映射列表类,继承自 类, + /// 用于在多个值与一个键关联的情况下进行管理和存储。该类支持并发操作,适用于多线程环境。 + /// + /// 键的类型。 + /// 值的类型。 + public class SortedConcurrentOneToManyList : SortedDictionary> where TKey : notnull + { + /// 用于同步操作的锁对象,它确保在多线程环境下对数据的安全访问。 + private readonly object _lockObject = new object(); + /// 用于存储缓存的队列。 + private readonly Queue> _queue = new Queue>(); + /// 控制缓存回收的限制。当缓存的数量超过此限制时,旧的缓存将会被回收。 + private readonly int _recyclingLimit; + + /// + /// 初始化一个新的 类的实例,使用默认的参数设置。 + /// + public SortedConcurrentOneToManyList() + { + } + + /// + /// 初始化一个新的 类的实例,指定最大缓存数量。 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedConcurrentOneToManyList(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查指定的键和值是否存在于映射列表中。 + /// + /// 要检查的键。 + /// 要检查的值。 + /// 如果存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + lock (_lockObject) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + } + + /// + /// 将指定的值添加到与指定键关联的列表中。 + /// + /// 要关联值的键。 + /// 要添加到列表的值。 + public void Add(TKey key, TValue value) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + } + + /// + /// 获取与指定键关联的列表中的第一个值。 + /// 如果列表不存在或为空,则返回默认值。 + /// + /// 要获取第一个值的键。 + /// 第一个值,或默认值。 + public TValue First(TKey key) + { + lock (_lockObject) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + } + + /// + /// 从与指定键关联的列表中移除指定的值。 + /// 如果列表不存在或值不存在于列表中,则不执行任何操作。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + } + + /// + /// 从映射列表中移除指定的键及其关联的列表。 + /// 如果键不存在于映射列表中,则不执行任何操作。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + + Recycle(list); + } + } + + /// + /// 从缓存中获取一个可重用的列表。如果缓存中不存在列表,则创建一个新的列表并返回。 + /// + /// 可重用的列表。 + private List Fetch() + { + lock (_lockObject) + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + } + + /// + /// 将不再使用的列表回收到缓存中,以便重复利用。如果缓存数量超过限制,则丢弃列表而不进行回收。 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + lock (_lockObject) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + } + + /// + /// 清空映射列表以及队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta new file mode 100644 index 0000000..8cb7178 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a674c814e81ddab4ba537637cfa43782 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs new file mode 100644 index 0000000..8158db5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典实现的一对多关系的映射哈希集合的对象池包装类,将唯一键映射到多个值的哈希集合。 + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 字典中键的类型。 + /// 哈希集合中值的类型。 + public class SortedOneToManyHashSetPool : SortedOneToManyHashSet, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 实例。 + /// + /// 新创建的实例。 + public static SortedOneToManyHashSetPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典实现的一对多关系的映射哈希集合类,将唯一键映射到多个值的哈希集合。 + /// 用于在多个值与一个键关联的情况下进行管理和存储。 + /// + /// 字典中键的类型。 + /// 集合中值的类型。 + public class SortedOneToManyHashSet : SortedDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 创建一个新的 实例。 + /// + public SortedOneToManyHashSet() { } + + /// + /// 创建一个新的 实例,设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedOneToManyHashSet(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断哈希集合中是否包含指定的键值对。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果键值对存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定值添加到给定键关联的哈希集合中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 从指定键关联的哈希集合中移除特定值。 + /// 如果哈希集合不存在或值不存在于集合中,则不执行任何操作。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从字典中移除指定键以及关联的哈希集合,并将集合进行回收。 + /// 如果键不存在于映射列表中,则不执行任何操作。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + + Recycle(list); + } + + /// + /// 获取一个空的或回收的哈希集合。 + /// + /// 获取的哈希集合实例。 + private HashSet Fetch() + { + return _queue.Count <= 0 ? new HashSet() : _queue.Dequeue(); + } + + /// + /// 回收一个哈希集合,将其清空并放入回收队列中。 + /// + /// 要回收的哈希集合。 + private void Recycle(HashSet list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 重写 Clear 方法,清空字典并清空回收队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta new file mode 100644 index 0000000..7e61558 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6ce6cc73a185874caf2b74bd7d21e37 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs new file mode 100644 index 0000000..f0bae12 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典实现的一对多映射列表的对象池包装类,继承自 类, + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 字典中键的类型。 + /// 列表中值的类型。 + public class SortedOneToManyListPool : SortedOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 实例。 + /// + /// 新创建的实例。 + public static SortedOneToManyListPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典实现的一对多关系的映射列表类,将唯一键映射到包含多个值的列表。 + /// 用于在多个值与一个键关联的情况下进行管理和存储。 + /// + /// 字典中键的类型。 + /// 列表中值的类型。 + public class SortedOneToManyList : SortedDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 创建一个新的 实例。 + /// + public SortedOneToManyList() + { + } + + /// + /// 创建一个新的 实例,设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedOneToManyList(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断列表中是否包含指定的键值对。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果键值对存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定值添加到给定键关联的列表中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + + /// + /// 获取指定键关联的列表中的第一个值。 + /// + /// 要查找值的键。 + /// 指定键关联的列表中的第一个值,如果列表为空则返回默认值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从指定键关联的列表中移除特定值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + return; + } + + list.Remove(value); + + if (list.Count == 0) + { + RemoveKey(key); + } + } + + /// + /// 从字典中移除指定键以及关联的列表,并将列表进行回收。 + /// + /// 要移除的键。 + + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return; + } + + Remove(key); + Recycle(list); + } + + /// + /// 获取一个空的或回收的列表。 + /// + /// 获取的列表实例。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 回收一个列表,将其清空并放入回收队列中。如果缓存数量超过限制,则丢弃列表而不进行回收 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) + { + return; + } + + _queue.Enqueue(list); + } + + /// + /// 重写 Clear 方法,清空字典并清空回收队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta new file mode 100644 index 0000000..6d975b2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 036cd28ac2417c14682d7d23cfb70e1c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary.meta new file mode 100644 index 0000000..17f76e8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 03783538a8b735243a1716efa6f8878a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs new file mode 100644 index 0000000..ed0aa57 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +#pragma warning disable CS8601 // Possible null reference assignment. + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供对字典的扩展方法。 + /// + public static class DictionaryExtensions + { + /// + /// 尝试从字典中移除指定键,并返回相应的值。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + /// 要操作的字典实例。 + /// 要移除的键。 + /// 从字典中移除的值(如果成功移除)。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public static bool TryRemove(this IDictionary self, T key, out TV value) + { + if (!self.TryGetValue(key, out value)) + { + return false; + } + + self.Remove(key); + return true; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta new file mode 100644 index 0000000..fcc7537 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 518d4d5f27703994f92049cd720c7215 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs new file mode 100644 index 0000000..567901c --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以使用对象池管理的字典类。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public sealed class DictionaryPool : Dictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static DictionaryPool Create() + { +#if FANTASY_WEBGL + var dictionary = Pool>.Rent(); +#else + var dictionary = MultiThreadPool.Rent>(); +#endif + dictionary._isDispose = false; + dictionary._isPool = true; + return dictionary; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta new file mode 100644 index 0000000..07e96cc --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 68c7a566ce8a92e4193abe208024aad4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs new file mode 100644 index 0000000..e868710 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个双向映射字典对象池类,用于双向键值对映射。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public class DoubleMapDictionaryPool : DoubleMapDictionary, IDisposable, IPool where TKey : notnull where TValue : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static DoubleMapDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 可以实现双向映射的字典类,用于将键和值进行双向映射。 + /// + /// 键的类型,不能为 null。 + /// 值的类型,不能为 null。 + public class DoubleMapDictionary where TK : notnull where TV : notnull + { + private readonly Dictionary _kv = new Dictionary(); + private readonly Dictionary _vk = new Dictionary(); + + /// + /// 创建一个新的空的 实例。 + /// + public DoubleMapDictionary() { } + + /// + /// 创建一个新的具有指定初始容量的 实例。 + /// + /// 初始容量。 + public DoubleMapDictionary(int capacity) + { + _kv = new Dictionary(capacity); + _vk = new Dictionary(capacity); + } + + /// + /// 获取包含字典中所有键的列表。 + /// + public List Keys => new List(_kv.Keys); + + /// + /// 获取包含字典中所有值的列表。 + /// + public List Values => new List(_vk.Keys); + + /// + /// 对字典中的每个键值对执行指定的操作。 + /// + /// 要执行的操作。 + public void ForEach(Action action) + { + if (action == null) + { + return; + } + + var keys = _kv.Keys; + foreach (var key in keys) + { + action(key, _kv[key]); + } + } + + /// + /// 将指定的键值对添加到字典中。 + /// + /// 要添加的键。 + /// 要添加的值。 + public void Add(TK key, TV value) + { + if (key == null || value == null || _kv.ContainsKey(key) || _vk.ContainsKey(value)) + { + return; + } + + _kv.Add(key, value); + _vk.Add(value, key); + } + + /// + /// 根据指定的键获取相应的值。 + /// + /// 要查找值的键。 + /// 与指定键关联的值,如果找不到键,则返回默认值。 + public TV GetValueByKey(TK key) + { + if (key != null && _kv.ContainsKey(key)) + { + return _kv[key]; + } + + return default; + } + + /// + /// 尝试根据指定的键获取相应的值。 + /// + /// 要查找值的键。 + /// 如果找到,则为与指定键关联的值;否则为值的默认值。 + /// 如果找到键,则为 true;否则为 false。 + public bool TryGetValueByKey(TK key, out TV value) + { + var result = key != null && _kv.ContainsKey(key); + + value = result ? _kv[key] : default; + + return result; + } + + /// + /// 根据指定的值获取相应的键。 + /// + /// 要查找键的值。 + /// 与指定值关联的键,如果找不到值,则返回默认键。 + public TK GetKeyByValue(TV value) + { + if (value != null && _vk.ContainsKey(value)) + { + return _vk[value]; + } + + return default; + } + + /// + /// 尝试根据指定的值获取相应的键。 + /// + /// 要查找键的值。 + /// 如果找到,则为与指定值关联的键;否则为键的默认值。 + /// 如果找到值,则为 true;否则为 false。 + public bool TryGetKeyByValue(TV value, out TK key) + { + var result = value != null && _vk.ContainsKey(value); + + key = result ? _vk[value] : default; + + return result; + } + + /// + /// 根据指定的键移除键值对。 + /// + /// 要移除的键。 + public void RemoveByKey(TK key) + { + if (key == null) + { + return; + } + + if (!_kv.TryGetValue(key, out var value)) + { + return; + } + + _kv.Remove(key); + _vk.Remove(value); + } + + /// + /// 根据指定的值移除键值对。 + /// + /// 要移除的值。 + public void RemoveByValue(TV value) + { + if (value == null) + { + return; + } + + if (!_vk.TryGetValue(value, out var key)) + { + return; + } + + _kv.Remove(key); + _vk.Remove(value); + } + + /// + /// 清空字典中的所有键值对。 + /// + public void Clear() + { + _kv.Clear(); + _vk.Clear(); + } + + /// + /// 判断字典是否包含指定的键。 + /// + /// 要检查的键。 + /// 如果字典包含指定的键,则为 true;否则为 false。 + public bool ContainsKey(TK key) + { + return key != null && _kv.ContainsKey(key); + } + + /// + /// 判断字典是否包含指定的值。 + /// + /// 要检查的值。 + /// 如果字典包含指定的值,则为 true;否则为 false。 + public bool ContainsValue(TV value) + { + return value != null && _vk.ContainsKey(value); + } + + /// + /// 判断字典是否包含指定的键值对。 + /// + /// 要检查的键。 + /// 要检查的值。 + /// 如果字典包含指定的键值对,则为 true;否则为 false。 + public bool Contains(TK key, TV value) + { + if (key == null || value == null) + { + return false; + } + + return _kv.ContainsKey(key) && _vk.ContainsKey(value); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta new file mode 100644 index 0000000..4fecec7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89e054e94e110024c8a3a11f3d9a2f07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs new file mode 100644 index 0000000..fc4d44f --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个带资源释放功能的实体字典类,支持使用对象池管理。 + /// + /// 字典中键的类型。 + /// 字典中值的类型,必须实现 IDisposable 接口。 + public sealed class EntityDictionary : Dictionary, IDisposable, IPool where TN : IDisposable where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static EntityDictionary Create() + { +#if FANTASY_WEBGL + var entityDictionary = Pool>.Rent(); +#else + var entityDictionary = MultiThreadPool.Rent>(); +#endif + entityDictionary._isDispose = false; + entityDictionary._isPool = true; + return entityDictionary; + } + + /// + /// 清空字典中的所有键值对,并释放值的资源。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) + { + keyValuePair.Value.Dispose(); + } + + base.Clear(); + } + + /// + /// 清空字典中的所有键值对,但不释放值的资源。 + /// + public void ClearNotDispose() + { + base.Clear(); + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta new file mode 100644 index 0000000..ffbd256 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b52b6117133f5ea4b8cf9dbbea4f014b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs new file mode 100644 index 0000000..0515423 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 +#pragma warning disable CS8601 + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 一对多映射关系的字典对象池。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的键类型。 + /// 内部字典中的值类型。 + public class OneToManyDictionaryPool : OneToManyDictionary, IDisposable, IPool where TKey : notnull where TValueKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 新创建的 OneToManyDictionaryPool 实例。 + public static OneToManyDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例及其资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多映射关系的字典。每个键都对应一个内部字典,该内部字典将键值映射到相应的值。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的键类型。 + /// 内部字典中的值类型。 + public class OneToManyDictionary : Dictionary> + where TKey : notnull where TValueKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 创建一个新的 实例。 + /// + public OneToManyDictionary() { } + + /// + /// 创建一个新的 实例,并指定最大缓存数量。 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyDictionary(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查是否包含指定的键值对。 + /// + /// 外部字典中的键。 + /// 内部字典中的键。 + /// 如果包含指定的键值对,则为 true;否则为 false。 + public bool Contains(TKey key, TValueKey valueKey) + { + TryGetValue(key, out var dic); + + return dic != null && dic.ContainsKey(valueKey); + } + + /// + /// 尝试获取指定键值对的值。 + /// + /// 外部字典中的键。 + /// 内部字典中的键。 + /// 获取的值,如果操作成功,则为值;否则为默认值。 + /// 如果操作成功,则为 true;否则为 false。 + public bool TryGetValue(TKey key, TValueKey valueKey, out TValue value) + { + value = default; + return TryGetValue(key, out var dic) && dic.TryGetValue(valueKey, out value); + } + + /// + /// 获取指定键的第一个值。 + /// + /// 要获取第一个值的键。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var dic) ? default : dic.First().Value; + } + + /// + /// 向字典中添加指定的键值对。 + /// + /// 要添加键值对的键。 + /// 要添加键值对的内部字典键。 + /// 要添加的值。 + public void Add(TKey key, TValueKey valueKey, TValue value) + { + if (!TryGetValue(key, out var dic)) + { + dic = Fetch(); + dic[valueKey] = value; + // dic.Add(valueKey, value); + Add(key, dic); + + return; + } + + dic[valueKey] = value; + // dic.Add(valueKey, value); + } + + /// + /// 从字典中移除指定的键值对。 + /// + /// 要移除键值对的键。 + /// 要移除键值对的内部字典键。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public bool Remove(TKey key, TValueKey valueKey) + { + if (!TryGetValue(key, out var dic)) return false; + + var result = dic.Remove(valueKey); + + if (dic.Count == 0) RemoveKey(key); + + return result; + } + + /// + /// 从字典中移除指定的键值对。 + /// + /// 要移除键值对的键。 + /// 要移除键值对的内部字典键。 + /// 如果成功移除键值对,则为移除的值;否则为默认值。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public bool Remove(TKey key, TValueKey valueKey, out TValue value) + { + if (!TryGetValue(key, out var dic)) + { + value = default; + return false; + } + + var result = dic.TryGetValue(valueKey, out value); + + if (result) dic.Remove(valueKey); + + if (dic.Count == 0) RemoveKey(key); + + return result; + } + + /// + /// 移除字典中的指定键及其相关的所有键值对。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var dic)) return; + + Remove(key); + Recycle(dic); + } + + /// + /// 从对象池中获取一个内部字典实例,如果池中没有,则创建一个新实例。 + /// + /// 获取的内部字典实例。 + private Dictionary Fetch() + { + return _queue.Count <= 0 ? new Dictionary() : _queue.Dequeue(); + } + + /// + /// 将不再使用的内部字典实例放回对象池中,以便后续重用。 + /// + /// 要放回对象池的内部字典实例。 + private void Recycle(Dictionary dic) + { + dic.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(dic); + } + + /// + /// 清空字典中的所有键值对,并将不再使用的内部字典实例放回对象池中。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) Recycle(keyValuePair.Value); + + base.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta new file mode 100644 index 0000000..2674ad1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86f203177e838a04a9a89fda04b71145 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs new file mode 100644 index 0000000..127a8ac --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8601 + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 一对多映射关系的排序字典对象池。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的排序键类型。 + /// 内部字典中的值类型。 + public class OneToManySortedDictionaryPool : OneToManySortedDictionary, IDisposable, IPool where TKey : notnull where TSortedKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 新创建的 OneToManySortedDictionaryPool 实例。 + public static OneToManySortedDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例及其资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多映射关系的排序字典。每个外部键映射到一个内部排序字典,该内部排序字典将排序键映射到相应的值。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的排序键类型。 + /// 内部字典中的值类型。 + public class + OneToManySortedDictionary : Dictionary> + where TSortedKey : notnull where TKey : notnull + { + /// 缓存队列的回收限制 + private readonly int _recyclingLimit = 120; + /// 缓存队列,用于存储已回收的内部排序字典 + private readonly Queue> _queue = new Queue>(); + + /// + /// 创建一个新的 实例。 + /// + protected OneToManySortedDictionary() { } + + /// + /// 创建一个新的 实例。设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManySortedDictionary(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查字典是否包含指定的外部键。 + /// + /// 要检查的外部键。 + /// 如果字典包含指定的外部键,则为 true;否则为 false。 + public bool Contains(TKey key) + { + return this.ContainsKey(key); + } + + /// + /// 检查字典是否包含指定的外部键和排序键。 + /// + /// 要检查的外部键。 + /// 要检查的排序键。 + /// 如果字典包含指定的外部键和排序键,则为 true;否则为 false。 + public bool Contains(TKey key, TSortedKey sortedKey) + { + return TryGetValue(key, out var dic) && dic.ContainsKey(sortedKey); + } + + /// + /// 尝试从字典中获取指定外部键对应的内部排序字典。 + /// + /// 要获取内部排序字典的外部键。 + /// 获取到的内部排序字典,如果找不到则为 null。 + /// 如果找到内部排序字典,则为 true;否则为 false。 + public new bool TryGetValue(TKey key, out SortedDictionary dic) + { + return base.TryGetValue(key, out dic); + } + + /// + /// 尝试从字典中获取指定外部键和排序键对应的值。 + /// + /// 要获取值的外部键。 + /// 要获取值的排序键。 + /// 获取到的值,如果找不到则为 default。 + /// 如果找到值,则为 true;否则为 false。 + public bool TryGetValueBySortedKey(TKey key, TSortedKey sortedKey, out TValue value) + { + if (base.TryGetValue(key, out var dic)) + { + return dic.TryGetValue(sortedKey, out value); + } + + value = default; + return false; + } + + /// + /// 向字典中添加一个值,关联到指定的外部键和排序键。 + /// + /// 要关联值的外部键。 + /// 要关联值的排序键。 + /// 要添加的值。 + public void Add(TKey key, TSortedKey sortedKey, TValue value) + { + if (!TryGetValue(key, out var dic)) + { + dic = Fetch(); + dic.Add(sortedKey, value); + Add(key, dic); + + return; + } + + dic.Add(sortedKey, value); + } + + /// + /// 从字典中移除指定外部键和排序键关联的值。 + /// + /// 要移除值的外部键。 + /// 要移除值的排序键。 + /// 如果成功移除值,则为 true;否则为 false。 + public bool RemoveSortedKey(TKey key, TSortedKey sortedKey) + { + if (!TryGetValue(key, out var dic)) + { + return false; + } + + var isRemove = dic.Remove(sortedKey); + + if (dic.Count == 0) + { + isRemove = RemoveKey(key); + } + + return isRemove; + } + + /// + /// 从字典中移除指定外部键及其关联的所有值。 + /// + /// 要移除的外部键。 + /// 如果成功移除外部键及其关联的所有值,则为 true;否则为 false。 + public bool RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return false; + } + + Remove(key); + Recycle(list); + return true; + } + + /// + /// 从缓存队列中获取一个内部排序字典。 + /// + /// 一个内部排序字典。 + private SortedDictionary Fetch() + { + return _queue.Count <= 0 ? new SortedDictionary() : _queue.Dequeue(); + } + + /// + /// 回收一个内部排序字典到缓存队列。 + /// + /// 要回收的内部排序字典。 + private void Recycle(SortedDictionary dic) + { + dic.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) + { + return; + } + + _queue.Enqueue(dic); + } + + /// + /// 清空字典以及内部排序字典缓存队列,释放所有资源。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta new file mode 100644 index 0000000..39369a1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a60895bae61946545ab19518a97ea7b7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs new file mode 100644 index 0000000..ebe12e9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以重用的字典类,支持使用对象池管理。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public sealed class ReuseDictionary : Dictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static ReuseDictionary Create() + { +#if FANTASY_WEBGL + var entityDictionary = Pool>.Rent(); +#else + var entityDictionary = MultiThreadPool.Rent>(); +#endif + entityDictionary._isDispose = false; + entityDictionary._isPool = true; + return entityDictionary; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta new file mode 100644 index 0000000..b711bd5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cf712318b312bb946a4d43746f3c11f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs new file mode 100644 index 0000000..8db66a8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以使用对象池管理的排序字典类。 + /// + /// + /// + public sealed class SortedDictionaryPool : SortedDictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static SortedDictionaryPool Create() + { +#if FANTASY_WEBGL + var dictionary = Pool>.Rent(); +#else + var dictionary = MultiThreadPool.Rent>(); +#endif + dictionary._isDispose = false; + dictionary._isPool = true; + return dictionary; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta new file mode 100644 index 0000000..77ea004 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b87d760d8e818a848b9da0812a318d6a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/NativeCollections.meta b/Runtime/CoreRuntime/Core/DataStructure/NativeCollections.meta new file mode 100644 index 0000000..9817022 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/NativeCollections.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c6c026f7470b12d4a9bddbbce6dd662c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue.meta b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue.meta new file mode 100644 index 0000000..5b1f992 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a2be747db231b534b91e0c7fd92c6999 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs new file mode 100644 index 0000000..2ef6704 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs @@ -0,0 +1,121 @@ +// ReSharper disable SwapViaDeconstruction +// ReSharper disable UseIndexFromEndExpression +// ReSharper disable ConvertToPrimaryConstructor +using System; +using System.Collections.Generic; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.PriorityQueue +{ + /// + /// 优先队列 + /// + /// 节点数据 + /// 排序的类型、 + public sealed class PriorityQueue where TPriority : IComparable + { + private readonly List> _heap; + + public PriorityQueue(int initialCapacity = 16) + { + _heap = new List>(initialCapacity); + } + + public int Count => _heap.Count; + + public void Enqueue(TElement element, TPriority priority) + { + _heap.Add(new PriorityQueueItem(element, priority)); + HeapifyUp(_heap.Count - 1); + } + + public TElement Dequeue() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + + var item = _heap[0]; + _heap[0] = _heap[_heap.Count - 1]; + _heap.RemoveAt(_heap.Count - 1); + HeapifyDown(0); + return item.Element; + } + + public bool TryDequeue(out TElement element) + { + if (_heap.Count == 0) + { + element = default(TElement); + return false; + } + + element = Dequeue(); + return true; + } + + public TElement Peek() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + return _heap[0].Element; + } + + // ReSharper disable once IdentifierTypo + private void HeapifyUp(int index) + { + while (index > 0) + { + var parentIndex = (index - 1) / 2; + if (_heap[index].Priority.CompareTo(_heap[parentIndex].Priority) >= 0) + { + break; + } + Swap(index, parentIndex); + index = parentIndex; + } + } + + // ReSharper disable once IdentifierTypo + private void HeapifyDown(int index) + { + var lastIndex = _heap.Count - 1; + while (true) + { + var smallestIndex = index; + var leftChildIndex = 2 * index + 1; + var rightChildIndex = 2 * index + 2; + + if (leftChildIndex <= lastIndex && _heap[leftChildIndex].Priority.CompareTo(_heap[smallestIndex].Priority) < 0) + { + smallestIndex = leftChildIndex; + } + + if (rightChildIndex <= lastIndex && _heap[rightChildIndex].Priority.CompareTo(_heap[smallestIndex].Priority) < 0) + { + smallestIndex = rightChildIndex; + } + + if (smallestIndex == index) + { + break; + } + + Swap(index, smallestIndex); + index = smallestIndex; + } + } + + private void Swap(int index1, int index2) + { + var temp = _heap[index1]; + _heap[index1] = _heap[index2]; + _heap[index2] = temp; + } + } +} + diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta new file mode 100644 index 0000000..8f67545 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5d9ea79288d88e040bef0c36410e8617 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs new file mode 100644 index 0000000..5b020b2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs @@ -0,0 +1,30 @@ +// ReSharper disable ConvertToPrimaryConstructor +// ReSharper disable SwapViaDeconstruction +// ReSharper disable InconsistentNaming +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.DataStructure.PriorityQueue +{ + public struct PriorityQueueItemUint + { + public T Element { get; set; } + public uint Priority { get; set; } + + public PriorityQueueItemUint(T element, uint priority) + { + Element = element; + Priority = priority; + } + } + + public struct PriorityQueueItem + { + public T Element { get; } + public T1 Priority { get; } + + public PriorityQueueItem(T element, T1 priority) + { + Element = element; + Priority = priority; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta new file mode 100644 index 0000000..0999222 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 16e00a9de7378c0428b1dbc258459183 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs new file mode 100644 index 0000000..63a4418 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs @@ -0,0 +1,116 @@ +// ReSharper disable SwapViaDeconstruction +// ReSharper disable UseIndexFromEndExpression +// ReSharper disable ConvertToPrimaryConstructor +using System; +using System.Collections.Generic; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.PriorityQueue +{ + public sealed class PriorityQueue where T : IComparable + { + private readonly List _heap; + + public PriorityQueue(int initialCapacity = 16) + { + _heap = new List(initialCapacity); + } + + public int Count => _heap.Count; + + public void Enqueue(T item) + { + _heap.Add(item); + HeapifyUp(_heap.Count - 1); + } + + public T Dequeue() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + + var item = _heap[0]; + var heapCount = _heap.Count - 1; + _heap[0] = _heap[heapCount]; + _heap.RemoveAt(heapCount); + HeapifyDown(0); + return item; + } + + public bool TryDequeue(out T item) + { + if (_heap.Count == 0) + { + item = default(T); + return false; + } + + item = Dequeue(); + return true; + } + + public T Peek() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + return _heap[0]; + } + + // ReSharper disable once IdentifierTypo + private void HeapifyUp(int index) + { + while (index > 0) + { + var parentIndex = (index - 1) / 2; + if (_heap[index].CompareTo(_heap[parentIndex]) >= 0) + { + break; + } + Swap(index, parentIndex); + index = parentIndex; + } + } + + // ReSharper disable once IdentifierTypo + private void HeapifyDown(int index) + { + var lastIndex = _heap.Count - 1; + while (true) + { + var smallestIndex = index; + var leftChildIndex = 2 * index + 1; + var rightChildIndex = 2 * index + 2; + + if (leftChildIndex <= lastIndex && _heap[leftChildIndex].CompareTo(_heap[smallestIndex]) < 0) + { + smallestIndex = leftChildIndex; + } + + if (rightChildIndex <= lastIndex && _heap[rightChildIndex].CompareTo(_heap[smallestIndex]) < 0) + { + smallestIndex = rightChildIndex; + } + + if (smallestIndex == index) + { + break; + } + + Swap(index, smallestIndex); + index = smallestIndex; + } + } + + private void Swap(int index1, int index2) + { + var temp = _heap[index1]; + _heap[index1] = _heap[index2]; + _heap[index2] = temp; + } + } +} + diff --git a/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta new file mode 100644 index 0000000..0d89ee9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8271cef0217701d4d8a019bb9977d29c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable.meta b/Runtime/CoreRuntime/Core/DataStructure/SkipTable.meta new file mode 100644 index 0000000..13cdf3b --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 40753c1a6c88fcf4e82db32f1f4ba4a5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs new file mode 100644 index 0000000..acbc2c1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs @@ -0,0 +1,190 @@ + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳表数据结构(升序版) + /// + /// 跳表中存储的值的类型。 + public class SkipTable : SkipTableBase + { + /// + /// 创建一个新的跳表实例。 + /// + /// 跳表的最大层数。 + public SkipTable(int maxLayer = 8) : base(maxLayer) { } + + /// + /// 向跳表中添加一个新节点。 + /// + /// 节点的主排序键。 + /// 节点的副排序键。 + /// 节点的唯一键。 + /// 要添加的值。 + public override void Add(long sortKey, long viceKey, long key, TValue value) + { + var rLevel = 1; + + while (rLevel <= MaxLayer && Random.Next(3) == 0) + { + ++rLevel; + } + + SkipTableNode cur = TopHeader, last = null; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 节点有next节点,且 (next主键 < 插入主键) 或 (next主键 == 插入主键 且 next副键 < 插入副键) + while (cur.Right != null && ((cur.Right.SortKey < sortKey) || + (cur.Right.SortKey == sortKey && cur.Right.ViceKey < viceKey))) + { + cur = cur.Right; + } + + if (layer <= rLevel) + { + var currentRight = cur.Right; + + // 在当前层插入新节点 + cur.Right = new SkipTableNode(sortKey, viceKey, key, value, layer == 1 ? cur.Index + 1 : 0, cur, cur.Right, null); + + if (currentRight != null) + { + currentRight.Left = cur.Right; + } + + if (last != null) + { + last.Down = cur.Right; + } + + if (layer == 1) + { + // 更新索引信息 + cur.Right.Index = cur.Index + 1; + Node.Add(key, cur.Right); + + SkipTableNode v = cur.Right.Right; + + while (v != null) + { + v.Index++; + v = v.Right; + } + } + + last = cur.Right; + } + + cur = cur.Down; + } + } + + /// + /// 从跳表中移除一个节点。 + /// + /// 节点的主排序键。 + /// 节点的副排序键。 + /// 节点的唯一键。 + /// 被移除的节点的值。 + /// 如果成功移除节点,则为 true;否则为 false。 + public override bool Remove(long sortKey, long viceKey, long key, out TValue value) + { + value = default; + var seen = false; + var cur = TopHeader; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 先按照主键查找 再 按副键查找 + while (cur.Right != null && cur.Right.SortKey < sortKey && cur.Right.Key != key) cur = cur.Right; + while (cur.Right != null && (cur.Right.SortKey == sortKey && cur.Right.ViceKey <= viceKey) && + cur.Right.Key != key) cur = cur.Right; + + var isFind = false; + var currentCur = cur; + SkipTableNode removeCur = null; + // 如果当前不是要删除的节点、但主键和副键都一样、需要特殊处理下。 + if (cur.Right != null && cur.Right.Key == key) + { + isFind = true; + removeCur = cur.Right; + currentCur = cur; + } + else + { + // 先向左查找下 + var currentNode = cur.Left; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Left; + } + + // 再向右查找下 + if (!isFind) + { + currentNode = cur.Right; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Right; + } + } + } + + if (isFind && currentCur != null) + { + value = removeCur.Value; + currentCur.Right = removeCur.Right; + + if (removeCur.Right != null) + { + removeCur.Right.Left = currentCur; + removeCur.Right = null; + } + + removeCur.Left = null; + removeCur.Down = null; + removeCur.Value = default; + + if (layer == 1) + { + var tempCur = currentCur.Right; + while (tempCur != null) + { + tempCur.Index--; + tempCur = tempCur.Right; + } + + Node.Remove(removeCur.Key); + } + + seen = true; + } + + cur = cur.Down; + } + + return seen; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs.meta new file mode 100644 index 0000000..b3447ed --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd88ad42b48be2a498a7563a1a5cda20 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs new file mode 100644 index 0000000..82783e8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs @@ -0,0 +1,282 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Fantasy.DataStructure.Collection; + +#pragma warning disable CS8601 +#pragma warning disable CS8603 +#pragma warning disable CS8625 +#pragma warning disable CS8604 + +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 抽象的跳表基类,提供跳表的基本功能和操作。 + /// + /// 跳表中存储的值的类型。 + public abstract class SkipTableBase : IEnumerable> + { + /// + /// 跳表的最大层数 + /// + public readonly int MaxLayer; + /// + /// 跳表的顶部头节点 + /// + public readonly SkipTableNode TopHeader; + /// + /// 跳表的底部头节点 + /// + public SkipTableNode BottomHeader; + /// + /// 跳表中节点的数量,使用了 Node 字典的计数 + /// + public int Count => Node.Count; + /// + /// 用于生成随机数的随机数生成器 + /// + protected readonly Random Random = new Random(); + /// + /// 存储跳表节点的字典 + /// + protected readonly Dictionary> Node = new(); + /// + /// 用于辅助反向查找的栈 + /// + protected readonly Stack> AntiFindStack = new Stack>(); + + /// + /// 初始化一个新的跳表实例。 + /// + /// 跳表的最大层数,默认为 8。 + protected SkipTableBase(int maxLayer = 8) + { + MaxLayer = maxLayer; + var cur = TopHeader = new SkipTableNode(long.MinValue, 0, 0, default, 0, null, null, null); + + for (var layer = MaxLayer - 1; layer >= 1; --layer) + { + cur.Down = new SkipTableNode(long.MinValue, 0, 0, default, 0, null, null, null); + cur = cur.Down; + } + + BottomHeader = cur; + } + + /// + /// 获取指定键的节点的值,若不存在则返回默认值。 + /// + /// 要查找的键。 + public TValue this[long key] => !TryGetValueByKey(key, out TValue value) ? default : value; + + /// + /// 获取指定键的节点在跳表中的排名。 + /// + /// 要查找的键。 + /// 节点的排名。 + public int GetRanking(long key) + { + if (!Node.TryGetValue(key, out var node)) + { + return 0; + } + + return node.Index; + } + + /// + /// 获取指定键的反向排名,即在比该键更大的节点中的排名。 + /// + /// 要查找的键。 + /// 反向排名。 + public int GetAntiRanking(long key) + { + var ranking = GetRanking(key); + + if (ranking == 0) + { + return 0; + } + + return Count + 1 - ranking; + } + + /// + /// 尝试通过键获取节点的值。 + /// + /// 要查找的键。 + /// 获取到的节点的值,如果键不存在则为默认值。 + /// 是否成功获取节点的值。 + public bool TryGetValueByKey(long key, out TValue value) + { + if (!Node.TryGetValue(key, out var node)) + { + value = default; + return false; + } + + value = node.Value; + return true; + } + + /// + /// 尝试通过键获取节点。 + /// + /// 要查找的键。 + /// 获取到的节点,如果键不存在则为 null。 + /// 是否成功获取节点。 + public bool TryGetNodeByKey(long key, out SkipTableNode node) + { + if (Node.TryGetValue(key, out node)) + { + return true; + } + + return false; + } + + /// + /// 在跳表中查找节点,返回从起始位置到结束位置的节点列表。 + /// + /// 起始位置的排名。 + /// 结束位置的排名。 + /// 用于存储节点列表的 实例。 + public void Find(int start, int end, ListPool> list) + { + var cur = BottomHeader; + var count = end - start; + + for (var i = 0; i < start; i++) + { + cur = cur.Right; + } + + for (var i = 0; i <= count; i++) + { + if (cur == null) + { + break; + } + + list.Add(cur); + cur = cur.Right; + } + } + + /// + /// 在跳表中进行反向查找节点,返回从结束位置到起始位置的节点列表。 + /// + /// 结束位置的排名。 + /// 起始位置的排名。 + /// 用于存储节点列表的 实例。 + public void AntiFind(int start, int end, ListPool> list) + { + var cur = BottomHeader; + start = Count + 1 - start; + end = start - end; + + for (var i = 0; i < start; i++) + { + cur = cur.Right; + + if (cur == null) + { + break; + } + + if (i < end) + { + continue; + } + + AntiFindStack.Push(cur); + } + + while (AntiFindStack.TryPop(out var node)) + { + list.Add(node); + } + } + + /// + /// 获取跳表中最后一个节点的值。 + /// + /// 最后一个节点的值。 + public TValue GetLastValue() + { + var cur = TopHeader; + + while (cur.Right != null || cur.Down != null) + { + while (cur.Right != null) + { + cur = cur.Right; + } + + if (cur.Down != null) + { + cur = cur.Down; + } + } + + return cur.Value; + } + + /// + /// 移除跳表中指定键的节点。 + /// + /// 要移除的节点的键。 + /// 移除是否成功。 + public bool Remove(long key) + { + if (!Node.TryGetValue(key, out var node)) + { + return false; + } + + return Remove(node.SortKey, node.ViceKey, key, out _); + } + + /// + /// 向跳表中添加节点。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的键。 + /// 节点的值。 + public abstract void Add(long sortKey, long viceKey, long key, TValue value); + + /// + /// 从跳表中移除指定键的节点。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的键。 + /// 被移除的节点的值。 + /// 移除是否成功。 + public abstract bool Remove(long sortKey, long viceKey, long key, out TValue value); + + /// + /// 返回一个枚举器,用于遍历跳表中的节点。 + /// + /// 一个可用于遍历跳表节点的枚举器。 + public IEnumerator> GetEnumerator() + { + var cur = BottomHeader.Right; + while (cur != null) + { + yield return cur; + cur = cur.Right; + } + } + + /// + /// 返回一个非泛型枚举器,用于遍历跳表中的节点。 + /// + /// 一个非泛型枚举器,可用于遍历跳表节点。 + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta new file mode 100644 index 0000000..32eb8bb --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83a2a26ccc53b2944b584c0f00010a77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs new file mode 100644 index 0000000..63daa16 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs @@ -0,0 +1,188 @@ + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳表降序版,用于存储降序排列的数据。 + /// + /// 存储的值的类型。 + public class SkipTableDesc : SkipTableBase + { + /// + /// 初始化跳表降序版的新实例。 + /// + /// 跳表的最大层数,默认为 8。 + public SkipTableDesc(int maxLayer = 8) : base(maxLayer) { } + + /// + /// 向跳表中添加一个节点,根据降序规则进行插入。 + /// + /// 排序主键。 + /// 副键。 + /// 键。 + /// 值。 + public override void Add(long sortKey, long viceKey, long key, TValue value) + { + var rLevel = 1; + + while (rLevel <= MaxLayer && Random.Next(3) == 0) + { + ++rLevel; + } + + SkipTableNode cur = TopHeader, last = null; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 节点有next节点,且 (next主键 > 插入主键) 或 (next主键 == 插入主键 且 next副键 > 插入副键) + while (cur.Right != null && ((cur.Right.SortKey > sortKey) || + (cur.Right.SortKey == sortKey && cur.Right.ViceKey > viceKey))) + { + cur = cur.Right; + } + + if (layer <= rLevel) + { + var currentRight = cur.Right; + cur.Right = new SkipTableNode(sortKey, viceKey, key, value, + layer == 1 ? cur.Index + 1 : 0, cur, cur.Right, null); + + if (currentRight != null) + { + currentRight.Left = cur.Right; + } + + if (last != null) + { + last.Down = cur.Right; + } + + if (layer == 1) + { + cur.Right.Index = cur.Index + 1; + Node.Add(key, cur.Right); + + SkipTableNode v = cur.Right.Right; + + while (v != null) + { + v.Index++; + v = v.Right; + } + } + + last = cur.Right; + } + + cur = cur.Down; + } + } + + /// + /// 从跳表中移除一个节点,根据降序规则进行移除。 + /// + /// 排序主键。 + /// 副键。 + /// 键。 + /// 移除的节点值。 + /// 如果成功移除节点,则返回 true,否则返回 false。 + public override bool Remove(long sortKey, long viceKey, long key, out TValue value) + { + value = default; + var seen = false; + var cur = TopHeader; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 先按照主键查找 再 按副键查找 + while (cur.Right != null && cur.Right.SortKey > sortKey && cur.Right.Key != key) cur = cur.Right; + while (cur.Right != null && (cur.Right.SortKey == sortKey && cur.Right.ViceKey >= viceKey) && + cur.Right.Key != key) cur = cur.Right; + + var isFind = false; + var currentCur = cur; + SkipTableNode removeCur = null; + // 如果当前不是要删除的节点、但主键和副键都一样、需要特殊处理下。 + if (cur.Right != null && cur.Right.Key == key) + { + isFind = true; + removeCur = cur.Right; + currentCur = cur; + } + else + { + // 先向左查找下 + var currentNode = cur.Left; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Left; + } + + // 再向右查找下 + if (!isFind) + { + currentNode = cur.Right; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Right; + } + } + } + + if (isFind && currentCur != null) + { + value = removeCur.Value; + currentCur.Right = removeCur.Right; + + if (removeCur.Right != null) + { + removeCur.Right.Left = currentCur; + removeCur.Right = null; + } + + removeCur.Left = null; + removeCur.Down = null; + removeCur.Value = default; + + if (layer == 1) + { + var tempCur = currentCur.Right; + while (tempCur != null) + { + tempCur.Index--; + tempCur = tempCur.Right; + } + + Node.Remove(removeCur.Key); + } + + seen = true; + } + + cur = cur.Down; + } + + return seen; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta new file mode 100644 index 0000000..af18b53 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09af986a342b3e849baefbf4ac89d3a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs new file mode 100644 index 0000000..8a1a144 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs @@ -0,0 +1,68 @@ +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳跃表节点。 + /// + /// 节点的值的类型。 + public class SkipTableNode + { + /// + /// 节点在跳跃表中的索引。 + /// + public int Index; + /// + /// 节点的主键。 + /// + public long Key; + /// + /// 节点的排序键。 + /// + public long SortKey; + /// + /// 节点的副键。 + /// + public long ViceKey; + /// + /// 节点存储的值。 + /// + public TValue Value; + /// + /// 指向左侧节点的引用。 + /// + public SkipTableNode Left; + /// + /// 指向右侧节点的引用。 + /// + public SkipTableNode Right; + /// + /// 指向下一层节点的引用。 + /// + public SkipTableNode Down; + + /// + /// 初始化跳跃表节点的新实例。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的主键。 + /// 节点存储的值。 + /// 节点在跳跃表中的索引。 + /// 指向左侧节点的引用。 + /// 指向右侧节点的引用。 + /// 指向下一层节点的引用。 + public SkipTableNode(long sortKey, long viceKey, long key, TValue value, int index, + SkipTableNode l, + SkipTableNode r, + SkipTableNode d) + { + Left = l; + Right = r; + Down = d; + Value = value; + Key = key; + Index = index; + SortKey = sortKey; + ViceKey = viceKey; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta new file mode 100644 index 0000000..eca7ab3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3e595e0020a2617459acb309bfa358e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas.meta b/Runtime/CoreRuntime/Core/Entitas.meta new file mode 100644 index 0000000..0d0c93d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7bc366ba0b3bd19448ee206bd301c4b6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component.meta b/Runtime/CoreRuntime/Core/Entitas/Component.meta new file mode 100644 index 0000000..1900a7f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 867c936612958bd41b6d17cac30a5222 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock.meta b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock.meta new file mode 100644 index 0000000..b680323 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: baebd19f76ed92c4f906ae78fdea6a26 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs new file mode 100644 index 0000000..a95d8f3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Async +{ + /// + /// 协程锁专用的对象池 + /// + public sealed class CoroutineLockPool : PoolCore + { + /// + /// 协程锁专用的对象池的构造函数 + /// + public CoroutineLockPool() : base(2000) { } + } + + /// + /// 协程锁 + /// + public sealed class CoroutineLock : IPool, IDisposable + { + private Scene _scene; + private CoroutineLockComponent _coroutineLockComponent; + private readonly Dictionary _queue = new Dictionary(); + /// + /// 表示是否是对象池中创建的 + /// + private bool _isPool; + /// + /// 协程锁的类型 + /// + public long CoroutineLockType { get; private set; } + + internal void Initialize(CoroutineLockComponent coroutineLockComponent, ref long coroutineLockType) + { + _scene = coroutineLockComponent.Scene; + CoroutineLockType = coroutineLockType; + _coroutineLockComponent = coroutineLockComponent; + } + /// + /// 销毁协程锁,如果调用了该方法,所有使用当前协程锁等待的逻辑会按照顺序释放锁。 + /// + public void Dispose() + { + foreach (var (_, coroutineLockQueue) in _queue) + { + while (TryCoroutineLockQueueDequeue(coroutineLockQueue)) { } + } + + _queue.Clear(); + _scene = null; + CoroutineLockType = 0; + _coroutineLockComponent = null; + } + /// + /// 等待上一个任务完成 + /// + /// 需要等待的Id + /// 用于查询协程锁的标记,可不传入,只有在超时的时候排查是哪个锁超时时使用 + /// 等待多久会超时,当到达设定的时候会把当前锁给按照超时处理 + /// + public async FTask Wait(long coroutineLockQueueKey, string tag = null, int timeOut = 30000) + { + var waitCoroutineLock = _coroutineLockComponent.WaitCoroutineLockPool.Rent(this, ref coroutineLockQueueKey, tag, timeOut); + + if (!_queue.TryGetValue(coroutineLockQueueKey, out var queue)) + { + queue = _coroutineLockComponent.CoroutineLockQueuePool.Rent(); + _queue.Add(coroutineLockQueueKey, queue); + return waitCoroutineLock; + } + + queue.Enqueue(waitCoroutineLock); + return await waitCoroutineLock.Tcs; + } + /// + /// 按照先入先出的顺序,释放最早的一个协程锁 + /// + /// + public void Release(long coroutineLockQueueKey) + { + if (!_queue.TryGetValue(coroutineLockQueueKey, out var coroutineLockQueue)) + { + return; + } + + if (!TryCoroutineLockQueueDequeue(coroutineLockQueue)) + { + _queue.Remove(coroutineLockQueueKey); + } + } + + private bool TryCoroutineLockQueueDequeue(CoroutineLockQueue coroutineLockQueue) + { + if (!coroutineLockQueue.TryDequeue(out var waitCoroutineLock)) + { + _coroutineLockComponent.CoroutineLockQueuePool.Return(coroutineLockQueue); + return false; + } + + if (waitCoroutineLock.TimerId != 0) + { + _scene.TimerComponent.Net.Remove(waitCoroutineLock.TimerId); + } + + try + { + // 放到下一帧执行,如果不这样会导致逻辑的顺序不正常。 + _scene.ThreadSynchronizationContext.Post(waitCoroutineLock.SetResult); + } + catch (Exception e) + { + Log.Error($"Error in disposing CoroutineLock: {e}"); + } + + return true; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta new file mode 100644 index 0000000..4031fdf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22b8b5b1a65e771448ba3d0766a111ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs new file mode 100644 index 0000000..fe03298 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs @@ -0,0 +1,100 @@ +using System.Collections.Generic; +using Fantasy.Entitas; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Async +{ + /// + /// 协程锁组件 + /// + public class CoroutineLockComponent : Entity + { + private long _lockId; + private CoroutineLockPool _coroutineLockPool; + internal WaitCoroutineLockPool WaitCoroutineLockPool { get; private set; } + internal CoroutineLockQueuePool CoroutineLockQueuePool { get; private set; } + private readonly Dictionary _coroutineLocks = new Dictionary(); + internal CoroutineLockComponent Initialize() + { + _coroutineLockPool = new CoroutineLockPool(); + CoroutineLockQueuePool = new CoroutineLockQueuePool(); + WaitCoroutineLockPool = new WaitCoroutineLockPool(this); + return this; + } + + internal long LockId => ++_lockId; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public override void Dispose() +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + { + if (IsDisposed) + { + return; + } + + _lockId = 0; + base.Dispose(); + } + + /// + /// 创建一个新的协程锁 + /// 使用这个方法创建的协程锁,需要手动释放管理CoroutineLock。 + /// 不会再CoroutineLockComponent理进行管理。 + /// + /// + /// + public CoroutineLock Create(long coroutineLockType) + { + var coroutineLock = _coroutineLockPool.Rent(); + coroutineLock.Initialize(this, ref coroutineLockType); + return coroutineLock; + } + + /// + /// 请求一个协程锁。 + /// 使用这个方法创建的协程锁,会自动释放CoroutineLockQueueType。 + /// + /// 锁类型 + /// 锁队列Id + /// 当某些锁超时,需要一个标记来方便排查问题,正常的情况下这个默认为null就可以。 + /// 设置锁的超时时间,让超过设置的时间会触发超时,保证锁不会因为某一个锁一直不解锁导致卡住的问题。 + /// + /// 返回的WaitCoroutineLock通过Dispose来解除这个锁、建议用using来保住这个锁。 + /// 也可以返回的WaitCoroutineLock通过CoroutineLockComponent.UnLock来解除这个锁。 + /// + public FTask Wait(long coroutineLockType, long coroutineLockQueueKey, string tag = null, int time = 30000) + { + if (!_coroutineLocks.TryGetValue(coroutineLockType, out var coroutineLock)) + { + coroutineLock = _coroutineLockPool.Rent(); + coroutineLock.Initialize(this, ref coroutineLockType); + _coroutineLocks.Add(coroutineLockType, coroutineLock); + } + + return coroutineLock.Wait(coroutineLockQueueKey, tag, time); + } + + /// + /// 解除一个协程锁。 + /// + /// + /// + public void Release(long coroutineLockType, long coroutineLockQueueKey) + { + if (IsDisposed) + { + return; + } + + if (!_coroutineLocks.TryGetValue(coroutineLockType, out var coroutineLock)) + { + return; + } + + coroutineLock.Release(coroutineLockQueueKey); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta new file mode 100644 index 0000000..76a23d9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8db8b6852dd4a5b468b72a1644a1b05e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs new file mode 100644 index 0000000..2948aca --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs @@ -0,0 +1,35 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Async +{ + internal sealed class CoroutineLockQueuePool : PoolCore + { + public CoroutineLockQueuePool() : base(2000) { } + } + + internal sealed class CoroutineLockQueue : Queue, IPool + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta new file mode 100644 index 0000000..a7434c2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60315d8bd80b35a49bed294a6a3a5e96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs new file mode 100644 index 0000000..28d04d4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs @@ -0,0 +1,146 @@ +using System; +using Fantasy.Event; +using Fantasy.Pool; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Async +{ + internal sealed class WaitCoroutineLockPool : PoolCore + { + private readonly Scene _scene; + private readonly CoroutineLockComponent _coroutineLockComponent; + + public WaitCoroutineLockPool(CoroutineLockComponent coroutineLockComponent) : base(2000) + { + _scene = coroutineLockComponent.Scene; + _coroutineLockComponent = coroutineLockComponent; + } + + public WaitCoroutineLock Rent(CoroutineLock coroutineLock, ref long coroutineLockQueueKey, string tag = null, int timeOut = 30000) + { + var timerId = 0L; + var lockId = _coroutineLockComponent.LockId; + var waitCoroutineLock = _coroutineLockComponent.WaitCoroutineLockPool.Rent(); + + if (timeOut > 0) + { + timerId = _scene.TimerComponent.Net.OnceTimer(timeOut, new CoroutineLockTimeout(ref lockId, waitCoroutineLock)); + } + + waitCoroutineLock.Initialize(coroutineLock, this, ref coroutineLockQueueKey, ref timerId, ref lockId, tag); + return waitCoroutineLock; + } + } + + internal struct CoroutineLockTimeout + { + public readonly long LockId; + public readonly WaitCoroutineLock WaitCoroutineLock; + + public CoroutineLockTimeout(ref long lockId, WaitCoroutineLock waitCoroutineLock) + { + LockId = lockId; + WaitCoroutineLock = waitCoroutineLock; + } + } + + internal sealed class OnCoroutineLockTimeout : EventSystem + { + protected override void Handler(CoroutineLockTimeout self) + { + var selfWaitCoroutineLock = self.WaitCoroutineLock; + + if (self.LockId != selfWaitCoroutineLock.LockId) + { + return; + } + + Log.Error($"coroutine lock timeout CoroutineLockQueueType:{selfWaitCoroutineLock.CoroutineLock.CoroutineLockType} Key:{selfWaitCoroutineLock.CoroutineLockQueueKey} Tag:{selfWaitCoroutineLock.Tag}"); + } + } + + /// + /// 一个协程锁的实例,用户可以用过这个手动释放锁 + /// + public sealed class WaitCoroutineLock : IPool, IDisposable + { + private bool _isPool; + internal string Tag { get; private set; } + internal long LockId { get; private set; } + internal long TimerId { get; private set; } + internal long CoroutineLockQueueKey { get; private set; } + internal CoroutineLock CoroutineLock { get; private set; } + + private bool _isSetResult; + private FTask _tcs; + private WaitCoroutineLockPool _waitCoroutineLockPool; + internal void Initialize(CoroutineLock coroutineLock, WaitCoroutineLockPool waitCoroutineLockPool, ref long coroutineLockQueueKey, ref long timerId, ref long lockId, string tag) + { + Tag = tag; + LockId = lockId; + TimerId = timerId; + CoroutineLock = coroutineLock; + CoroutineLockQueueKey = coroutineLockQueueKey; + _waitCoroutineLockPool = waitCoroutineLockPool; + } + /// + /// 释放协程锁 + /// + public void Dispose() + { + if (LockId == 0) + { + Log.Error("WaitCoroutineLock is already disposed"); + return; + } + + CoroutineLock.Release(CoroutineLockQueueKey); + + _tcs = null; + Tag = null; + LockId = 0; + TimerId = 0; + _isSetResult = false; + CoroutineLockQueueKey = 0; + _waitCoroutineLockPool.Return(this); + CoroutineLock = null; + _waitCoroutineLockPool = null; + } + + internal FTask Tcs + { + get { return _tcs ??= FTask.Create(); } + } + + internal void SetResult() + { + if (_isSetResult) + { + Log.Error("WaitCoroutineLock is already SetResult"); + return; + } + + _isSetResult = true; + Tcs.SetResult(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta new file mode 100644 index 0000000..0e52f4d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96259a5dd985c0840b98b94f436980f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs new file mode 100644 index 0000000..67dc9ef --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs @@ -0,0 +1,523 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8765 // Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes). + +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas +{ + internal sealed class UpdateQueueInfo + { + public bool IsStop; + public readonly Type Type; + public readonly long RunTimeId; + + public UpdateQueueInfo(Type type, long runTimeId) + { + Type = type; + IsStop = false; + RunTimeId = runTimeId; + } + } + + internal sealed class FrameUpdateQueueInfo + { + public readonly Type Type; + public readonly long RunTimeId; + + public FrameUpdateQueueInfo(Type type, long runTimeId) + { + Type = type; + RunTimeId = runTimeId; + } + } + + internal struct CustomEntitiesSystemKey : IEquatable + { + public int CustomEventType { get; } + public Type EntitiesType { get; } + public CustomEntitiesSystemKey(int customEventType, Type entitiesType) + { + CustomEventType = customEventType; + EntitiesType = entitiesType; + } + public bool Equals(CustomEntitiesSystemKey other) + { + return CustomEventType == other.CustomEventType && EntitiesType == other.EntitiesType; + } + + public override bool Equals(object obj) + { + return obj is CustomEntitiesSystemKey other && Equals(other); + } + + public override int GetHashCode() + { + return HashCode.Combine(CustomEventType, EntitiesType); + } + } + + /// + /// Entity管理组件 + /// +#if FANTASY_UNITY + public sealed class EntityComponent : Entity, ISceneUpdate, ISceneLateUpdate, IAssembly +#else + public sealed class EntityComponent : Entity, ISceneUpdate, IAssembly +#endif + { + private readonly OneToManyList _assemblyList = new(); + private readonly OneToManyList _assemblyHashCodes = new(); + + private readonly Dictionary _awakeSystems = new(); + private readonly Dictionary _updateSystems = new(); + private readonly Dictionary _destroySystems = new(); + private readonly Dictionary _deserializeSystems = new(); + + private readonly OneToManyList _assemblyCustomSystemList = new(); + private readonly Dictionary _customEntitiesSystems = new Dictionary(); + + private readonly Dictionary _hashCodes = new Dictionary(); + private readonly Queue _updateQueue = new Queue(); + + private readonly Dictionary _updateQueueDic = new Dictionary(); +#if FANTASY_UNITY + private readonly Dictionary _lateUpdateSystems = new(); + private readonly Queue _lateUpdateQueue = new Queue(); + private readonly Dictionary _lateUpdateQueueDic = new Dictionary(); +#endif + + internal async FTask Initialize() + { + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public FTask Load(long assemblyIdentity) + { + var task = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + task.SetResult(); + }); + return task; + } + + public FTask ReLoad(long assemblyIdentity) + { + var task = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + task.SetResult(); + }); + + return task; + } + + public FTask OnUnLoad(long assemblyIdentity) + { + var task = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + task.SetResult(); + }); + return task; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var entityType in AssemblySystem.ForEach(assemblyIdentity, typeof(IEntity))) + { + _hashCodes.Add(entityType, HashCodeHelper.ComputeHash64(entityType.FullName)); + _assemblyHashCodes.Add(assemblyIdentity, entityType); + } + + foreach (var entitiesSystemType in AssemblySystem.ForEach(assemblyIdentity, typeof(IEntitiesSystem))) + { + Type entitiesType = null; + var entity = Activator.CreateInstance(entitiesSystemType); + + switch (entity) + { + case IAwakeSystem iAwakeSystem: + { + entitiesType = iAwakeSystem.EntitiesType(); + _awakeSystems.Add(entitiesType, iAwakeSystem); + break; + } + case IDestroySystem iDestroySystem: + { + entitiesType = iDestroySystem.EntitiesType(); + _destroySystems.Add(entitiesType, iDestroySystem); + break; + } + case IDeserializeSystem iDeserializeSystem: + { + entitiesType = iDeserializeSystem.EntitiesType(); + _deserializeSystems.Add(entitiesType, iDeserializeSystem); + break; + } + case IUpdateSystem iUpdateSystem: + { + entitiesType = iUpdateSystem.EntitiesType(); + _updateSystems.Add(entitiesType, iUpdateSystem); + break; + } +#if FANTASY_UNITY + case ILateUpdateSystem iLateUpdateSystem: + { + entitiesType = iLateUpdateSystem.EntitiesType(); + _lateUpdateSystems.Add(entitiesType, iLateUpdateSystem); + break; + } +#endif + default: + { + Log.Error($"IEntitiesSystem not support type {entitiesSystemType}"); + return; + } + } + + _assemblyList.Add(assemblyIdentity, entitiesType); + } + + foreach (var customEntitiesSystemType in AssemblySystem.ForEach(assemblyIdentity, typeof(ICustomEntitiesSystem))) + { + var entity = (ICustomEntitiesSystem)Activator.CreateInstance(customEntitiesSystemType); + var customEntitiesSystemKey = new CustomEntitiesSystemKey(entity.CustomEventType, entity.EntitiesType()); + _customEntitiesSystems.Add(customEntitiesSystemKey, entity); + _assemblyCustomSystemList.Add(assemblyIdentity, customEntitiesSystemKey); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (_assemblyHashCodes.TryGetValue(assemblyIdentity, out var entityType)) + { + foreach (var type in entityType) + { + _hashCodes.Remove(type); + } + + _assemblyHashCodes.RemoveByKey(assemblyIdentity); + } + + if (_assemblyList.TryGetValue(assemblyIdentity, out var assembly)) + { + foreach (var type in assembly) + { + _awakeSystems.Remove(type); + _updateSystems.Remove(type); + _destroySystems.Remove(type); +#if FANTASY_UNITY + _lateUpdateSystems.Remove(type); +#endif + _deserializeSystems.Remove(type); + } + + _assemblyList.RemoveByKey(assemblyIdentity); + } + + if (_assemblyCustomSystemList.TryGetValue(assemblyIdentity, out var customSystemAssembly)) + { + foreach (var customEntitiesSystemKey in customSystemAssembly) + { + _customEntitiesSystems.Remove(customEntitiesSystemKey); + } + + _assemblyCustomSystemList.RemoveByKey(assemblyIdentity); + } + } + + #endregion + + #region Event + + /// + /// 触发实体的唤醒方法 + /// + /// 实体对象 + public void Awake(Entity entity) + { + if (!_awakeSystems.TryGetValue(entity.Type, out var awakeSystem)) + { + return; + } + + try + { + awakeSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Error {e}"); + } + } + + /// + /// 触发实体的销毁方法 + /// + /// 实体对象 + public void Destroy(Entity entity) + { + if (!_destroySystems.TryGetValue(entity.Type, out var system)) + { + return; + } + + try + { + system.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Destroy Error {e}"); + } + } + + /// + /// 触发实体的反序列化方法 + /// + /// 实体对象 + public void Deserialize(Entity entity) + { + if (!_deserializeSystems.TryGetValue(entity.Type, out var system)) + { + return; + } + + try + { + system.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Deserialize Error {e}"); + } + } + + #endregion + + #region CustomEvent + + public void CustomSystem(Entity entity, int customEventType) + { + var customEntitiesSystemKey = new CustomEntitiesSystemKey(customEventType, entity.Type); + + if (!_customEntitiesSystems.TryGetValue(customEntitiesSystemKey, out var system)) + { + return; + } + + try + { + system.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} CustomSystem Error {e}"); + } + } + + #endregion + + #region Update + + /// + /// 将实体加入Update队列,准备进行Update + /// + /// 实体对象 + public void StartUpdate(Entity entity) + { + var type = entity.Type; + var entityRuntimeId = entity.RuntimeId; + + if (!_updateSystems.ContainsKey(type)) + { + return; + } + + var updateQueueInfo = new UpdateQueueInfo(type, entityRuntimeId); + _updateQueue.Enqueue(updateQueueInfo); + _updateQueueDic.Add(entityRuntimeId, updateQueueInfo); + } + + /// + /// 停止实体Update + /// + /// 实体对象 + public void StopUpdate(Entity entity) + { + if (!_updateQueueDic.Remove(entity.RuntimeId, out var updateQueueInfo)) + { + return; + } + + updateQueueInfo.IsStop = true; + } + + /// + /// 执行实体系统的Update + /// + public void Update() + { + var updateQueueCount = _updateQueue.Count; + + while (updateQueueCount-- > 0) + { + var updateQueueStruct = _updateQueue.Dequeue(); + + if (updateQueueStruct.IsStop) + { + continue; + } + + if (!_updateSystems.TryGetValue(updateQueueStruct.Type, out var updateSystem)) + { + continue; + } + + var entity = Scene.GetEntity(updateQueueStruct.RunTimeId); + + if (entity == null || entity.IsDisposed) + { + _updateQueueDic.Remove(updateQueueStruct.RunTimeId); + continue; + } + + _updateQueue.Enqueue(updateQueueStruct); + + try + { + updateSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{updateQueueStruct.Type.FullName} Update Error {e}"); + } + } + } + + #endregion + +#if FANTASY_UNITY + #region LateUpdate + + /// + /// 将实体加入LateUpdate队列,准备进行LateUpdate + /// + /// 实体对象 + public void StartLateUpdate(Entity entity) + { + var type = entity.Type; + var entityRuntimeId = entity.RuntimeId; + + if (!_lateUpdateSystems.ContainsKey(type)) + { + return; + } + + var updateQueueInfo = new UpdateQueueInfo(type, entityRuntimeId); + _lateUpdateQueue.Enqueue(updateQueueInfo); + _lateUpdateQueueDic.Add(entityRuntimeId, updateQueueInfo); + } + + /// + /// 停止实体进行LateUpdate + /// + /// 实体对象 + public void StopLateUpdate(Entity entity) + { + if (!_lateUpdateQueueDic.Remove(entity.RuntimeId, out var updateQueueInfo)) + { + return; + } + + updateQueueInfo.IsStop = true; + } + + public void LateUpdate() + { + var lateUpdateQueue = _lateUpdateQueue.Count; + + while (lateUpdateQueue-- > 0) + { + var lateUpdateQueueStruct = _lateUpdateQueue.Dequeue(); + + if (lateUpdateQueueStruct.IsStop) + { + continue; + } + + if (!_lateUpdateSystems.TryGetValue(lateUpdateQueueStruct.Type, out var lateUpdateSystem)) + { + continue; + } + + var entity = Scene.GetEntity(lateUpdateQueueStruct.RunTimeId); + + if (entity == null || entity.IsDisposed) + { + _lateUpdateQueueDic.Remove(lateUpdateQueueStruct.RunTimeId); + continue; + } + + _lateUpdateQueue.Enqueue(lateUpdateQueueStruct); + + try + { + lateUpdateSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{lateUpdateQueueStruct.Type.FullName} Update Error {e}"); + } + } + } + #endregion +#endif + public long GetHashCode(Type type) + { + return _hashCodes[type]; + } + + /// + /// 释放实体系统管理器资源 + /// + public override void Dispose() + { + _updateQueue.Clear(); + _updateQueueDic.Clear(); +#if FANTASY_UNITY + _lateUpdateQueue.Clear(); + _lateUpdateQueueDic.Clear(); + _lateUpdateSystems.Clear(); +#endif + _assemblyList.Clear(); + _awakeSystems.Clear(); + _updateSystems.Clear(); + _destroySystems.Clear(); + _deserializeSystems.Clear(); + + AssemblySystem.UnRegister(this); + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs.meta new file mode 100644 index 0000000..a083043 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EntityComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6675e0b1ce6132740b32deb688da4f67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent.meta b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent.meta new file mode 100644 index 0000000..fa53dac --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b8cdd44264dbba64e97d74274877d6ce +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs new file mode 100644 index 0000000..30ca61e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs @@ -0,0 +1,252 @@ +using System; +using System.Reflection; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; + +// ReSharper disable PossibleMultipleEnumeration +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// ReSharper disable MethodOverloadWithOptionalParameter + +namespace Fantasy.Event +{ + internal sealed class EventCache + { + public readonly Type EnventType; + public readonly object Obj; + public EventCache(Type enventType, object obj) + { + EnventType = enventType; + Obj = obj; + } + } + + public sealed class EventComponent : Entity, IAssembly + { + private readonly OneToManyList _events = new(); + private readonly OneToManyList _asyncEvents = new(); + private readonly OneToManyList _assemblyEvents = new(); + private readonly OneToManyList _assemblyAsyncEvents = new(); + + internal async FTask Initialize() + { + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public async FTask Load(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask ReLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask OnUnLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IEvent))) + { + var @event = (IEvent)Activator.CreateInstance(type); + + if (@event == null) + { + continue; + } + + var eventType = @event.EventType(); + _events.Add(eventType, @event); + _assemblyEvents.Add(assemblyIdentity, new EventCache(eventType, @event)); + } + + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IAsyncEvent))) + { + var @event = (IAsyncEvent)Activator.CreateInstance(type); + + if (@event == null) + { + continue; + } + + var eventType = @event.EventType(); + _asyncEvents.Add(eventType, @event); + _assemblyAsyncEvents.Add(assemblyIdentity, new EventCache(eventType, @event)); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (_assemblyEvents.TryGetValue(assemblyIdentity, out var events)) + { + foreach (var @event in events) + { + _events.RemoveValue(@event.EnventType, (IEvent)@event.Obj); + } + + _assemblyEvents.RemoveByKey(assemblyIdentity); + } + + if (_assemblyAsyncEvents.TryGetValue(assemblyIdentity, out var asyncEvents)) + { + foreach (var @event in asyncEvents) + { + _asyncEvents.RemoveValue(@event.EnventType, (IAsyncEvent)@event.Obj); + } + + _assemblyAsyncEvents.RemoveByKey(assemblyIdentity); + } + } + + #endregion + + #region Publish + + /// + /// 发布一个值类型的事件数据。 + /// + /// 事件数据类型(值类型)。 + /// 事件数据实例。 + public void Publish(TEventData eventData) where TEventData : struct + { + if (!_events.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + foreach (var @event in list) + { + try + { + @event.Invoke(eventData); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + /// + /// 发布一个继承自 Entity 的事件数据。 + /// + /// 事件数据类型(继承自 Entity)。 + /// 事件数据实例。 + /// 是否释放事件数据。 + public void Publish(TEventData eventData, bool isDisposed = true) where TEventData : Entity + { + if (!_events.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + foreach (var @event in list) + { + try + { + @event.Invoke(eventData); + } + catch (Exception e) + { + Log.Error(e); + } + } + + if (isDisposed) + { + eventData.Dispose(); + } + } + + /// + /// 异步发布一个值类型的事件数据。 + /// + /// 事件数据类型(值类型)。 + /// 事件数据实例。 + /// 表示异步操作的任务。 + public async FTask PublishAsync(TEventData eventData) where TEventData : struct + { + if (!_asyncEvents.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + using var tasks = ListPool.Create(); + + foreach (var @event in list) + { + tasks.Add(@event.InvokeAsync(eventData)); + } + + await FTask.WaitAll(tasks); + } + + /// + /// 异步发布一个继承自 Entity 的事件数据。 + /// + /// 事件数据类型(继承自 Entity)。 + /// 事件数据实例。 + /// 是否释放事件数据。 + /// 表示异步操作的任务。 + public async FTask PublishAsync(TEventData eventData, bool isDisposed = true) where TEventData : Entity + { + if (!_asyncEvents.TryGetValue(eventData.GetType(), out var list)) + { + return; + } + + using var tasks = ListPool.Create(); + + foreach (var @event in list) + { + tasks.Add(@event.InvokeAsync(eventData)); + } + + await FTask.WaitAll(tasks); + + if (isDisposed) + { + eventData.Dispose(); + } + } + + #endregion + + public override void Dispose() + { + _events.Clear(); + _asyncEvents.Clear(); + _assemblyEvents.Clear(); + _assemblyAsyncEvents.Clear(); + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta new file mode 100644 index 0000000..a767fac --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79cf9c100979df446981ba0213f51c6e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface.meta b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface.meta new file mode 100644 index 0000000..7dfaec4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 58c5047ecf7aa0c4aad4d613aa534b1d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs new file mode 100644 index 0000000..5314995 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs @@ -0,0 +1,112 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Event +{ + /// + /// 事件的接口 + /// + public interface IEvent + { + /// + /// 用于指定事件的Type + /// + /// + Type EventType(); + /// + /// 时间内部使用的入口 + /// + /// + void Invoke(object self); + } + + /// + /// 异步事件的接口 + /// + public interface IAsyncEvent + { + /// + /// + /// + /// + Type EventType(); + /// + /// + /// + /// + FTask InvokeAsync(object self); + } + + /// + /// 事件的抽象类,要使用事件必须要继承这个抽象接口。 + /// + /// 要监听的事件泛型类型 + public abstract class EventSystem : IEvent + { + private readonly Type _selfType = typeof(T); + /// + /// + /// + /// + public Type EventType() + { + return _selfType; + } + /// + /// 事件调用的方法,要在这个方法里编写事件发生的逻辑 + /// + /// + protected abstract void Handler(T self); + /// + /// + /// + /// + public void Invoke(object self) + { + try + { + Handler((T) self); + } + catch (Exception e) + { + Log.Error($"{_selfType.Name} Error {e}"); + } + } + } + /// + /// 异步事件的抽象类,要使用事件必须要继承这个抽象接口。 + /// + /// 要监听的事件泛型类型 + public abstract class AsyncEventSystem : IAsyncEvent + { + private readonly Type _selfType = typeof(T); + /// + /// + /// + /// + public Type EventType() + { + return _selfType; + } + /// + /// 事件调用的方法,要在这个方法里编写事件发生的逻辑 + /// + /// + protected abstract FTask Handler(T self); + /// + /// + /// + /// + public async FTask InvokeAsync(object self) + { + try + { + await Handler((T) self); + } + catch (Exception e) + { + Log.Error($"{_selfType.Name} Error {e}"); + } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta new file mode 100644 index 0000000..bad45dc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6aa7440e0340d9b4eb746ea3450c3fde +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs new file mode 100644 index 0000000..f1ddb23 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs @@ -0,0 +1,139 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Pool; +using Fantasy.Serialize; + +namespace Fantasy.Entitas +{ + /// + /// 消息的对象池组件 + /// + public sealed class MessagePoolComponent : Entity + { + private int _poolCount; + private const int MaxCapacity = ushort.MaxValue; + private readonly OneToManyQueue _poolQueue = new OneToManyQueue(); + private readonly Dictionary> _typeCheckCache = new Dictionary>(); + /// + /// 销毁组件 + /// + public override void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + _typeCheckCache.Clear(); + base.Dispose(); + } + /// + /// 从对象池里获取一个消息,如果没有就创建一个新的 + /// + /// 消息的泛型类型 + /// + public T Rent() where T : AMessage, new() + { + if (!_poolQueue.TryDequeue(typeof(T), out var queue)) + { + var instance = new T(); + instance.SetScene(Scene); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return (T)queue; + } + + /// + /// + /// + /// 消息的类型 + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public AMessage Rent(Type type) + { + if (!_poolQueue.TryDequeue(type, out var queue)) + { + if (!_typeCheckCache.TryGetValue(type, out var createInstance)) + { + if (!typeof(AMessage).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{this.GetType().FullName} Type:{type.FullName} must inherit from IPool"); + } + else + { + createInstance = CreateInstance.CreateMessage(type); + _typeCheckCache[type] = createInstance; + } + } + + var instance = createInstance(); + instance.SetScene(Scene); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return queue; + } + /// + /// 返还一个消息到对象池中 + /// + /// + public void Return(AMessage obj) + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= MaxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(obj.GetType(), obj); + } + + /// + /// + /// + /// 返还的消息 + /// 返还的消息泛型类型 + public void Return(T obj) where T : AMessage + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= MaxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(typeof(T), obj); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs.meta new file mode 100644 index 0000000..578a07a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/MessagePoolComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5524b80cac2acbc4c9b32d04bc4d91fa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent.meta b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent.meta new file mode 100644 index 0000000..2e13fb6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0b4805c91a18d29419ef1838791efa0e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs new file mode 100644 index 0000000..5c0969d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs @@ -0,0 +1,167 @@ +// ReSharper disable SuspiciousTypeConversion.Global + +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#if FANTASY_NET +namespace Fantasy.SingleCollection +{ + /// + /// 用于处理Entity下的实体进行数据库分表存储的组件 + /// + public sealed class SingleCollectionComponent : Entity, IAssembly + { + private CoroutineLock _coroutineLock; + private readonly OneToManyHashSet _collection = new OneToManyHashSet(); + + private readonly OneToManyList _assemblyCollections = + new OneToManyList(); + + private sealed class SingleCollectionInfo(Type rootType, string collectionName) + { + public readonly Type RootType = rootType; + public readonly string CollectionName = collectionName; + } + + internal async FTask Initialize() + { + var coroutineLockType = HashCodeHelper.ComputeHash64(GetType().FullName); + _coroutineLock = Scene.CoroutineLockComponent.Create(coroutineLockType); + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public async FTask Load(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask ReLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask OnUnLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(ISupportedSingleCollection))) + { + var customAttributes = type.GetCustomAttributes(typeof(SingleCollectionAttribute), false); + if (customAttributes.Length == 0) + { + Log.Error( + $"type {type.FullName} Implemented the interface of ISingleCollection, requiring the implementation of SingleCollectionAttribute"); + continue; + } + + var singleCollectionAttribute = (SingleCollectionAttribute)customAttributes[0]; + var rootType = singleCollectionAttribute.RootType; + var collectionName = singleCollectionAttribute.CollectionName; + _collection.Add(rootType, collectionName); + _assemblyCollections.Add(assemblyIdentity, new SingleCollectionInfo(rootType, collectionName)); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (!_assemblyCollections.TryGetValue(assemblyIdentity, out var types)) + { + return; + } + + foreach (var singleCollectionInfo in types) + { + _collection.RemoveValue(singleCollectionInfo.RootType, singleCollectionInfo.CollectionName); + } + + _assemblyCollections.RemoveByKey(assemblyIdentity); + } + + #endregion + + #region Collections + + /// + /// 通过数据库获取某一个实体类型下所有的分表数据到当前实体下,并且会自动建立父子关系。 + /// + /// 实体实例 + /// 实体泛型类型 + public async FTask GetCollections(T entity) where T : Entity, ISingleCollectionRoot + { + if (!_collection.TryGetValue(typeof(T), out var collections)) + { + return; + } + + var worldDateBase = Scene.World.DataBase; + + using (await _coroutineLock.Wait(entity.Id)) + { + foreach (var collectionName in collections) + { + var singleCollection = await worldDateBase.QueryNotLock(entity.Id, true, collectionName); + entity.AddComponent(singleCollection); + } + } + } + + /// + /// 存储当前实体下支持分表的组件到数据中,包括存储实体本身。 + /// + /// 实体实例 + /// 实体泛型类型 + public async FTask SaveCollections(T entity) where T : Entity, ISingleCollectionRoot + { + using var collections = ListPool.Create(); + + foreach (var treeEntity in entity.ForEachSingleCollection) + { + if (treeEntity is not ISupportedSingleCollection) + { + continue; + } + + collections.Add(treeEntity); + } + + collections.Add(entity); + await entity.Scene.World.DataBase.Save(entity.Id, collections); + } + + #endregion + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta new file mode 100644 index 0000000..c2da151 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de8460d7105238f4aba4d5b3107c8bba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent.meta new file mode 100644 index 0000000..c632abb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0e451226147c21744a020c00cc48b760 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface.meta new file mode 100644 index 0000000..f1819fc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 31d9e54fda3dd74468a79468737c4866 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs new file mode 100644 index 0000000..9e1f4c9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs @@ -0,0 +1,10 @@ +using Fantasy.Event; + +namespace Fantasy.Timer +{ + /// + /// 计时器抽象类,提供了一个基础框架,用于创建处理计时器事件的具体类。 + /// + /// 事件的类型参数 + public abstract class TimerHandler : EventSystem { } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta new file mode 100644 index 0000000..05e3deb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 640129a66850ea143a68e9d82f6a3e9d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel.meta new file mode 100644 index 0000000..6e1f72c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8d02e65b44372ae4abb92fbdaee74700 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs new file mode 100644 index 0000000..d644386 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs @@ -0,0 +1,49 @@ +// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// namespace Fantasy +// { +// public sealed class ScheduledTaskPool : PoolCore +// { +// public ScheduledTaskPool() : base(2000) { } +// +// public ScheduledTask Rent(Action action, ref int rounds, ref int finalSlot) +// { +// var scheduledTask = Rent(); +// scheduledTask.Rounds = rounds; +// scheduledTask.Action = action; +// scheduledTask.FinalSlot = finalSlot; +// return scheduledTask; +// } +// +// public override void Return(ScheduledTask item) +// { +// base.Return(item); +// item.Dispose(); +// } +// } +// +// public sealed class ScheduledTask : IPool, IDisposable +// { +// public int Rounds; +// public int FinalSlot; +// public Action Action; +// public LinkedListNode Node; +// +// public bool IsPool { get; set; } +// public ScheduledTask() { } +// public ScheduledTask(Action action, ref int rounds, ref int finalSlot) +// { +// Action = action; +// Rounds = rounds; +// FinalSlot = finalSlot; +// } +// +// public void Dispose() +// { +// Rounds = 0; +// FinalSlot = 0; +// Action = null; +// Node = null; +// } +// } +// } \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta new file mode 100644 index 0000000..d16bcd2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d50b57ed61803854d84db6c8e3e2ecfe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs new file mode 100644 index 0000000..58916b1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs @@ -0,0 +1,134 @@ +// using System.Runtime.CompilerServices; +// // ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// +// namespace Fantasy +// { +// public sealed class TimeWheel +// { +// private int _currentIndex; +// private ScheduledTaskPool _scheduledTaskPool; +// +// private readonly Scene _scene; +// private readonly int _wheelSize; +// private readonly int _tickDuration; +// private readonly TimeWheel _upperLevelWheel; +// private readonly LinkedList[] _wheel; +// private readonly Queue _tasksToReschedule = new Queue(); +// private readonly Dictionary _taskDictionary = new Dictionary(); +// +// public TimeWheel(TimerComponent timerComponent, int wheelSize, int tickDuration, TimeWheel upperLevelWheel = null) +// { +// _scene = timerComponent.Scene; +// _wheelSize = wheelSize; +// _tickDuration = tickDuration; +// _upperLevelWheel = upperLevelWheel; +// _scheduledTaskPool = timerComponent.ScheduledTaskPool; +// _wheel = new LinkedList[_wheelSize]; +// for (var i = 0; i < wheelSize; i++) +// { +// _wheel[i] = new LinkedList(); +// } +// } +// +// public long Schedule(Action action, int delay) +// { +// var ticks = delay / _tickDuration; +// var futureIndex = ticks + _currentIndex; +// var rounds = futureIndex / _wheelSize; +// var slot = futureIndex % _wheelSize; +// +// if (slot == 0) +// { +// slot = _wheelSize - 1; +// rounds--; +// } +// else +// { +// slot--; +// } +// +// var taskId = _scene.RuntimeIdFactory.Create; +// var task = _scheduledTaskPool.Rent(action, ref rounds, ref slot); +// task.Node = _wheel[slot].AddLast(task); +// _taskDictionary.Add(taskId, task); +// Console.WriteLine($"Schedule rounds:{rounds} slot:{slot} _currentIndex:{_currentIndex}"); +// return taskId; +// } +// +// public bool Remove(int taskId) +// { +// if (!_taskDictionary.TryGetValue(taskId, out var task)) +// { +// return false; +// } +// +// _taskDictionary.Remove(taskId); +// _wheel[task.FinalSlot].Remove(task.Node); +// _scheduledTaskPool.Return(task); +// Console.WriteLine("找到已经删除了任务"); +// return true; +// } +// +// public void Tick(object? state) +// { +// var currentWheel = _wheel[_currentIndex]; +// +// if (currentWheel.Count == 0) +// { +// AdvanceIndex(); +// return; +// } +// +// var currentNode = currentWheel.First; +// +// while (currentNode != null) +// { +// var nextNode = currentNode.Next; +// var task = currentNode.Value; +// +// if (task.Rounds <= 0 && task.FinalSlot == _currentIndex) +// { +// try +// { +// task.Action.Invoke(); +// } +// catch (Exception ex) +// { +// Log.Error($"Exception during task execution: {ex.Message}"); +// } +// } +// else +// { +// task.Rounds--; +// _tasksToReschedule.Enqueue(task); +// } +// +// currentWheel.Remove(currentNode); +// currentNode = nextNode; +// } +// +// RescheduleTasks(); +// AdvanceIndex(); +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private void AdvanceIndex() +// { +// _currentIndex = (_currentIndex + 1) % _wheelSize; +// if (_currentIndex == 0 && _upperLevelWheel != null) +// { +// _upperLevelWheel.Tick(null); +// } +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private void RescheduleTasks() +// { +// while (_tasksToReschedule.TryDequeue(out var task)) +// { +// _wheel[task.FinalSlot].AddLast(task); +// } +// } +// } +// } \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta new file mode 100644 index 0000000..d5b097d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7cfccef31996d414b9681e4c98ca64f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs new file mode 100644 index 0000000..2a836ab --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 +#pragma warning disable CS8618 + +namespace Fantasy.Timer +{ + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct TimerAction + { + public long TimerId; + public long StartTime; + public long TriggerTime; + public readonly object Callback; + public readonly TimerType TimerType; + public TimerAction(long timerId, TimerType timerType, long startTime, long triggerTime, object callback) + { + TimerId = timerId; + Callback = callback; + TimerType = timerType; + StartTime = startTime; + TriggerTime = triggerTime; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta new file mode 100644 index 0000000..410789d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0561ef5db496dbc4f9f443c11c03c208 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs new file mode 100644 index 0000000..ffa7864 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs @@ -0,0 +1,52 @@ +// ReSharper disable ForCanBeConvertedToForeach + +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#if FANTASY_UNITY +using UnityEngine; +#endif +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Timer +{ + public sealed class TimerComponentUpdateSystem : UpdateSystem + { + protected override void Update(TimerComponent self) + { + self.Update(); + } + } + + /// + /// 时间调度组件 + /// + public sealed class TimerComponent : Entity + { + /// + /// 使用系统时间创建的计时器核心。 + /// + public TimerSchedulerNet Net { get; private set; } +#if FANTASY_UNITY + /// + /// 使用 Unity 时间创建的计时器核心。 + /// + public TimerSchedulerNetUnity Unity { get; private set; } +#endif + internal TimerComponent Initialize() + { + Net = new TimerSchedulerNet(Scene); +#if FANTASY_UNITY + Unity = new TimerSchedulerNetUnity(Scene); +#endif + return this; + } + public void Update() + { + Net.Update(); +#if FANTASY_UNITY + Unity.Update(); +#endif + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta new file mode 100644 index 0000000..2bacdd7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ea52bb33f5040c4d8577a08e4f12a58 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta new file mode 100644 index 0000000..a9731e4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a4207ef761d56e3458d51b3ac20b9b66 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs new file mode 100644 index 0000000..26581f8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Helper; +// ReSharper disable UnusedParameter.Global + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Timer +{ + /// + /// 基于系统事件的任务调度系统 + /// + public sealed class TimerSchedulerNet + { + private readonly Scene _scene; + private long _idGenerator; + private long _minTime; // 最小时间 + private readonly Queue _timeOutTime = new Queue(); + private readonly Queue _timeOutTimerIds = new Queue(); + private readonly Dictionary _timerActions = new Dictionary(); + private readonly SortedOneToManyList _timeId = new(); // 时间与计时器ID的有序一对多列表 + private long GetId => ++_idGenerator; + /// + /// 构造函数 + /// + /// 当前的Scene + public TimerSchedulerNet(Scene scene) + { + _scene = scene; + } + + private long Now() + { + return TimeHelper.Now; + } + + /// + /// 驱动方法,只有调用这个方法任务系统才会正常运转。 + /// + public void Update() + { + if (_timeId.Count == 0) + { + return; + } + + var currentTime = Now(); + + if (currentTime < _minTime) + { + return; + } + + // 遍历时间ID列表,查找超时的计时器任务 + foreach (var (key, _) in _timeId) + { + if (key > currentTime) + { + _minTime = key; + break; + } + + _timeOutTime.Enqueue(key); + } + + // 处理超时的计时器任务 + while (_timeOutTime.TryDequeue(out var time)) + { + var timerIds = _timeId[time]; + for (var i = 0; i < timerIds.Count; ++i) + { + _timeOutTimerIds.Enqueue(timerIds[i]); + } + + _timeId.Remove(time); + // _timeId.RemoveKey(time); + } + + if (_timeId.Count == 0) + { + _minTime = long.MaxValue; + } + + // 执行超时的计时器任务的回调操作 + while (_timeOutTimerIds.TryDequeue(out var timerId)) + { + if (!_timerActions.Remove(timerId, out var timerAction)) + { + continue; + } + + // 根据计时器类型执行不同的操作 + switch (timerAction.TimerType) + { + case TimerType.OnceWaitTimer: + { + var tcs = (FTask)timerAction.Callback; + tcs.SetResult(true); + break; + } + case TimerType.OnceTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + action(); + break; + } + case TimerType.RepeatedTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + timerAction.StartTime = Now(); + AddTimer(ref timerAction); + action(); + break; + } + } + } + } + + private void AddTimer(ref TimerAction timer) + { + var tillTime = timer.StartTime + timer.TriggerTime; + _timeId.Add(tillTime, timer.TimerId); + _timerActions.Add(timer.TimerId, timer); + + if (tillTime < _minTime) + { + _minTime = tillTime; + } + } + + /// + /// 异步等待指定时间。 + /// + /// 等待的时间长度。 + /// 取消令牌。 + /// 等待是否成功。 + public async FTask WaitAsync(long time, FCancellationToken cancellationToken = null) + { + if (time <= 0) + { + return true; + } + + var now = Now(); + var timerId = GetId; + var tcs = FTask.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, time, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.SetResult(false); + } + } + + bool result; + + try + { + cancellationToken?.Add(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs; + } + finally + { + cancellationToken?.Remove(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待直到指定时间。 + /// + /// 等待的目标时间。 + /// 取消令牌。 + /// 等待是否成功。 + public async FTask WaitTillAsync(long tillTime, FCancellationToken cancellationToken = null) + { + var now = Now(); + + if (now >= tillTime) + { + return true; + } + + var timerId = GetId; + var tcs = FTask.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, tillTime - now, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.SetResult(false); + } + } + + bool result; + + try + { + cancellationToken?.Add(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs; + } + finally + { + cancellationToken?.Remove(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待一帧时间。 + /// + /// 等待是否成功。 + public async FTask WaitFrameAsync() + { +#if FANTASY_NET + await WaitAsync(100); +#else + await WaitAsync(1); +#endif + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// + public long OnceTimer(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, Action action) + { + var now = Now(); + + if (tillTime < now) + { + Log.Error($"new once time too small tillTime:{tillTime} Now:{now}"); + } + + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, tillTime - now, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的延迟时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTimer(long time, T timerHandlerType) where T : struct + { + void OnceTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTimer(time, OnceTimerVoid); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的目标时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, T timerHandlerType) where T : struct + { + void OnceTillTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTillTimer(tillTime, OnceTillTimerVoid); + } + + /// + /// 创建一个帧任务 + /// + /// + /// + public long FrameTimer(Action action) + { +#if FANTASY_NET + return RepeatedTimerInner(100, action); +#else + return RepeatedTimerInner(0, action); +#endif + } + + /// + /// 创建一个重复执行的计时器。 + /// + /// 计时器重复间隔的时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, Action action) + { + if (time < 0) + { + Log.Error($"time too small: {time}"); + return 0; + } + + return RepeatedTimerInner(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器重复间隔的时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, T timerHandlerType) where T : struct + { + void RepeatedTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return RepeatedTimer(time, RepeatedTimerVoid); + } + + private long RepeatedTimerInner(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.RepeatedTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// + /// + public bool Remove(ref long timerId) + { + var id = timerId; + timerId = 0; + return Remove(id); + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// 计时器的 ID。 + public bool Remove(long timerId) + { + return timerId != 0 && _timerActions.Remove(timerId, out _); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta new file mode 100644 index 0000000..1f82795 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b91ada01937627468fd3f23307b1f7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs new file mode 100644 index 0000000..f00bfe4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs @@ -0,0 +1,372 @@ +#if FANTASY_UNITY +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Helper; +using UnityEngine; +namespace Fantasy.Timer +{ + public sealed class TimerSchedulerNetUnity + { + private readonly Scene _scene; + private long _idGenerator; + private long _minTime; // 最小时间 + private readonly Queue _timeOutTime = new Queue(); + private readonly Queue _timeOutTimerIds = new Queue(); + private readonly Dictionary _timerActions = new Dictionary(); + private readonly SortedOneToManyList _timeId = new(); // 时间与计时器ID的有序一对多列表 + private long GetId => ++_idGenerator; + public TimerSchedulerNetUnity(Scene scene) + { + _scene = scene; + } + + private long Now() + { + return (long)(Time.time * 1000); + } + + public void Update() + { + if (_timeId.Count == 0) + { + return; + } + + var currentTime = Now(); + + if (currentTime < _minTime) + { + return; + } + + // 遍历时间ID列表,查找超时的计时器任务 + foreach (var (key, _) in _timeId) + { + if (key > currentTime) + { + _minTime = key; + break; + } + + _timeOutTime.Enqueue(key); + } + + // 处理超时的计时器任务 + while (_timeOutTime.TryDequeue(out var time)) + { + var timerIds = _timeId[time]; + for (var i = 0; i < timerIds.Count; ++i) + { + _timeOutTimerIds.Enqueue(timerIds[i]); + } + + _timeId.Remove(time); + // _timeId.RemoveKey(time); + } + + if (_timeId.Count == 0) + { + _minTime = long.MaxValue; + } + + // 执行超时的计时器任务的回调操作 + while (_timeOutTimerIds.TryDequeue(out var timerId)) + { + if (!_timerActions.Remove(timerId, out var timerAction)) + { + continue; + } + + // 根据计时器类型执行不同的操作 + switch (timerAction.TimerType) + { + case TimerType.OnceWaitTimer: + { + var tcs = (FTask)timerAction.Callback; + tcs.SetResult(true); + break; + } + case TimerType.OnceTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + action(); + break; + } + case TimerType.RepeatedTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + timerAction.StartTime = Now(); + AddTimer(ref timerAction); + action(); + break; + } + } + } + } + + private void AddTimer(ref TimerAction timer) + { + var tillTime = timer.StartTime + timer.TriggerTime; + _timeId.Add(tillTime, timer.TimerId); + _timerActions.Add(timer.TimerId, timer); + + if (tillTime < _minTime) + { + _minTime = tillTime; + } + } + + /// + /// 异步等待指定时间。 + /// + /// 等待的时间长度。 + /// 可选的取消令牌。 + /// 等待是否成功。 + public async FTask WaitAsync(long time, FCancellationToken cancellationToken = null) + { + if (time <= 0) + { + return true; + } + + var now = Now(); + var timerId = GetId; + var tcs = FTask.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, time, tcs); + + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.SetResult(false); + } + } + + bool result; + + try + { + cancellationToken?.Add(CancelActionVoid); + AddTimer(ref timerAction); + result =await tcs; + } + finally + { + cancellationToken?.Remove(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待直到指定时间。 + /// + /// 等待的目标时间。 + /// 可选的取消令牌。 + /// 等待是否成功。 + public async FTask WaitTillAsync(long tillTime, FCancellationToken cancellationToken = null) + { + var now = Now(); + + if (now >= tillTime) + { + return true; + } + + var timerId = GetId; + var tcs = FTask.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, tillTime - now, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.SetResult(false); + } + } + + bool result; + + try + { + cancellationToken?.Add(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs; + } + finally + { + cancellationToken?.Remove(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待一帧时间。 + /// + /// 等待是否成功。 + public async FTask WaitFrameAsync(FCancellationToken cancellationToken = null) + { + await WaitAsync(1, cancellationToken); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// + public long OnceTimer(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, Action action) + { + var now = Now(); + + if (tillTime < now) + { + Log.Error($"new once time too small tillTime:{tillTime} Now:{now}"); + } + + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, tillTime - now, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的延迟时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTimer(long time, T timerHandlerType) where T : struct + { + void OnceTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTimer(time, OnceTimerVoid); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的目标时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, T timerHandlerType) where T : struct + { + void OnceTillTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTillTimer(tillTime, OnceTillTimerVoid); + } + + /// + /// 创建一个帧任务 + /// + /// + /// + public long FrameTimer(Action action) + { + return RepeatedTimerInner(1, action); + } + + /// + /// 创建一个重复执行的计时器。 + /// + /// 计时器重复间隔的时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, Action action) + { + if (time < 0) + { + Log.Error($"time too small: {time}"); + return 0; + } + + return RepeatedTimerInner(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器重复间隔的时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, T timerHandlerType) where T : struct + { + void RepeatedTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return RepeatedTimer(time, RepeatedTimerVoid); + } + + private long RepeatedTimerInner(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.RepeatedTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// + /// + public bool Remove(ref long timerId) + { + var id = timerId; + timerId = 0; + return Remove(id); + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// 计时器的 ID。 + public bool Remove(long timerId) + { + return timerId != 0 && _timerActions.Remove(timerId, out _); + } + } +} +#endif + diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta new file mode 100644 index 0000000..1c95729 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81a965eed70ba9447a3b7ec786ebbf8e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs new file mode 100644 index 0000000..6f16f80 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs @@ -0,0 +1,25 @@ +namespace Fantasy.Timer +{ + /// + /// 枚举对象TimerType + /// + public enum TimerType + { + /// + /// None + /// + None, + /// + /// 一次等待定时器 + /// + OnceWaitTimer, + /// + /// 一次性定时器 + /// + OnceTimer, + /// + /// 重复定时器 + /// + RepeatedTimer + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta new file mode 100644 index 0000000..42cb28f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4212c38bee8e2e54f8c5b58d6f2365b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Entity.cs b/Runtime/CoreRuntime/Core/Entitas/Entity.cs new file mode 100644 index 0000000..99faad7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Entity.cs @@ -0,0 +1,1066 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Fantasy.Entitas.Interface; +using Fantasy.Pool; +using MongoDB.Bson.Serialization.Attributes; +using Newtonsoft.Json; +using ProtoBuf; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable MergeIntoPattern +// ReSharper disable SuspiciousTypeConversion.Global +// ReSharper disable NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract +// ReSharper disable CheckNamespace +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Entitas +{ + /// + /// 用来表示一个Entity + /// + public interface IEntity : IDisposable, IPool { } + + /// + /// Entity的抽象类,任何Entity必须继承这个接口才可以使用 + /// + public abstract partial class Entity : IEntity + { + #region Members + + /// + /// 获取一个值,表示实体是否支持对象池。 + /// + [BsonIgnore] + [JsonIgnore] + [ProtoIgnore] + [IgnoreDataMember] + private bool _isPool; + /// + /// 实体的Id + /// + [BsonId] + [BsonElement] + [BsonIgnoreIfDefault] + [BsonDefaultValue(0L)] + public long Id { get; protected set; } + /// + /// 实体的RunTimeId,其他系统可以通过这个Id发送Route消息,这个Id也可以理解为RouteId + /// + [BsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public long RuntimeId { get; protected set; } + /// + /// 当前实体是否已经被销毁 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public bool IsDisposed => RuntimeId == 0; + /// + /// 当前实体所归属的Scene + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Scene Scene { get; protected set; } + /// + /// 实体的父实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Entity Parent { get; protected set; } + /// + /// 实体的真实Type + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Type Type { get; protected set; } +#if FANTASY_NET + [BsonElement("t")] [BsonIgnoreIfNull] private EntityList _treeDb; + [BsonElement("m")] [BsonIgnoreIfNull] private EntityList _multiDb; +#endif + [BsonIgnore] [IgnoreDataMember] [ProtoIgnore] private EntitySortedDictionary _tree; + [BsonIgnore] [IgnoreDataMember] [ProtoIgnore] private EntitySortedDictionary _multi; + + /// + /// 获得父Entity + /// + /// 父实体的泛型类型 + /// + public T GetParent() where T : Entity, new() + { + return Parent as T; + } + + /// + /// 获取当前实体的RouteId。 + /// + public long RouteId => RuntimeId; + + #endregion + + #region Create + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 实体的Type + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// + public static Entity Create(Scene scene, Type type, bool isPool, bool isRunEvent) + { + return Create(scene, type, scene.EntityIdFactory.Create, isPool, isRunEvent); + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 实体的Type + /// 指定实体的Id + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// + public static Entity Create(Scene scene, Type type, long id, bool isPool, bool isRunEvent) + { + if (!typeof(Entity).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{type.FullName} Type:{type.FullName} must inherit from Entity"); + } + + Entity entity = null; + + if (isPool) + { + entity = (Entity)scene.EntityPool.Rent(type); + } + else + { + if (!scene.TypeInstance.TryGetValue(type, out var createInstance)) + { + createInstance = CreateInstance.CreateIPool(type); + scene.TypeInstance[type] = createInstance; + } + + entity = (Entity)createInstance(); + } + + entity.Scene = scene; + entity.Type = type; + entity.SetIsPool(isPool); + entity.Id = id; + entity.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(entity); + + if (isRunEvent) + { + scene.EntityComponent.Awake(entity); + scene.EntityComponent.StartUpdate(entity); +#if FANTASY_UNITY + scene.EntityComponent.StartLateUpdate(entity); +#endif + } + + return entity; + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// 要创建的实体泛型类型 + /// + public static T Create(Scene scene, bool isPool, bool isRunEvent) where T : Entity, new() + { + return Create(scene, scene.EntityIdFactory.Create, isPool, isRunEvent); + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 指定实体的Id + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// 要创建的实体泛型类型 + /// + public static T Create(Scene scene, long id, bool isPool, bool isRunEvent) where T : Entity, new() + { + var entity = isPool ? scene.EntityPool.Rent() : new T(); + entity.Scene = scene; + entity.Type = typeof(T); + entity.SetIsPool(isPool); + entity.Id = id; + entity.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(entity); + + if (isRunEvent) + { + scene.EntityComponent.Awake(entity); + scene.EntityComponent.StartUpdate(entity); +#if FANTASY_UNITY + scene.EntityComponent.StartLateUpdate(entity); +#endif + } + + return entity; + } + + #endregion + + #region AddComponent + + /// + /// 添加一个组件到当前实体上 + /// + /// 是否从对象池里创建 + /// 要添加组件的泛型类型 + /// 返回添加到实体上组件的实例 + public T AddComponent(bool isPool = true) where T : Entity, new() + { + var id = SupportedMultiEntityChecker.IsSupported ? Scene.EntityIdFactory.Create : Id; + var entity = Create(Scene, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); +#if FANTASY_UNITY + Scene.EntityComponent.StartLateUpdate(entity); +#endif + return entity; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加组件的Id + /// 是否从对象池里创建 + /// 要添加组件的泛型类型 + /// 返回添加到实体上组件的实例 + public T AddComponent(long id, bool isPool = true) where T : Entity, new() + { + var entity = Create(Scene, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); +#if FANTASY_UNITY + Scene.EntityComponent.StartLateUpdate(entity); +#endif + return entity; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加的实体实例 + public void AddComponent(Entity component) + { + if (this == component) + { + Log.Error("Cannot add oneself to one's own components"); + return; + } + + if (component.IsDisposed) + { + Log.Error($"component is Disposed {component.Type.FullName}"); + return; + } + + var type = component.Type; + component.Parent?.RemoveComponent(component, false); + + if (component is ISupportedMultiEntity) + { + _multi ??= Scene.EntitySortedDictionaryPool.Rent(); + _multi.Add(component.Id, component); +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _multiDb ??= Scene.EntityListPool.Rent(); + _multiDb.Add(component); + } +#endif + } + else + { +#if FANTASY_NET + if (component is ISupportedSingleCollection && component.Id != Id) + { + Log.Error($"component type :{type.FullName} for implementing ISupportedSingleCollection, it is required that the Id must be the same as the parent"); + } +#endif + var typeHashCode = Scene.EntityComponent.GetHashCode(type);; + + if (_tree == null) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + } + else if (_tree.ContainsKey(typeHashCode)) + { + Log.Error($"type:{type.FullName} If you want to add multiple components of the same type, please implement IMultiEntity"); + return; + } + + _tree.Add(typeHashCode, component); +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _treeDb ??= Scene.EntityListPool.Rent(); + _treeDb.Add(component); + } +#endif + } + + component.Parent = this; + component.Scene = Scene; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加的实体实例 + /// 要添加组件的泛型类型 + public void AddComponent(T component) where T : Entity + { + var type = typeof(T); + + if (type == typeof(Entity)) + { + Log.Error("Cannot add a generic Entity type as a component. Specify a more specific type."); + return; + } + + if (this == component) + { + Log.Error("Cannot add oneself to one's own components"); + return; + } + + if (component.IsDisposed) + { + Log.Error($"component is Disposed {type.FullName}"); + return; + } + + component.Parent?.RemoveComponent(component, false); + + if (SupportedMultiEntityChecker.IsSupported) + { + _multi ??= Scene.EntitySortedDictionaryPool.Rent(); + _multi.Add(component.Id, component); +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb ??= Scene.EntityListPool.Rent(); + _multiDb.Add(component); + } +#endif + } + else + { +#if FANTASY_NET + if (SupportedSingleCollectionChecker.IsSupported && component.Id != Id) + { + Log.Error($"component type :{type.FullName} for implementing ISupportedSingleCollection, it is required that the Id must be the same as the parent"); + } +#endif + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + + if (_tree == null) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + } + else if (_tree.ContainsKey(typeHashCode)) + { + Log.Error($"type:{type.FullName} If you want to add multiple components of the same type, please implement IMultiEntity"); + return; + } + + _tree.Add(typeHashCode, component); +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _treeDb ??= Scene.EntityListPool.Rent(); + _treeDb.Add(component); + } +#endif + } + + component.Parent = this; + component.Scene = Scene; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 组件的类型 + /// 是否在对象池创建 + /// + public Entity AddComponent(Type type, bool isPool = true) + { + var id = typeof(ISupportedMultiEntity).IsAssignableFrom(type) ? Scene.EntityIdFactory.Create : Id; + var entity = Entity.Create(Scene, type, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); +#if FANTASY_UNITY + Scene.EntityComponent.StartLateUpdate(entity); +#endif + return entity; + } + + #endregion + + #region HasComponent + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + public bool HasComponent() where T : Entity, new() + { + return HasComponent(typeof(T)); + } + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + public bool HasComponent(Type type) + { + if (_tree == null) + { + return false; + } + + return _tree.ContainsKey(Scene.EntityComponent.GetHashCode(type)); + } + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + /// + public bool HasComponent(long id) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return false; + } + + return _multi.ContainsKey(id); + } + + #endregion + + #region GetComponent + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体泛型类型 + /// 查找的实体实例 + public T GetComponent() where T : Entity, new() + { + if (_tree == null) + { + return null; + } + + var typeHashCode = Scene.EntityComponent.GetHashCode(typeof(T)); + return _tree.TryGetValue(typeHashCode, out var component) ? (T)component : null; + } + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体类型 + /// 查找的实体实例 + public Entity GetComponent(Type type) + { + if (_tree == null) + { + return null; + } + + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + return _tree.TryGetValue(typeHashCode, out var component) ? component : null; + } + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体的Id + /// 要查找实体泛型类型 + /// 查找的实体实例 + public T GetComponent(long id) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return default; + } + + return _multi.TryGetValue(id, out var entity) ? (T)entity : default; + } + + /// + /// 当前实体上查找一个字实体,如果没有就创建一个新的并添加到当前实体上 + /// + /// 是否从对象池创建 + /// 要查找或添加实体泛型类型 + /// 查找的实体实例 + public T GetOrAddComponent(bool isPool = true) where T : Entity, new() + { + return GetComponent() ?? AddComponent(isPool); + } + + #endregion + + #region RemoveComponent + + /// + /// 当前实体下删除一个实体 + /// + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + /// + public void RemoveComponent(bool isDispose = true) where T : Entity, new() + { + if (SupportedMultiEntityChecker.IsSupported) + { + throw new NotSupportedException($"{typeof(T).FullName} message:Cannot delete components that implement the ISupportedMultiEntity interface"); + } + + if (_tree == null) + { + return; + } + + var type = typeof(T); + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + if (!_tree.TryGetValue(typeHashCode, out var component)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && SupportedDataBaseChecker.IsSupported) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体Id + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + public void RemoveComponent(long id, bool isDispose = true) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return; + } + + if (!_multi.TryGetValue(id, out var component)) + { + return; + } +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体实例 + /// 是否执行删除实体的Dispose方法 + public void RemoveComponent(Entity component, bool isDispose = true) + { + if (this == component) + { + return; + } + + if (component is ISupportedMultiEntity) + { + if (_multi != null) + { + if (!_multi.ContainsKey(component.Id)) + { + return; + } +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + } + } + else if (_tree != null) + { + var typeHashCode = Scene.EntityComponent.GetHashCode(component.Type); + if (!_tree.ContainsKey(typeHashCode)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && component is ISupportedDataBase) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体实例 + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + public void RemoveComponent(T component, bool isDispose = true) where T : Entity + { + if (this == component) + { + return; + } + + if (typeof(T) == typeof(Entity)) + { + Log.Error("Cannot remove a generic Entity type as a component. Specify a more specific type."); + return; + } + + if (SupportedMultiEntityChecker.IsSupported) + { + if (_multi != null) + { + if (!_multi.ContainsKey(component.Id)) + { + return; + } +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + } + } + else if (_tree != null) + { + var typeHashCode = Scene.EntityComponent.GetHashCode(typeof(T)); + if (!_tree.ContainsKey(typeHashCode)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && SupportedDataBaseChecker.IsSupported) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + } + + if (isDispose) + { + component.Dispose(); + } + } + + #endregion + + #region Deserialize + + /// + /// 反序列化当前实体,因为在数据库加载过来的或通过协议传送过来的实体并没有跟当前Scene做关联。 + /// 所以必须要执行一下这个反序列化的方法才可以使用。 + /// + /// Scene + /// 是否是重新生成实体的Id,如果是数据库加载过来的一般是不需要的 + public void Deserialize(Scene scene, bool resetId = false) + { + if (RuntimeId != 0) + { + return; + } + + try + { + Scene = scene; + Type ??= GetType(); + RuntimeId = Scene.RuntimeIdFactory.Create; + if (resetId) + { + Id = RuntimeId; + } +#if FANTASY_NET + if (_treeDb != null && _treeDb.Count > 0) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + foreach (var entity in _treeDb) + { + entity.Parent = this; + entity.Type = entity.GetType(); + var typeHashCode = Scene.EntityComponent.GetHashCode(entity.Type); + _tree.Add(typeHashCode, entity); + entity.Deserialize(scene, resetId); + } + } + + if (_multiDb != null && _multiDb.Count > 0) + { + _multi = Scene.EntitySortedDictionaryPool.Rent(); + foreach (var entity in _multiDb) + { + entity.Parent = this; + entity.Deserialize(scene, resetId); + _multi.Add(entity.Id, entity); + } + } +#endif + scene.AddEntity(this); + scene.EntityComponent.Deserialize(this); + } + catch (Exception e) + { + if (RuntimeId != 0) + { + scene.RemoveEntity(RuntimeId); + } + + Log.Error(e); + } + } + + #endregion + + #region ForEach +#if FANTASY_NET + /// + /// 查询当前实体下支持数据库分表存储实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachSingleCollection + { + get + { + foreach (var (_, treeEntity) in _tree) + { + if (treeEntity is not ISupportedSingleCollection) + { + continue; + } + + yield return treeEntity; + } + } + } + /// + /// 查询当前实体下支持传送实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachTransfer + { + get + { + if (_tree != null) + { + foreach (var (_, treeEntity) in _tree) + { + if (treeEntity is ISupportedTransfer) + { + yield return treeEntity; + } + } + } + + if (_multiDb != null) + { + foreach (var treeEntity in _multiDb) + { + if (treeEntity is not ISupportedTransfer) + { + continue; + } + + yield return treeEntity; + } + } + } + } +#endif + /// + /// 查询当前实体下的实现了ISupportedMultiEntity接口的实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachMultiEntity + { + get + { + if (_multi == null) + { + yield break; + } + + foreach (var (_, supportedMultiEntity) in _multi) + { + yield return supportedMultiEntity; + } + } + } + /// + /// 查找当前实体下的所有实体,不包括实现ISupportedMultiEntity接口的实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachEntity + { + get + { + if (_tree == null) + { + yield break; + } + + foreach (var (_, entity) in _tree) + { + yield return entity; + } + } + } + #endregion + + #region Dispose + + /// + /// 销毁当前实体,销毁后会自动销毁当前实体下的所有实体。 + /// + public virtual void Dispose() + { + if (IsDisposed) + { + return; + } + + var scene = Scene; + var runTimeId = RuntimeId; + RuntimeId = 0; + + if (_tree != null) + { + foreach (var (_, entity) in _tree) + { + entity.Dispose(); + } + + _tree.Clear(); + scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + + if (_multi != null) + { + foreach (var (_, entity) in _multi) + { + entity.Dispose(); + } + + _multi.Clear(); + scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } +#if FANTASY_NET + if (_treeDb != null) + { + foreach (var entity in _treeDb) + { + entity.Dispose(); + } + + _treeDb.Clear(); + scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + + if (_multiDb != null) + { + foreach (var entity in _multiDb) + { + entity.Dispose(); + } + + _multiDb.Clear(); + scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } +#endif + scene.EntityComponent.Destroy(this); + + if (Parent != null && Parent != this && !Parent.IsDisposed) + { + Parent.RemoveComponent(this, false); + Parent = null; + } + + Id = 0; + Scene = null; + Parent = null; + scene.RemoveEntity(runTimeId); + + if (IsPool()) + { + scene.EntityPool.Return(Type, this); + } + + Type = null; + } + + #endregion + + #region Pool + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + + #endregion + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Entity.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Entity.cs.meta new file mode 100644 index 0000000..5f81faf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Entity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18e5881586a6d234798912eca8499dec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs b/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs new file mode 100644 index 0000000..9a6441c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8714 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. + +namespace Fantasy.Entitas +{ + internal sealed class EntityPool : PoolCore + { + public EntityPool() : base(4096) { } + } + + internal sealed class EntityList : List, IPool where T : Entity + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + internal sealed class EntityListPool : PoolCore> where T : Entity + { + public EntityListPool() : base(4096) { } + } + + internal sealed class EntitySortedDictionary : SortedDictionary, IPool where TN : Entity + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + internal sealed class EntitySortedDictionaryPool : PoolCore> where TN : Entity + { + public EntitySortedDictionaryPool() : base(4096) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs.meta b/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs.meta new file mode 100644 index 0000000..0978111 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/EntityPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03cd2167f479b024285016456e7c54ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs b/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs new file mode 100644 index 0000000..dd1a3fd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs @@ -0,0 +1,59 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.Entitas +{ + /// + /// 实体引用检查组件 + /// + /// + public struct EntityReference where T : Entity + { + private T _entity; + private readonly long _runTimeId; + + private EntityReference(T t) + { + if (t == null) + { + _entity = null; + _runTimeId = 0; + return; + } + + _entity = t; + _runTimeId = t.RuntimeId; + } + + /// + /// 将一个实体转换为EntityReference + /// + /// 实体泛型类型 + /// 返回一个EntityReference + public static implicit operator EntityReference(T t) + { + return new EntityReference(t); + } + + /// + /// 将一个EntityReference转换为实体 + /// + /// 实体泛型类型 + /// 当实体已经被销毁过会返回null + public static implicit operator T(EntityReference v) + { + if (v._entity == null) + { + return null; + } + + if (v._entity.RuntimeId != v._runTimeId) + { + v._entity = null; + } + + return v._entity; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs.meta b/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs.meta new file mode 100644 index 0000000..4694a9b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/EntityReference.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12d64dd9587be7342983cf637fd48491 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface.meta b/Runtime/CoreRuntime/Core/Entitas/Interface.meta new file mode 100644 index 0000000..e093ad3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0895a0e9079cc094cbcec84ca1924bb3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported.meta new file mode 100644 index 0000000..51e72c6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5497701db404b1d40a5b3701abea5c29 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs new file mode 100644 index 0000000..84de7a4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity保存到数据库的时候会根据子组件设置分离存储特性分表存储在不同的集合表中 + /// + public interface ISingleCollectionRoot { } + public static class SingleCollectionRootChecker where T : Entity + { + public static bool IsSupported { get; } + + static SingleCollectionRootChecker() + { + IsSupported = typeof(ISingleCollectionRoot).IsAssignableFrom(typeof(T)); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta new file mode 100644 index 0000000..fab2fc1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f9daeefe64572ee499cf049bbbd89cc9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs new file mode 100644 index 0000000..f505241 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs @@ -0,0 +1,19 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity支持数据库 + /// + // ReSharper disable once InconsistentNaming + public interface ISupportedDataBase { } + + public static class SupportedDataBaseChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedDataBaseChecker() + { + IsSupported = typeof(ISupportedDataBase).IsAssignableFrom(typeof(T)); + } + } +} diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta new file mode 100644 index 0000000..f0a95c7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ada8b299628c67c41bc809c1854fef5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs new file mode 100644 index 0000000..ee6aeb7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs @@ -0,0 +1,20 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Entitas.Interface +{ + /// + /// 支持再一个组件里添加多个同类型组件 + /// + public interface ISupportedMultiEntity : IDisposable { } + + public static class SupportedMultiEntityChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedMultiEntityChecker() + { + IsSupported = typeof(ISupportedMultiEntity).IsAssignableFrom(typeof(T)); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta new file mode 100644 index 0000000..700fd67 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f663cb1c231b2e94d83427fe3d237725 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs new file mode 100644 index 0000000..302e697 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs @@ -0,0 +1,47 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas.Interface +{ + // Entity是单一集合、保存到数据库的时候不会跟随父组件保存在一个集合里、会单独保存在一个集合里 + // 需要配合SingleCollectionAttribute一起使用、如在Entity类头部定义SingleCollectionAttribute(typeOf(Unit)) + // SingleCollectionAttribute用来定义这个Entity是属于哪个Entity的子集 + /// + /// 定义实体支持单一集合存储的接口。当实体需要单独存储在一个集合中,并且在保存到数据库时不会与父组件一起保存在同一个集合中时,应实现此接口。 + /// + public interface ISupportedSingleCollection { } + public static class SupportedSingleCollectionChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedSingleCollectionChecker() + { + IsSupported = typeof(ISupportedSingleCollection).IsAssignableFrom(typeof(T)); + } + } + /// + /// 表示用于指定实体的单一集合存储属性。此属性用于配合 接口使用, + /// 用于定义实体属于哪个父实体的子集合,以及在数据库中使用的集合名称。 + /// + [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] + public class SingleCollectionAttribute : Attribute + { + /// + /// 获取父实体的类型,指示此实体是属于哪个父实体的子集合。 + /// + public readonly Type RootType; + /// + /// 获取在数据库中使用的集合名称。 + /// + public readonly string CollectionName; + /// + /// 初始化 类的新实例,指定父实体类型和集合名称。 + /// + /// 父实体的类型。 + /// 在数据库中使用的集合名称。 + public SingleCollectionAttribute(Type rootType, string collectionName) + { + RootType = rootType; + CollectionName = collectionName; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta new file mode 100644 index 0000000..4055004 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e8261cf85d96f86438ede2799c08fd06 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs new file mode 100644 index 0000000..a3ae4a9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs @@ -0,0 +1,19 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity支持传送 + /// + public interface ISupportedTransfer { } + public static class SupportedTransferChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedTransferChecker() + { + IsSupported = typeof(ISupportedTransfer).IsAssignableFrom(typeof(T)); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta new file mode 100644 index 0000000..4ed6b4c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a7dcbb85ca0433c4b9ed893db34848e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System.meta new file mode 100644 index 0000000..9571c20 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 01f465d969b48db479f65455a29745c4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs new file mode 100644 index 0000000..f651701 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IAwakeSystem : IEntitiesSystem { } + /// + /// 实体的Awake事件的抽象接口 + /// + /// 实体的泛型类型 + public abstract class AwakeSystem : IAwakeSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Awake(T self); + /// + /// 框架内部调用的触发Awake的方法。 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Awake((T) self); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta new file mode 100644 index 0000000..886e9ec --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d721009acdd14cb48be914eb7a4f327b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs new file mode 100644 index 0000000..da42e58 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs @@ -0,0 +1,59 @@ +using System; + +namespace Fantasy.Entitas.Interface +{ + /// + /// 自定义组件事件系统接口 + /// 如果需要自定义组件事件系统,请继承此接口。 + /// 这个接口内部使用。不对外开放。 + /// + internal interface ICustomEntitiesSystem + { + /// + /// 事件类型 + /// 用于触发这个组件事件关键因素。 + /// + int CustomEventType { get; } + /// + /// 实体的类型 + /// + /// + Type EntitiesType(); + /// + /// 框架内部调用的触发事件方法 + /// + /// + void Invoke(Entity entity); + } + + /// + /// 自定义组件事件系统抽象类 + /// 如果需要自定义组件事件系统,请继承此抽象类。 + /// + /// + public abstract class CustomSystem : ICustomEntitiesSystem where T : Entity + { + /// + /// 这个1表示是一个自定义事件类型,执行这个事件是时候需要用到这个1. + /// + public abstract int CustomEventType { get; } + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Custom(T self); + /// + /// 实体的类型 + /// + /// + public abstract Type EntitiesType(); + /// + /// 框架内部调用的触发Awake的方法。 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Custom((T) self); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs.meta new file mode 100644 index 0000000..d455a73 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ICustomEntitiesSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb771aa2f5675154fb65283bddca2aff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs new file mode 100644 index 0000000..9c38ab6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IDeserializeSystem : IEntitiesSystem { } + /// + /// 实体的反序列化事件的抽象接口 + /// + /// 实体的泛型数据 + public abstract class DeserializeSystem : IDeserializeSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Deserialize(T self); + /// + /// 框架内部调用的触发Deserialize的方法 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Deserialize((T) self); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta new file mode 100644 index 0000000..ab3c4d0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70d3c8da0124dc149abe64660a909360 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs new file mode 100644 index 0000000..531ebbe --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IDestroySystem : IEntitiesSystem { } + /// + /// 实体销毁事件的抽象接口 + /// + /// + public abstract class DestroySystem : IDestroySystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Destroy(T self); + /// + /// 框架内部调用的触发Destroy的方法 + /// + /// + public void Invoke(Entity self) + { + Destroy((T) self); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs.meta new file mode 100644 index 0000000..3328a1a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IDestroySystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5185fe9892a3a674faccf98e5771bbad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs new file mode 100644 index 0000000..555d21a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs @@ -0,0 +1,22 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + /// + /// ECS事件系统的核心接口,任何事件都是要继承这个接口 + /// + public interface IEntitiesSystem + { + /// + /// 实体的类型 + /// + /// + Type EntitiesType(); + /// + /// 框架内部调用的触发事件方法 + /// + /// + void Invoke(Entity entity); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta new file mode 100644 index 0000000..a516bfc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a42c9583928f02a4fb0b95b988a457e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs new file mode 100644 index 0000000..34b5f80 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs @@ -0,0 +1,36 @@ +#if FANTASY_UNITY +using System; + +namespace Fantasy.Entitas.Interface +{ + internal interface ILateUpdateSystem : IEntitiesSystem { } + + /// + /// 实体的LateUpdate事件的抽象接口 + /// + /// 实体的泛型类型 + public abstract class LateUpdateSystem : ILateUpdateSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void LateUpdate(T self); + + /// + /// 框架内部调用的触发Awake的方法。 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + LateUpdate((T)self); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs.meta new file mode 100644 index 0000000..6a5ab4a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/ILateUpdateSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9dab50e606a24e728b890d6fd6977b9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs new file mode 100644 index 0000000..4b34ac8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs @@ -0,0 +1,31 @@ +using System; + +namespace Fantasy.Entitas.Interface +{ + internal interface IUpdateSystem : IEntitiesSystem { } + /// + /// Update事件的抽象接口 + /// + /// + public abstract class UpdateSystem : IUpdateSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Update(T self); + /// + /// 框架内部调用的触发Update的方法 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Update((T) self); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta new file mode 100644 index 0000000..1bbb19f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa306ece37787644fad38454d8b9a80d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask.meta b/Runtime/CoreRuntime/Core/FTask.meta new file mode 100644 index 0000000..b6f6706 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 81e8554d3259dc24e80aa2efa949019c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Builder.meta b/Runtime/CoreRuntime/Core/FTask/Builder.meta new file mode 100644 index 0000000..ff61c28 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 284b8b3115308ca42b163be0894e41f9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs new file mode 100644 index 0000000..60b0d08 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs @@ -0,0 +1,52 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Async +{ + [StructLayout(LayoutKind.Auto)] + public struct AsyncFTaskCompletedMethodBuilder + { + public FTaskCompleted Task => default; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncFTaskCompletedMethodBuilder Create() + { + return new AsyncFTaskCompletedMethodBuilder(); + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + ExceptionDispatchInfo.Capture(exception).Throw(); + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() { } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.OnCompleted(stateMachine.MoveNext); + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.UnsafeOnCompleted(stateMachine.MoveNext); + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetStateMachine(IAsyncStateMachine stateMachine) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs.meta b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs.meta new file mode 100644 index 0000000..ee85782 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskCompletedMethodBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c602c862b3232bf4abb918f3d3d5565a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs new file mode 100644 index 0000000..6c072cd --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +// ReSharper disable MemberCanBePrivate.Global +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8604 // Possible null reference argument. + +namespace Fantasy.Async +{ + [StructLayout(LayoutKind.Auto)] + public readonly struct AsyncFTaskMethodBuilder + { + public FTask Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncFTaskMethodBuilder Create() + { + return new AsyncFTaskMethodBuilder(FTask.Create()); + } + + public AsyncFTaskMethodBuilder(FTask fTask) + { + Task = fTask; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() + { + Task.SetResult(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + Task.SetException(exception); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + // 通常在异步方法中遇到 await 关键字时调用,并且需要将执行恢复到调用 await 之前的同步上下文。 + awaiter.OnCompleted(stateMachine.MoveNext); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + // 通常在你不需要恢复到原始同步上下文时调用,这意味着你不关心在什么线程上恢复执行。 + awaiter.UnsafeOnCompleted(stateMachine.MoveNext); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + // 用于设置和保存异步方法的状态机实例。 + // 编译器在生成异步方法时要求其存在。 + // 编译器生成的代码已经足够处理状态机的管理,所以这里没有什么特殊要求所以保持空实现。 + } + } + + [StructLayout(LayoutKind.Auto)] + public readonly struct AsyncFTaskMethodBuilder + { + public FTask Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncFTaskMethodBuilder Create() + { + return new AsyncFTaskMethodBuilder(FTask.Create()); + } + + public AsyncFTaskMethodBuilder(FTask fTask) + { + Task = fTask; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult(T value) + { + Task.SetResult(value); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + Task.SetException(exception); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.OnCompleted(stateMachine.MoveNext); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.UnsafeOnCompleted(stateMachine.MoveNext); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetStateMachine(IAsyncStateMachine stateMachine) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs.meta b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs.meta new file mode 100644 index 0000000..ae66478 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFTaskMethodBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 922f1f1393cbba04f8fe03e4badfc904 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs new file mode 100644 index 0000000..b9f7bc0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs @@ -0,0 +1,62 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Async +{ + [StructLayout(LayoutKind.Auto)] + internal struct AsyncFVoidMethodBuilder + { + public FVoid Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => default; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncFVoidMethodBuilder Create() + { + return default; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() { } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + ExceptionDispatchInfo.Capture(exception).Throw(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.OnCompleted(stateMachine.MoveNext); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine + { + awaiter.UnsafeOnCompleted(stateMachine.MoveNext); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetStateMachine(IAsyncStateMachine stateMachine) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs.meta b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs.meta new file mode 100644 index 0000000..9d947f2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Builder/AsyncFVoidMethodBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f2ccd7e885b640b4eb3cfa8ee883fa12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/FCancellationToken.meta b/Runtime/CoreRuntime/Core/FTask/FCancellationToken.meta new file mode 100644 index 0000000..86ce396 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FCancellationToken.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0d7358afebf20e14ebcef908c60f2f6b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs b/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs new file mode 100644 index 0000000..90913e3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace Fantasy.Async +{ + /// + /// 用于FTask取消的CancellationToken + /// + public sealed class FCancellationToken : IDisposable + { + private bool _isDispose; + private bool _isCancel; + private readonly HashSet _actions = new HashSet(); + /// + /// 当前CancellationToken是否已经取消过了 + /// + public bool IsCancel => _isDispose || _isCancel; + /// + /// 添加一个取消要执行的Action + /// + /// + public void Add(Action action) + { + if (_isDispose) + { + return; + } + + _actions.Add(action); + } + /// + /// 移除一个取消要执行的Action + /// + /// + public void Remove(Action action) + { + if (_isDispose) + { + return; + } + + _actions.Remove(action); + } + /// + /// 取消CancellationToken + /// + public void Cancel() + { + if (IsCancel) + { + return; + } + + _isCancel = true; + + foreach (var action in _actions) + { + try + { + action.Invoke(); + } + catch (Exception e) + { + Console.WriteLine(e); + } + } + + _actions.Clear(); + } + /// + /// 销毁掉CancellationToken,会执行Cancel方法。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + if (!IsCancel) + { + Cancel(); + _isCancel = true; + } + + _isDispose = true; + + if (Caches.Count > 2000) + { + return; + } + + Caches.Enqueue(this); + } + + #region Static + + private static readonly ConcurrentQueue Caches = new ConcurrentQueue(); + + /// + /// 获取一个新的CancellationToken + /// + public static FCancellationToken ToKen + { + get + { + if (!Caches.TryDequeue(out var fCancellationToken)) + { + fCancellationToken = new FCancellationToken(); + } + + fCancellationToken._isCancel = false; + fCancellationToken._isDispose = false; + return fCancellationToken; + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs.meta b/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs.meta new file mode 100644 index 0000000..a136c15 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FCancellationToken/FCancellationToken.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 01b4ab093b925a54795590d0d2db1f77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/FTask.Extension.meta b/Runtime/CoreRuntime/Core/FTask/FTask.Extension.meta new file mode 100644 index 0000000..9ee0a16 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FTask.Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d8f5be627a6166d4c8440311c1504d0c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs new file mode 100644 index 0000000..80c7fc8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs @@ -0,0 +1,115 @@ +#if !FANTASY_WEBGL +using System.Collections.Concurrent; +#endif +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Async +{ + /// + /// 一个异步任务 + /// + public partial class FTask + { + private bool _isPool; +#if FANTASY_WEBGL + private static readonly Queue Caches = new Queue(); +#else + private static readonly ConcurrentQueue Caches = new ConcurrentQueue(); +#endif + /// + /// 创建一个空的任务 + /// + public static FTaskCompleted CompletedTask => new FTaskCompleted(); + + private FTask() { } + + /// + /// 创建一个任务 + /// + /// 是否从对象池中创建 + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FTask Create(bool isPool = true) + { + if (!isPool) + { + return new FTask(); + } + + if (!Caches.TryDequeue(out var fTask)) + { + fTask = new FTask(); + } + + fTask._isPool = true; + return fTask; + } + + private void Return() + { + if (!_isPool || Caches.Count > 2000) + { + return; + } + + _callBack = null; + _status = STaskStatus.Pending; + Caches.Enqueue(this); + } + } + + /// + /// 一个异步任务 + /// + /// 任务的泛型类型 + public partial class FTask + { + private bool _isPool; +#if FANTASY_WEBGL + private static readonly Queue> Caches = new Queue>(); +#else + private static readonly ConcurrentQueue> Caches = new ConcurrentQueue>(); +#endif + /// + /// 创建一个任务 + /// + /// 是否从对象池中创建 + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FTask Create(bool isPool = true) + { + if (!isPool) + { + return new FTask(); + } + + if (!Caches.TryDequeue(out var fTask)) + { + fTask = new FTask(); + } + + fTask._isPool = true; + return fTask; + } + + private FTask() { } + + private void Return() + { + if (!_isPool || Caches.Count > 2000) + { + return; + } + + _callBack = null; + _status = STaskStatus.Pending; + Caches.Enqueue(this); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs.meta b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs.meta new file mode 100644 index 0000000..53be1c2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Factory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c11be174ba242d43904008ce7527791 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs new file mode 100644 index 0000000..a42edec --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs @@ -0,0 +1,345 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +using System; +using System.Collections.Generic; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Async +{ + public partial class FTask + { + #region NetTimer + + /// + /// 异步等待指定时间 + /// + /// + /// + /// + /// + public static FTask Wait(Scene scene, long time, FCancellationToken cancellationToken = null) + { + return scene.TimerComponent.Net.WaitAsync(time, cancellationToken); + } + + /// + /// 异步等待直到指定时间 + /// + /// + /// + /// + /// + public static FTask WaitTill(Scene scene, long time, FCancellationToken cancellationToken = null) + { + return scene.TimerComponent.Net.WaitTillAsync(time, cancellationToken); + } + + /// + /// 异步等待一帧时间 + /// + /// + /// + public static FTask WaitFrame(Scene scene) + { + return scene.TimerComponent.Net.WaitFrameAsync(); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间 + /// + /// + /// + /// + /// + public static long OnceTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Net.OnceTimer(time, action); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。 + /// + /// + /// + /// + /// + public static long OnceTillTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Net.OnceTillTimer(time, action); + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。 + /// + /// + /// + /// + /// + /// + public static long OnceTimer(Scene scene, long time, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Net.OnceTimer(time, timerHandlerType); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。 + /// + /// + /// + /// + /// + /// + public static long OnceTillTimer(Scene scene, long tillTime, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Net.OnceTillTimer(tillTime, timerHandlerType); + } + + /// + /// 创建一个重复执行的计时器。 + /// + /// + /// + /// + /// + public static long RepeatedTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Net.RepeatedTimer(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。 + /// + /// + /// + /// + /// + /// + public static long RepeatedTimer(Scene scene, long time, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Net.RepeatedTimer(time, timerHandlerType); + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// + /// + /// + public static bool RemoveTimer(Scene scene, ref long timerId) + { + return scene.TimerComponent.Net.Remove(ref timerId); + } + + #endregion + + #region Unity + +#if FANTASY_UNITY + /// + /// 异步等待指定时间。(使用Unity的Time时间) + /// + /// + /// + /// + /// + public static FTask UnityWait(Scene scene, long time, FCancellationToken cancellationToken = null) + { + return scene.TimerComponent.Unity.WaitAsync(time, cancellationToken); + } + + /// + /// 异步等待直到指定时间。(使用Unity的Time时间) + /// + /// + /// + /// + /// + public static FTask UnityWaitTill(Scene scene, long time, FCancellationToken cancellationToken = null) + { + return scene.TimerComponent.Unity.WaitTillAsync(time, cancellationToken); + } + + /// + /// 异步等待一帧时间。(使用Unity的Time时间) + /// + /// + /// + public static FTask UnityWaitFrame(Scene scene) + { + return scene.TimerComponent.Unity.WaitFrameAsync(); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。(使用Unity的Time时间) + /// + /// + /// + /// + /// + public static long UnityOnceTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Unity.OnceTimer(time, action); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。(使用Unity的Time时间) + /// + /// + /// + /// + /// + public static long UnityOnceTillTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Unity.OnceTillTimer(time, action); + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。(使用Unity的Time时间) + /// + /// + /// + /// + /// + /// + public static long UnityOnceTimer(Scene scene, long time, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Unity.OnceTimer(time, timerHandlerType); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。(使用Unity的Time时间) + /// + /// + /// + /// + /// + /// + public static long UnityOnceTillTimer(Scene scene, long tillTime, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Unity.OnceTillTimer(tillTime, timerHandlerType); + } + + /// + /// 创建一个重复执行的计时器。(使用Unity的Time时间) + /// + /// + /// + /// + /// + public static long UnityRepeatedTimer(Scene scene, long time, Action action) + { + return scene.TimerComponent.Unity.RepeatedTimer(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。(使用Unity的Time时间) + /// + /// + /// + /// + /// + /// + public static long UnityRepeatedTimer(Scene scene, long time, T timerHandlerType) where T : struct + { + return scene.TimerComponent.Unity.RepeatedTimer(time, timerHandlerType); + } + + /// + /// 移除指定 ID 的计时器。(使用Unity的Time时间) + /// + /// + /// + /// + public static bool UnityRemoveTimer(Scene scene, ref long timerId) + { + return scene.TimerComponent.Unity.Remove(ref timerId); + } +#endif + + #endregion + + /// + /// 创建并运行一个异步任务 + /// + /// + /// + public static FTask Run(Func factory) + { + return factory(); + } + + /// + /// 创建并运行一个带有结果的异步任务 + /// + /// + /// + /// + public static FTask Run(Func> factory) + { + return factory(); + } + + /// + /// 等待所有任务完成 + /// + /// + public static async FTask WaitAll(List tasks) + { + if (tasks.Count <= 0) + { + return; + } + + var count = tasks.Count; + var sTaskCompletionSource = Create(); + + foreach (var task in tasks) + { + RunSTask(task).Coroutine(); + } + + await sTaskCompletionSource; + + async FVoid RunSTask(FTask task) + { + await task; + count--; + if (count <= 0) + { + sTaskCompletionSource.SetResult(); + } + } + } + /// + /// 等待其中一个任务完成 + /// + /// + public static async FTask WaitAny(List tasks) + { + if (tasks.Count <= 0) + { + return; + } + + var count = 1; + var sTaskCompletionSource = Create(); + + foreach (var task in tasks) + { + RunSTask(task).Coroutine(); + } + + await sTaskCompletionSource; + + async FVoid RunSTask(FTask task) + { + await task; + count--; + if (count == 0) + { + sTaskCompletionSource.SetResult(); + } + } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs.meta b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs.meta new file mode 100644 index 0000000..3c07e7f --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/FTask.Extension/FTask.Tools.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1740bb2a5275f44281fa9aa97419e78 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Task.meta b/Runtime/CoreRuntime/Core/FTask/Task.meta new file mode 100644 index 0000000..c3f40fa --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 481d96d4488ac824ca46a1515942f9a5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs b/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs new file mode 100644 index 0000000..ce925f2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs @@ -0,0 +1,263 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable ConditionalAccessQualifierIsNonNullableAccordingToAPIContract +// ReSharper disable CheckNamespace +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Async +{ + public enum STaskStatus : byte + { + Pending = 0, // The operation has not yet completed. + Succeeded = 1, // The operation completed successfully. + Faulted = 2 // The operation completed with an error. + } + + [AsyncMethodBuilder(typeof(AsyncFTaskMethodBuilder))] + public sealed partial class FTask : ICriticalNotifyCompletion + { + private Action _callBack; + private ExceptionDispatchInfo _exception; + private STaskStatus _status = STaskStatus.Pending; + public bool IsCompleted + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _status != STaskStatus.Pending; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public FTask GetAwaiter() => this; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private async FVoid InnerCoroutine() + { + await this; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Coroutine() + { + InnerCoroutine().Coroutine(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GetResult() + { + switch (_status) + { + case STaskStatus.Succeeded: + { + Return(); + return; + } + case STaskStatus.Faulted: + { + Return(); + + if (_exception == null) + { + return; + } + + var exception = _exception; + _exception = null; + exception.Throw(); + return; + } + default: + { + throw new NotSupportedException("Direct call to getResult is not allowed"); + } + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() + { + if (_status != STaskStatus.Pending) + { + throw new InvalidOperationException("The task has been completed"); + } + + _status = STaskStatus.Succeeded; + + if (_callBack == null) + { + return; + } + + var callBack = _callBack; + _callBack = null; + callBack.Invoke(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action action) + { + UnsafeOnCompleted(action); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action action) + { + if (_status != STaskStatus.Pending) + { + action?.Invoke(); + return; + } + + _callBack = action; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + if (_status != STaskStatus.Pending) + { + throw new InvalidOperationException("The task has been completed"); + } + + _status = STaskStatus.Faulted; + _exception = ExceptionDispatchInfo.Capture(exception); + _callBack?.Invoke(); + } + } + + [AsyncMethodBuilder(typeof(AsyncFTaskMethodBuilder<>))] + public sealed partial class FTask : ICriticalNotifyCompletion + { + private T _value; + private Action _callBack; + private ExceptionDispatchInfo _exception; + private STaskStatus _status = STaskStatus.Pending; + public bool IsCompleted + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _status != STaskStatus.Pending; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public FTask GetAwaiter() => this; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [DebuggerHidden] + private async FVoid InnerCoroutine() + { + await this; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Coroutine() + { + InnerCoroutine().Coroutine(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T GetResult() + { + switch (_status) + { + case STaskStatus.Succeeded: + { + var value = _value; + Return(); + return value; + } + case STaskStatus.Faulted: + { + Return(); + + if (_exception == null) + { + return default; + } + + var exception = _exception; + _exception = null; + exception.Throw(); + return default; + } + default: + { + throw new NotSupportedException("Direct call to getResult is not allowed"); + } + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult(T value) + { + if (_status != STaskStatus.Pending) + { + throw new InvalidOperationException("The task has been completed"); + } + + _value = value; + _status = STaskStatus.Succeeded; + + if (_callBack == null) + { + return; + } + + var callBack = _callBack; + _callBack = null; + callBack.Invoke(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action action) + { + UnsafeOnCompleted(action); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action action) + { + if (_status != STaskStatus.Pending) + { + action?.Invoke(); + return; + } + + _callBack = action; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + if (_status != STaskStatus.Pending) + { + throw new InvalidOperationException("The task has been completed"); + } + + _status = STaskStatus.Faulted; + _exception = ExceptionDispatchInfo.Capture(exception); + _callBack?.Invoke(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs.meta b/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs.meta new file mode 100644 index 0000000..41f58ff --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b93ea81277623f40a7eac969ec52faf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs b/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs new file mode 100644 index 0000000..48b9e36 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs @@ -0,0 +1,31 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Async +{ + [StructLayout(LayoutKind.Auto)] + [AsyncMethodBuilder(typeof(AsyncFTaskCompletedMethodBuilder))] + public struct FTaskCompleted : ICriticalNotifyCompletion + { + [DebuggerHidden] + public bool IsCompleted => true; + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public FTaskCompleted GetAwaiter() + { + return this; + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GetResult() { } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation) { } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action continuation) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs.meta b/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs.meta new file mode 100644 index 0000000..f8278c2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FTaskCompleted.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1cff360ee003fa49b9245a94a5134d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs b/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs new file mode 100644 index 0000000..f10ca7c --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Fantasy.Async +{ + [StructLayout(LayoutKind.Auto)] + [AsyncMethodBuilder(typeof(AsyncFVoidMethodBuilder))] + internal struct FVoid : ICriticalNotifyCompletion + { + public bool IsCompleted + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => true; + } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Coroutine() { } + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation) { } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action continuation) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs.meta b/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs.meta new file mode 100644 index 0000000..0f0ab50 --- /dev/null +++ b/Runtime/CoreRuntime/Core/FTask/Task/FVoid.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1d3fb384eb2539a41b1db05b7644ead6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper.meta b/Runtime/CoreRuntime/Core/Helper.meta new file mode 100644 index 0000000..7fa7753 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cdf67b0342e47d84ebda41107d16e8fa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs b/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs new file mode 100644 index 0000000..3e8492b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs @@ -0,0 +1,801 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; + +namespace Fantasy.Helper +{ + /// + /// 提供字节操作辅助方法的静态类。 + /// + public static class ByteHelper + { + private static readonly string[] HexTableUpper = new string[256]; + private static readonly string[] HexTableLower = new string[256]; + private static readonly string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" }; + private static readonly long[] Divisors = { 1L, 1024L, 1024L * 1024, 1024L * 1024 * 1024, 1024L * 1024 * 1024 * 1024 }; + + static ByteHelper() + { + // 预计算所有256个字节的十六进制表示 + for (var i = 0; i < 256; i++) + { + HexTableUpper[i] = i.ToString("X2"); // 大写:00, 01, ..., FF + HexTableLower[i] = i.ToString("x2"); // 小写:00, 01, ..., ff + } + } + + #region Read + + /// + /// 从指定的流中读取一个 64 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReadInt64(this Stream stream) + { + Span buffer = stackalloc byte[8]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + /// + /// 从指定的流中读取一个 32 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadInt32(this Stream stream) + { + Span buffer = stackalloc byte[4]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + /// + /// 从指定的流中读取一个 16 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadInt16(this Stream stream) + { + Span buffer = stackalloc byte[2]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + /// + /// 从指定的流中读取一个无符号 64 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ReadUInt64(this Stream stream) + { + Span buffer = stackalloc byte[8]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + /// + /// 从指定的流中读取一个无符号 32 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ReadUInt32(this Stream stream) + { + Span buffer = stackalloc byte[4]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + /// + /// 从指定的流中读取一个无符号 16 位整数。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ReadUInt16(this Stream stream) + { + Span buffer = stackalloc byte[2]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + _ = stream.Read(buffer); +#endif + return MemoryMarshal.Read(buffer); + } + + #endregion + + #region WriteTo + + /// + /// 将值写入字节数组的指定偏移位置。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTo(this byte[] bytes, int offset, T value) where T : unmanaged + { + if (offset < 0 || offset + Marshal.SizeOf() > bytes.Length) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + MemoryMarshal.Write(bytes.AsSpan(offset), +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + } + + /// + /// 将值写入Span的指定偏移位置。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTo(this Span span, int offset, T value) where T : unmanaged + { + if (offset < 0 || offset + Marshal.SizeOf() > span.Length) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + MemoryMarshal.Write(span.Slice(offset), +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + } + + /// + /// 将值写入内存流 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTo(this Stream stream, T value) where T : unmanaged + { + Span buffer = stackalloc byte[Marshal.SizeOf()]; + MemoryMarshal.Write(buffer, +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + stream.Write(buffer); + } + + /// + /// 将值写入内存流的指定偏移位置。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTo(this Stream stream, int offset, T value) where T : unmanaged + { + if (stream == null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanSeek) + { + throw new NotSupportedException("Stream must support seeking"); + } + + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + var originalPosition = stream.Position; + try + { + stream.Position = offset; + Span buffer = stackalloc byte[Marshal.SizeOf()]; + MemoryMarshal.Write(buffer, +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + stream.Write(buffer); + } + finally + { + stream.Position = originalPosition; + } + } + + #endregion + + #region ReadFrom + + /// + /// 从字节数组的指定偏移位置读取值。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadFrom(this byte[] bytes, int offset) where T : unmanaged + { + if (offset < 0 || offset + Marshal.SizeOf() > bytes.Length) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + return MemoryMarshal.Read(bytes.AsSpan(offset)); + } + + /// + /// 从Span的指定偏移位置读取值。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadFrom(this ReadOnlySpan span, int offset) where T : unmanaged + { + if (offset < 0 || offset + Marshal.SizeOf() > span.Length) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + return MemoryMarshal.Read(span.Slice(offset)); + } + + /// + /// 从流的指定偏移位置读取值 + /// + /// + /// + /// 是否在读取完成后恢复到原始位置 + /// + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ReadFrom(this Stream stream, int offset, bool restorePosition = false) where T : unmanaged + { + if (stream == null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanSeek) + { + throw new NotSupportedException("Stream must support seeking"); + } + + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + var originalPosition = restorePosition ? stream.Position : 0; + + try + { + var sizeOf = Marshal.SizeOf(); + stream.Position = offset; + Span buffer = stackalloc byte[sizeOf]; +#if FANTASY_NET + stream.ReadExactly(buffer); +#else + var bytesRead = stream.Read(buffer); + if (bytesRead != sizeOf) + { + throw new EndOfStreamException($"Could not read {sizeOf} bytes from stream"); + } +#endif + return MemoryMarshal.Read(buffer); + } + finally + { + if (restorePosition) + { + stream.Position = originalPosition; + } + } + } + + #endregion + + #region GetBytes + + /// + /// 将值转换为字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetBytes(this T value, Span buffer) where T : unmanaged + { + if (buffer.Length < Marshal.SizeOf()) + { + throw new ArgumentException($"Buffer too small. Required: {Marshal.SizeOf()}, Actual: {buffer.Length}"); + } + + MemoryMarshal.Write(buffer, +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + } + + /// + /// 将值转换为字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetBytes(this T value, byte[] buffer) where T : unmanaged + { + value.GetBytes(buffer.AsSpan()); + } + + /// + /// 将值转换为字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] GetBytes(this T value) where T : unmanaged + { + var result = new byte[Marshal.SizeOf()]; + MemoryMarshal.Write(result.AsSpan(), +#if FANTASY_NET || FANTASY_CONSOLE + in value +#endif +#if FANTASY_UNITY + ref value +#endif + ); + return result; + } + + #endregion + + #region ToReadableSpeed + + /// + /// 将字节数转换为可读的大小表示 + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToReadableSpeed(this long byteCount) + { + switch (byteCount) + { + case <= 0: + { + return "0 Byte"; + } + // < 1TB,使用快速版本 + case < 1L << 40: + { + var minLevel = 0; + var temp = byteCount; + while (temp >= 1024 && minLevel < 4) + { + temp >>= 10; + minLevel++; + } + return $"{(double)byteCount / Divisors[minLevel]:0.##} {Suffix[minLevel]}"; + } + default: + { +#if NET6_0_OR_GREATER + var level = Math.Min((int)(Math.Log2(byteCount) / 10), Suffix.Length - 1); +#else + // .NET Framework / .NET Core < 6.0 替代方案 + var level = Math.Min((int)(Math.Log(byteCount) / Math.Log(2) / 10), Suffix.Length - 1); +#endif + var divisor = 1L << (level * 10); + var value = (double)byteCount / divisor; + return $"{value:0.##} {Suffix[level]}"; + } + } + } + + /// + /// 将字节数转换为可读的大小表示(无符号版本) + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToReadableSpeed(this ulong byteCount) + { + switch (byteCount) + { + case 0: + { + return "0 Byte"; + } + // < 1TB,使用快速版本 + case < 1L << 40: + { + var minLevel = 0; + var temp = byteCount; + while (temp >= 1024 && minLevel < 4) + { + temp >>= 10; + minLevel++; + } + return $"{(double)byteCount / Divisors[minLevel]:0.##} {Suffix[minLevel]}"; + } + default: + { +#if NET6_0_OR_GREATER + var level = Math.Min((int)(Math.Log2(byteCount) / 10), Suffix.Length - 1); +#else + // .NET Framework / .NET Core < 6.0 替代方案 + var level = Math.Min((int)(Math.Log(byteCount) / Math.Log(2) / 10), Suffix.Length - 1); +#endif + var divisor = 1L << (level * 10); + var value = (double)byteCount / divisor; + return $"{value:0.##} {Suffix[level]}"; + } + } + } + + #endregion + + #region MergeBytes + + /// + /// 合并字节数组到目标缓冲区(零分配版本)。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void MergeBytesTo(Span destination, ReadOnlySpan first, ReadOnlySpan second) + { + if (destination.Length < first.Length + second.Length) + throw new ArgumentException("Destination buffer too small"); + + first.CopyTo(destination); + second.CopyTo(destination.Slice(first.Length)); + } + + /// + /// 合并两个字节数组。 + /// + /// 第一个字节数组 + /// 第二个字节数组 + /// 合并后的字节数组 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] MergeBytes(byte[] bytes, byte[] otherBytes) + { + if (bytes == null) + { + throw new ArgumentNullException(nameof(bytes)); + } + + if (otherBytes == null) + { + throw new ArgumentNullException(nameof(otherBytes)); + } + + // 优化:如果其中一个为空,直接返回另一个的副本 + if (bytes.Length == 0) + { + return (byte[])otherBytes.Clone(); + } + + if (otherBytes.Length == 0) + { + return (byte[])bytes.Clone(); + } + + var result = new byte[bytes.Length + otherBytes.Length]; + bytes.CopyTo(result.AsSpan()); + otherBytes.CopyTo(result.AsSpan(bytes.Length)); + return result; + } + + #endregion + + #region ToHex + + /// + /// 将字节转换为大写十六进制字符串。 + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHex(this byte b) + { + return HexTableUpper[b]; + } + + /// + /// 将字节转换为小写十六进制字符串。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHexLower(this byte b) + { + return HexTableLower[b]; + } + + /// + /// 将字节转换为指定格式的十六进制字符串。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHex(this byte b, bool upperCase) + { + return upperCase ? HexTableUpper[b] : HexTableLower[b]; + } + + /// + /// 将字节数组转换为十六进制字符串表示。 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHex(this byte[] bytes, bool upperCase = true) + { + if (bytes == null) + { + throw new ArgumentNullException(nameof(bytes)); + } + + if (bytes.Length == 0) + { + return string.Empty; + } + + var hexTable = upperCase ? HexTableUpper : HexTableLower; + + return string.Create(bytes.Length * 2, (bytes, hexTable), (chars, state) => + { + var (buffer, table) = state; + var charIndex = 0; + ref var bytesRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); + + for (var i = 0; i < buffer.Length; i++) + { + var hexStr = table[Unsafe.Add(ref bytesRef, i)]; + chars[charIndex++] = hexStr[0]; + chars[charIndex++] = hexStr[1]; + } + }); + } + + /// + /// 将字节数组的指定范围按十六进制格式转换为字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHex(this byte[] bytes, int offset, int count, bool upperCase = true) + { + if (bytes == null) + { + throw new ArgumentNullException(nameof(bytes)); + } + + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + if (count < 0 || offset + count > bytes.Length) + { + throw new ArgumentOutOfRangeException(nameof(count)); + } + + if (count == 0) + { + return string.Empty; + } + + var hexTable = upperCase ? HexTableUpper : HexTableLower; + + return string.Create(count * 2, (bytes, offset, count, hexTable), (chars, state) => + { + var (buffer, start, length, table) = state; + var charIndex = 0; + ref var bytesRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); + + for (var i = 0; i < length; i++) + { + var hexStr = table[Unsafe.Add(ref bytesRef, start + i)]; + chars[charIndex++] = hexStr[0]; + chars[charIndex++] = hexStr[1]; + } + }); + } + + /// + /// 将字节数组的指定范围按十六进制格式转换为字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToHex(this ReadOnlySpan bytes, bool upperCase = true) + { + if (bytes.Length == 0) + { + return string.Empty; + } + + var hexTable = upperCase ? HexTableUpper : HexTableLower; + + return string.Create(bytes.Length * 2, (MemoryMarshal.GetReference(bytes), bytes.Length, hexTable), (chars, + state) => + { + var (bytesRef, length, table) = state; + var charIndex = 0; + + for (var i = 0; i < length; i++) + { + var hexStr = table[Unsafe.Add(ref bytesRef, i)]; + chars[charIndex++] = hexStr[0]; + chars[charIndex++] = hexStr[1]; + } + }); + } + + /// + /// 将十六进制字符串转换为字节数组。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] FromHex(this string hexString) + { + return hexString.AsSpan().FromHex(); + } + + /// + /// 将十六进制字符串转换为字节数组。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte[] FromHex(this ReadOnlySpan hexSpan) + { + if (hexSpan.Length == 0) + { + return Array.Empty(); + } + + if (hexSpan.Length % 2 != 0) + { + throw new ArgumentException("Hex string must have even length"); + } + + var result = new byte[hexSpan.Length / 2]; + + for (var i = 0; i < result.Length; i++) + { + var high = HexCharToValue(hexSpan[i * 2]); + var low = HexCharToValue(hexSpan[i * 2 + 1]); + result[i] = (byte)((high << 4) | low); + } + + return result; + } + + + /// + /// 将十六进制字符串转换到现有字节数组。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void FromHexTo(this string hexString, Span destination) + { + if (string.IsNullOrEmpty(hexString)) + { + return; + } + + if (hexString.Length % 2 != 0) + { + throw new ArgumentException("Hex string must have even length", nameof(hexString)); + } + + if (destination.Length < hexString.Length / 2) + { + throw new ArgumentException("Destination buffer too small", nameof(destination)); + } + + for (var i = 0; i < hexString.Length / 2; i++) + { + var high = HexCharToValue(hexString[i * 2]); + var low = HexCharToValue(hexString[i * 2 + 1]); + destination[i] = (byte)((high << 4) | low); + } + } + + + /// + /// 将十六进制字符转换为数值。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int HexCharToValue(char c) + { + return c switch + { + >= '0' and <= '9' => c - '0', + >= 'A' and <= 'F' => c - 'A' + 10, + >= 'a' and <= 'f' => c - 'a' + 10, + _ => throw new ArgumentException($"Invalid hex character: {c}") + }; + } + + + /// + /// 将字节数组转换为默认编码的字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToStr(this byte[] bytes) + { + return Encoding.Default.GetString(bytes); + } + + /// + /// 将字节数组的指定范围按默认编码转换为字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToStr(this byte[] bytes, int index, int count) + { + return Encoding.Default.GetString(bytes, index, count); + } + + /// + /// 将字节数组转换为 UTF-8 编码的字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string Utf8ToStr(this byte[] bytes) + { + return Encoding.UTF8.GetString(bytes); + } + + /// + /// 将字节数组的指定范围按 UTF-8 编码转换为字符串表示。 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string Utf8ToStr(this byte[] bytes, int index, int count) + { + return Encoding.UTF8.GetString(bytes, index, count); + } + + + #endregion + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs.meta new file mode 100644 index 0000000..bb43023 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/ByteHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5a904b74442f064ab17e3b1f797fe33 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/Download.meta b/Runtime/CoreRuntime/Core/Helper/Download.meta new file mode 100644 index 0000000..535394f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 96ea51906d8d9f04eb839db70e7edaeb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs b/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs new file mode 100644 index 0000000..4846d51 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs @@ -0,0 +1,50 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public abstract class AUnityDownload : IDisposable + { + private long _timeId; + private ulong _totalDownloadedBytes; + private Download _download; + protected UnityWebRequest UnityWebRequest; + private FCancellationToken _cancellationToken; + private Scene Scene; + + protected AUnityDownload(Scene scene,Download download) + { + Scene = scene; + _download = download; + _download.Tasks.Add(this); + } + + protected UnityWebRequestAsyncOperation Start(UnityWebRequest unityWebRequest, bool monitor) + { + UnityWebRequest = unityWebRequest; + _timeId = Scene.TimerComponent.Unity.RepeatedTimer(33, Update); + return UnityWebRequest.SendWebRequest(); + } + + private void Update() + { + var downloadSpeed = UnityWebRequest.downloadedBytes - _totalDownloadedBytes; + _download.DownloadSpeed += downloadSpeed; + _download.TotalDownloadedBytes += downloadSpeed; + _totalDownloadedBytes = UnityWebRequest.downloadedBytes; + } + + public virtual void Dispose() + { + Update(); + _totalDownloadedBytes = 0; + UnityWebRequest?.Dispose(); + _download.Tasks.Remove(this); + Scene.TimerComponent.Unity.Remove(ref _timeId); + _download = null; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs.meta new file mode 100644 index 0000000..9668439 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/ADownload.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c7c3582dce88e5a4c93201daead54fc3 +timeCreated: 1726021902 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/Download.cs b/Runtime/CoreRuntime/Core/Helper/Download/Download.cs new file mode 100644 index 0000000..a53a42a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/Download.cs @@ -0,0 +1,72 @@ +#if FANTASY_UNITY +using System.Collections.Generic; +using System.Linq; +using Fantasy.Async; +using UnityEngine; + +namespace Fantasy.Unity.Download +{ + public sealed class Download + { + public Scene Scene; + public ulong DownloadSpeed; + public ulong TotalDownloadedBytes; + public readonly HashSet Tasks = new(); + + public static Download Create(Scene scene) => new Download(scene); + + private Download(Scene scene) + { + Scene = scene; + } + + public void Clear() + { + DownloadSpeed = 0; + TotalDownloadedBytes = 0; + + if (Tasks.Count <= 0) + { + return; + } + + foreach (var aUnityDownload in Tasks.ToArray()) + { + aUnityDownload.Dispose(); + } + + Tasks.Clear(); + } + + public FTask DownloadAssetBundle(string url, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadAssetBundle(Scene, this).StartDownload(url, monitor, cancellationToken); + } + + public FTask DownloadAudioClip(string url, AudioType audioType, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadAudioClip(Scene, this).StartDownload(url, audioType, monitor, cancellationToken); + } + + public FTask DownloadSprite(string url, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadSprite(Scene, this).StartDownload(url, monitor, cancellationToken); + } + + public FTask DownloadTexture(string url, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadTexture(Scene, this).StartDownload(url, monitor, cancellationToken); + } + + public FTask DownloadText(string url, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadText(Scene, this).StartDownload(url, monitor, cancellationToken); + } + + public FTask DownloadByte(string url, bool monitor = false, FCancellationToken cancellationToken = null) + { + return new DownloadByte(Scene, this).StartDownload(url, monitor, cancellationToken); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/Download.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/Download.cs.meta new file mode 100644 index 0000000..c47ba15 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/Download.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 799e99126b3695e4e9eddae7e2132d18 +timeCreated: 1726023436 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs new file mode 100644 index 0000000..9d8f5a4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs @@ -0,0 +1,54 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadAssetBundle : AUnityDownload + { + public DownloadAssetBundle(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequestAssetBundle.GetAssetBundle(Uri.EscapeUriString(url)), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var assetBundle = DownloadHandlerAssetBundle.GetContent(UnityWebRequest); + task.SetResult(assetBundle); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs.meta new file mode 100644 index 0000000..f97d38f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAssetBundle.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 54d273c7061258448bd1b3a465b08096 +timeCreated: 1726023471 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs new file mode 100644 index 0000000..29b3dc5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs @@ -0,0 +1,54 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadAudioClip : AUnityDownload + { + public DownloadAudioClip(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, AudioType audioType, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequestMultimedia.GetAudioClip(Uri.EscapeUriString(url), audioType), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var audioClip = DownloadHandlerAudioClip.GetContent(UnityWebRequest); + task.SetResult(audioClip); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs.meta new file mode 100644 index 0000000..cc25b99 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadAudioClip.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0feed95c5e7599b43ae8ca4e1d8f1794 +timeCreated: 1726023476 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs new file mode 100644 index 0000000..6c934d9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs @@ -0,0 +1,52 @@ +#if FANTASY_UNITY +using Fantasy.Async; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadByte : AUnityDownload + { + public DownloadByte(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequest.Get(url), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var bytes = UnityWebRequest.downloadHandler.data; + task.SetResult(bytes); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs.meta new file mode 100644 index 0000000..cc545be --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadByte.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0f43d3ba442968e40bc0f02feb457805 +timeCreated: 1726023481 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs new file mode 100644 index 0000000..802a967 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs @@ -0,0 +1,55 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadSprite : AUnityDownload + { + public DownloadSprite(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequestTexture.GetTexture(Uri.EscapeUriString(url)), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var texture = DownloadHandlerTexture.GetContent(UnityWebRequest); + var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 5, 1f); + task.SetResult(sprite); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs.meta new file mode 100644 index 0000000..e21a345 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadSprite.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d95ac549af149ee4a89f07f2a7bcdb7d +timeCreated: 1726023487 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs new file mode 100644 index 0000000..50d8329 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs @@ -0,0 +1,52 @@ +#if FANTASY_UNITY +using Fantasy.Async; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadText : AUnityDownload + { + public DownloadText(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequest.Get(url), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var text = UnityWebRequest.downloadHandler.text; + task.SetResult(text); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs.meta new file mode 100644 index 0000000..4cd1b4a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadText.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1e07c7aa9ed11184daf8530b6ea3c1be +timeCreated: 1726023491 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs b/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs new file mode 100644 index 0000000..f66533d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs @@ -0,0 +1,54 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine; +using UnityEngine.Networking; + +namespace Fantasy.Unity.Download +{ + public sealed class DownloadTexture : AUnityDownload + { + public DownloadTexture(Scene scene, Download download) : base(scene, download) + { + } + + public FTask StartDownload(string url, bool monitor, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequestAsyncOperation = Start(UnityWebRequestTexture.GetTexture(Uri.EscapeUriString(url)), monitor); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + Dispose(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + try + { + if (UnityWebRequest.result == UnityWebRequest.Result.Success) + { + var texture = DownloadHandlerTexture.GetContent(UnityWebRequest); + task.SetResult(texture); + } + else + { + Log.Error(UnityWebRequest.error); + task.SetResult(null); + } + } + finally + { + Dispose(); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs.meta b/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs.meta new file mode 100644 index 0000000..6e8d4d7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/Download/DownloadTexture.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5fceaaf4a528acb40a1186405a58d492 +timeCreated: 1726023496 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs b/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs new file mode 100644 index 0000000..5cbe7c7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs @@ -0,0 +1,63 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Fantasy.Helper +{ + /// + /// 提供计算 MD5 散列值的辅助方法。 + /// + public static partial class EncryptHelper + { + private static readonly SHA256 Sha256Hash = SHA256.Create(); + + /// + /// 计算指定字节数组的Sha256。 + /// + /// + /// + public static byte[] ComputeSha256Hash(byte[] bytes) + { +#if FANTASY_UNITY + using var sha256Hash = SHA256.Create(); + return sha256Hash.ComputeHash(bytes); +#else + return SHA256.HashData(bytes); +#endif + } + + /// + /// 计算指定文件的 MD5 散列值。 + /// + /// 要计算散列值的文件路径。 + /// 表示文件的 MD5 散列值的字符串。 + public static string FileMD5(string filePath) + { + using var file = new FileStream(filePath, FileMode.Open); + return FileMD5(file); + } + + /// + /// 计算给定文件流的 MD5 散列值。 + /// + /// 要计算散列值的文件流。 + /// 表示文件流的 MD5 散列值的字符串。 + public static string FileMD5(FileStream fileStream) + { + var md5 = MD5.Create(); + return md5.ComputeHash(fileStream).ToHex(false); + } + + /// + /// 计算给定字节数组的 MD5 散列值。 + /// + /// 要计算散列值的字节数组。 + /// 表示字节数组的 MD5 散列值的字符串。 + public static string BytesMD5(byte[] bytes) + { + var md5 = MD5.Create(); + bytes = md5.ComputeHash(bytes); + return bytes.ToHex(false); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs.meta new file mode 100644 index 0000000..bd8992d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/EncryptHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b4fd2a8784ea964c98ccbde872ff96e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/FileHelper.cs b/Runtime/CoreRuntime/Core/Helper/FileHelper.cs new file mode 100644 index 0000000..00c18ec --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/FileHelper.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace Fantasy.Helper +{ + /// + /// 文件操作助手类,提供了各种文件操作方法。 + /// + public static partial class FileHelper + { + /// + /// 获取相对路径的完整路径。 + /// + /// 相对路径。 + /// 完整路径。 + public static string GetFullPath(string relativePath) + { + return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, relativePath)); + } + + /// + /// 获取相对路径的完整路径。 + /// + /// 相对于指定的目录的相对路径。 + /// 指定的目录 + /// 完整路径。 + public static string GetFullPath(string relativePath, string srcDir) + { + return Path.GetFullPath(Path.Combine(srcDir, relativePath)); + } + + /// + /// 获取相对路径的的文本信息。 + /// + /// + /// + public static async Task GetTextByRelativePath(string relativePath) + { + var fullPath = GetFullPath(relativePath); + return await File.ReadAllTextAsync(fullPath, Encoding.UTF8); + } + + /// + /// 获取绝对路径的的文本信息。 + /// + /// + /// + public static async Task GetText(string fullPath) + { + return await File.ReadAllTextAsync(fullPath, Encoding.UTF8); + } + + /// + /// 根据文件夹路径创建文件夹,如果文件夹不存在会自动创建文件夹。 + /// + /// + public static void CreateDirectory(string directoryPath) + { + if (directoryPath.LastIndexOf('/') != directoryPath.Length - 1) + { + directoryPath += "/"; + } + + var directoriesByFilePath = GetDirectoriesByFilePath(directoryPath); + + foreach (var dir in directoriesByFilePath) + { + if (Directory.Exists(dir)) + { + continue; + } + + Directory.CreateDirectory(dir); + } + } + + /// + /// 将文件复制到目标路径,如果目标目录不存在会自动创建目录。 + /// + /// 源文件路径。 + /// 目标文件路径。 + /// 是否覆盖已存在的目标文件。 + public static void Copy(string sourceFile, string destinationFile, bool overwrite) + { + CreateDirectory(destinationFile); + File.Copy(sourceFile, destinationFile, overwrite); + } + + /// + /// 获取文件路径内的所有文件夹路径。 + /// + /// 文件路径。 + /// 文件夹路径列表。 + public static IEnumerable GetDirectoriesByFilePath(string filePath) + { + var dir = ""; + var fileDirectories = filePath.Split('/'); + + for (var i = 0; i < fileDirectories.Length - 1; i++) + { + dir = $"{dir}{fileDirectories[i]}/"; + yield return dir; + } + + if (fileDirectories.Length == 1) + { + yield return filePath; + } + } + + /// + /// 将文件夹内的所有内容复制到目标位置。 + /// + /// 源文件夹路径。 + /// 目标文件夹路径。 + /// 是否覆盖已存在的文件。 + public static void CopyDirectory(string sourceDirectory, string destinationDirectory, bool overwrite) + { + // 创建目标文件夹 + + if (!Directory.Exists(destinationDirectory)) + { + Directory.CreateDirectory(destinationDirectory); + } + + // 获取当前文件夹中的所有文件 + + var files = Directory.GetFiles(sourceDirectory); + + // 拷贝文件到目标文件夹 + + foreach (var file in files) + { + var fileName = Path.GetFileName(file); + var destinationPath = Path.Combine(destinationDirectory, fileName); + File.Copy(file, destinationPath, overwrite); + } + + // 获取源文件夹中的所有子文件夹 + + var directories = Directory.GetDirectories(sourceDirectory); + + // 递归方式拷贝文件夹 + + foreach (var directory in directories) + { + var directoryName = Path.GetFileName(directory); + var destinationPath = Path.Combine(destinationDirectory, directoryName); + CopyDirectory(directory, destinationPath, overwrite); + } + } + + /// + /// 获取目录下的所有文件 + /// + /// 文件夹路径。 + /// 需要查找的文件通配符 + /// 查找的类型 + /// + public static string[] GetDirectoryFile(string folderPath, string searchPattern, SearchOption searchOption) + { + return Directory.GetFiles(folderPath, searchPattern, searchOption); + } + + /// + /// 清空文件夹内的所有文件。 + /// + /// 文件夹路径。 + public static void ClearDirectoryFile(string folderPath) + { + if (!Directory.Exists(folderPath)) + { + return; + } + + var files = Directory.GetFiles(folderPath); + + foreach (var file in files) + { + File.Delete(file); + } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/FileHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/FileHelper.cs.meta new file mode 100644 index 0000000..5f52ca8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/FileHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b0496824a5f4c042833fadb6344d2ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs b/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs new file mode 100644 index 0000000..4ea6f29 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs @@ -0,0 +1,336 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +// ReSharper disable InconsistentNaming + +namespace Fantasy.Helper +{ + /// + /// HashCode算法帮助类 + /// + public static partial class HashCodeHelper + { + /// + /// 计算两个字符串的HashCode + /// + /// + /// + /// + public static int GetHashCode(string a, string b) + { + var hash = 17; + hash = hash * 31 + a.GetHashCode(); + hash = hash * 31 + b.GetHashCode(); + return hash; + } + + /// + /// 使用bkdr算法生成一个long的值 + /// + /// + /// + public static long GetBKDRHashCode(string str) + { + ulong hash = 0; + const uint seed = 13131; // 如果要修改这个种子、建议选择一个质数来做种子 31 131 1313 13131 131313 etc.. + var span = str.AsSpan(); + ref var local = ref MemoryMarshal.GetReference(span); + + for (var i = 0; i < span.Length; i++) + { + var c = Unsafe.Add(ref local, i); + var high = (byte)(c >> 8); + var low = (byte)(c & byte.MaxValue); + hash = hash * seed + high; + hash = hash * seed + low; + } + + return (long)hash; + } + + /// + /// 使用MurmurHash3算法生成一个uint的值 + /// + /// + /// + public static uint MurmurHash3(string str) + { + const uint seed = 0xc58f1a7b; + uint hash = seed; + uint c1 = 0xcc9e2d51; + uint c2 = 0x1b873593; + + var span = str.AsSpan(); + ref var local = ref MemoryMarshal.GetReference(span); + + for (var i = 0; i < span.Length; i++) + { + var k1 = (uint)Unsafe.Add(ref local, i); + k1 *= c1; + k1 = (k1 << 15) | (k1 >> (32 - 15)); + k1 *= c2; + + hash ^= k1; + hash = (hash << 13) | (hash >> (32 - 13)); + hash = hash * 5 + 0xe6546b64; + } + + hash ^= (uint)str.Length; + hash ^= hash >> 16; + hash *= 0x85ebca6b; + hash ^= hash >> 13; + hash *= 0xc2b2ae35; + hash ^= hash >> 16; + return hash; + } + + /// + /// 使用MurmurHash3算法生成一个long的值 + /// + /// + /// + public static long ComputeHash64(string str) + { + const ulong seed = 0xc58f1a7bc58f1a7bUL; // 64-bit seed + var hash = seed; + var c1 = 0x87c37b91114253d5UL; + var c2 = 0x4cf5ad432745937fUL; + + var span = str.AsSpan(); + ref var local = ref MemoryMarshal.GetReference(span); + + for (var i = 0; i < span.Length; i++) + { + var k1 = (ulong)Unsafe.Add(ref local, i); + k1 *= c1; + k1 = (k1 << 31) | (k1 >> (64 - 31)); + k1 *= c2; + + hash ^= k1; + hash = (hash << 27) | (hash >> (64 - 27)); + hash = hash * 5 + 0x52dce729; + } + + hash ^= (ulong)str.Length; + hash ^= hash >> 33; + hash *= 0xff51afd7ed558ccdUL; + hash ^= hash >> 33; + hash *= 0xc4ceb9fe1a85ec53UL; + hash ^= hash >> 33; + return (long)hash; + } + + /// + /// 根据字符串计算一个Hash值 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Hash32(string obj, uint seed = 0) => Hash32(obj.AsSpan(), seed); + + /// + /// 根据字符串计算一个Hash值 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Hash32(in T obj, uint seed = 0) where T : unmanaged => Hash32( + MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As(ref Unsafe.AsRef(in obj)), Unsafe.SizeOf()), + seed); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Hash32(ReadOnlySpan buffer, uint seed = 0) where T : unmanaged => + Hash32(MemoryMarshal.Cast(buffer), seed); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Hash32(ReadOnlySpan buffer, uint seed = 0) + { + int length = buffer.Length; + ref byte local1 = ref MemoryMarshal.GetReference(buffer); + uint num1; + if (buffer.Length >= 16) + { + uint num2 = seed + 606290984U; + uint num3 = seed + 2246822519U; + uint num4 = seed; + uint num5 = seed - 2654435761U; + for (; length >= 16; length -= 16) + { + const nint elementOffset1 = 4; + const nint elementOffset2 = 8; + const nint elementOffset3 = 12; + nint byteOffset = buffer.Length - length; + ref byte local2 = ref Unsafe.AddByteOffset(ref local1, byteOffset); + uint num6 = num2 + Unsafe.ReadUnaligned(ref local2) * 2246822519U; + num2 = (uint)((((int)num6 << 13) | (int)(num6 >> 19)) * -1640531535); + uint num7 = num3 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, elementOffset1)) * + 2246822519U; + num3 = (uint)((((int)num7 << 13) | (int)(num7 >> 19)) * -1640531535); + uint num8 = num4 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, elementOffset2)) * + 2246822519U; + num4 = (uint)((((int)num8 << 13) | (int)(num8 >> 19)) * -1640531535); + uint num9 = num5 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, elementOffset3)) * + 2246822519U; + num5 = (uint)((((int)num9 << 13) | (int)(num9 >> 19)) * -1640531535); + } + + num1 = (uint)((((int)num2 << 1) | (int)(num2 >> 31)) + (((int)num3 << 7) | (int)(num3 >> 25)) + + (((int)num4 << 12) | (int)(num4 >> 20)) + (((int)num5 << 18) | (int)(num5 >> 14)) + + buffer.Length); + } + else + num1 = (uint)((int)seed + 374761393 + buffer.Length); + + for (; length >= 4; length -= 4) + { + nint byteOffset = buffer.Length - length; + uint num10 = Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local1, byteOffset)); + uint num11 = num1 + num10 * 3266489917U; + num1 = (uint)((((int)num11 << 17) | (int)(num11 >> 15)) * 668265263); + } + + nint byteOffset1 = buffer.Length - length; + ref byte local3 = ref Unsafe.AddByteOffset(ref local1, byteOffset1); + for (int index = 0; index < length; ++index) + { + nint byteOffset2 = index; + uint num12 = Unsafe.AddByteOffset(ref local3, byteOffset2); + uint num13 = num1 + num12 * 374761393U; + num1 = (uint)((((int)num13 << 11) | (int)(num13 >> 21)) * -1640531535); + } + +#if NET7_0_OR_GREATER + int num14 = ((int)num1 ^ (int)(num1 >> 15)) * -2048144777; + int num15 = (num14 ^ (num14 >>> 13)) * -1028477379; + return num15 ^ (num15 >>> 16); +#else + int num14 = ((int)num1 ^ (int)(num1 >> 15)) * -2048144777; + int num15 = (num14 ^ (int)((uint)num14 >> 13)) * -1028477379; + return num15 ^ (int)((uint)num15 >> 16); +#endif + } + + /// + /// 根据字符串计算一个Hash值 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Hash64(string obj, ulong seed = 0) => Hash64(obj.AsSpan(), seed); + + /// + /// 根据字符串计算一个Hash值 + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Hash64(in T obj, ulong seed = 0) where T : unmanaged => Hash64( + MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As(ref Unsafe.AsRef(in obj)), Unsafe.SizeOf()), + seed); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static long Hash64(ReadOnlySpan buffer, ulong seed = 0) where T : unmanaged => + Hash64(MemoryMarshal.Cast(buffer), seed); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static long Hash64(ReadOnlySpan buffer, ulong seed = 0) + { + ref var local1 = ref MemoryMarshal.GetReference(buffer); + var length = buffer.Length; + ulong num1; + if (buffer.Length >= 32) + { + var num2 = seed + 6983438078262162902UL; + var num3 = seed + 14029467366897019727UL; + var num4 = seed; + var num5 = seed - 11400714785074694791UL; + for (; length >= 32; length -= 32) + { + ref var local2 = ref Unsafe.AddByteOffset(ref local1, (IntPtr)(buffer.Length - length)); + var num6 = num2 + Unsafe.ReadUnaligned(ref local2) * 14029467366897019727UL; + num2 = (ulong)((((long)num6 << 31) | (long)(num6 >> 33)) * -7046029288634856825L); + var num7 = num3 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, new UIntPtr(8U))) * + 14029467366897019727UL; + num3 = (ulong)((((long)num7 << 31) | (long)(num7 >> 33)) * -7046029288634856825L); + var num8 = num4 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, new UIntPtr(16U))) * + 14029467366897019727UL; + num4 = (ulong)((((long)num8 << 31) | (long)(num8 >> 33)) * -7046029288634856825L); + var num9 = num5 + + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local2, new UIntPtr(24U))) * + 14029467366897019727UL; + num5 = (ulong)((((long)num9 << 31) | (long)(num9 >> 33)) * -7046029288634856825L); + } + + var num10 = (((long)num2 << 1) | (long)(num2 >> 63)) + (((long)num3 << 7) | (long)(num3 >> 57)) + + (((long)num4 << 12) | (long)(num4 >> 52)) + (((long)num5 << 18) | (long)(num5 >> 46)); + var num11 = num2 * 14029467366897019727UL; + var num12 = (((long)num11 << 31) | (long)(num11 >> 33)) * -7046029288634856825L; + var num13 = (num10 ^ num12) * -7046029288634856825L + -8796714831421723037L; + var num14 = num3 * 14029467366897019727UL; + var num15 = (((long)num14 << 31) | (long)(num14 >> 33)) * -7046029288634856825L; + var num16 = (num13 ^ num15) * -7046029288634856825L + -8796714831421723037L; + var num17 = num4 * 14029467366897019727UL; + var num18 = (((long)num17 << 31) | (long)(num17 >> 33)) * -7046029288634856825L; + var num19 = (num16 ^ num18) * -7046029288634856825L + -8796714831421723037L; + var num20 = num5 * 14029467366897019727UL; + var num21 = (((long)num20 << 31) | (long)(num20 >> 33)) * -7046029288634856825L; + num1 = (ulong)((num19 ^ num21) * -7046029288634856825L + -8796714831421723037L); + } + else + num1 = seed + 2870177450012600261UL; + + var num22 = num1 + (ulong)buffer.Length; + for (; length >= 8; length -= 8) + { + var num23 = Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local1, + (IntPtr)(buffer.Length - length))) * 14029467366897019727UL; + var num24 = (ulong)((((long)num23 << 31) | (long)(num23 >> 33)) * -7046029288634856825L); + var num25 = num22 ^ num24; + num22 = (ulong)((((long)num25 << 27) | (long)(num25 >> 37)) * -7046029288634856825L + + -8796714831421723037L); + } + + if (length >= 4) + { + ulong num26 = + Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref local1, (IntPtr)(buffer.Length - length))); + var num27 = num22 ^ (num26 * 11400714785074694791UL); + num22 = (ulong)((((long)num27 << 23) | (long)(num27 >> 41)) * -4417276706812531889L + + 1609587929392839161L); + length -= 4; + } + + for (var byteOffset = 0; byteOffset < length; ++byteOffset) + { + ulong num28 = + Unsafe.AddByteOffset(ref Unsafe.AddByteOffset(ref local1, (IntPtr)(buffer.Length - length)), + (IntPtr)byteOffset); + var num29 = num22 ^ (num28 * 2870177450012600261UL); + num22 = (ulong)((((long)num29 << 11) | (long)(num29 >> 53)) * -7046029288634856825L); + } + +#if NET7_0_OR_GREATER + var num30 = (long)num22; + var num31 = (num30 ^ (num30 >>> 33)) * -4417276706812531889L; + var num32 = (num31 ^ (num31 >>> 29)) * 1609587929392839161L; + return num32 ^ (num32 >>> 32); +#else + var num30 = (long)num22; + var num31 = (num30 ^ (long)((ulong)num30 >> 33)) * -4417276706812531889L; + var num32 = (num31 ^ (long)((ulong)num31 >> 29)) * 1609587929392839161L; + return num32 ^ (long)((ulong)num32 >> 32); +#endif + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs.meta new file mode 100644 index 0000000..7024137 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HashCodeHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5d4f73f93df70d7408eab98454a65260 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient.meta b/Runtime/CoreRuntime/Core/Helper/HttpClient.meta new file mode 100644 index 0000000..6e87fd5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2e14bc91a62c2004a827bdbef3f9f8aa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs new file mode 100644 index 0000000..3954a8c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs @@ -0,0 +1,144 @@ +#if !FANTASY_WEBGL +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Pool; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Http +{ + /// + /// HTTP帮助类 + /// + public static partial class HttpClientHelper + { + private static readonly HttpClient Client = new HttpClient(new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true + }); + + /// + /// 用Post方式请求string数据 + /// + /// + /// + /// + /// + public static async FTask CallNotDeserializeByPost(string url, HttpContent content) + { + var response = await Client.PostAsync(url, content); + + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 用Get方式请求string数据 + /// + /// + /// + /// + public static async FTask CallNotDeserializeByGet(string url) + { + var response = await Client.GetAsync(url); + + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + public static async FTask CallByPost(string url, HttpContent content) + { + return await Deserialize(url, await Client.PostAsync(url, content)); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + public static async FTask CallByPost(string url, HttpMethod method) + { + return await Deserialize(url, await Client.SendAsync(new HttpRequestMessage(method, url))); + } + + /// + /// 用Get方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + public static async FTask CallByGet(string url) + { + return await Deserialize(url, await Client.GetAsync(url)); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static async FTask Call(string url, int id, AuthenticationHeaderValue authentication, string method, params object[] @params) where TRequest : class, IJsonRpcRequest, new() + { + var request = Pool.Rent(); + using var httpClientPool = HttpClientPool.Create(); + var client = httpClientPool.Client; + client.DefaultRequestHeaders.Authorization = authentication; + + try + { + request.Init(method, id, @params); + var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json"); + var response = await Deserialize(url, await client.PostAsync(url, content)); + return response; + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + Pool.Return(request); + } + + return default; + } + + private static async FTask Deserialize(string url, HttpResponseMessage response) + { + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return (await response.Content.ReadAsStringAsync()).Deserialize(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs.meta new file mode 100644 index 0000000..ccdb1b7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2125dbf92a8ee544b8415c3e33d9b152 +timeCreated: 1726023741 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs new file mode 100644 index 0000000..de421ff --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs @@ -0,0 +1,44 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Net.Http; +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Http +{ + internal class HttpClientPool : IDisposable + { + private bool IsDispose { get; set; } + public HttpClient Client { get; private set; } + private static readonly Queue Pools = new Queue(); + private static readonly HttpClientHandler ClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true + }; + + public static HttpClientPool Create() + { + if (Pools.TryDequeue(out var httpClientPool)) + { + httpClientPool.IsDispose = false; + return httpClientPool; + } + + httpClientPool = new HttpClientPool(); + httpClientPool.Client = new HttpClient(ClientHandler); + return httpClientPool; + } + + public void Dispose() + { + if (IsDispose) + { + return; + } + + IsDispose = true; + Pools.Enqueue(this); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs.meta b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs.meta new file mode 100644 index 0000000..78d873b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/HttpClientPool.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fe26a6b64cfcdd74aa7072e5ef84d6db +timeCreated: 1726023895 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs b/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs new file mode 100644 index 0000000..ae756c5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs @@ -0,0 +1,20 @@ +using Fantasy.Pool; + +#if !FANTASY_WEBGL +namespace Fantasy.Http +{ + /// + /// 一个JsonRPC的接口 + /// + public interface IJsonRpcRequest : IPool + { + /// + /// 用于初始化这个Json对象 + /// + /// + /// + /// + void Init(string method, int id, params object[] @params); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta b/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta new file mode 100644 index 0000000..238afb6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2533b64d149d43e4fb4712c15e24c0fb +timeCreated: 1726023900 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs b/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs new file mode 100644 index 0000000..2b10fab --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs @@ -0,0 +1,57 @@ +using System; +using Newtonsoft.Json; +#pragma warning disable CS8603 + +namespace Fantasy.Helper +{ + /// + /// 提供操作 JSON 数据的辅助方法。 + /// + public static partial class JsonHelper + { + /// + /// 将对象序列化为 JSON 字符串。 + /// + /// 要序列化的对象类型。 + /// 要序列化的对象。 + /// 表示序列化对象的 JSON 字符串。 + public static string ToJson(this T t) + { + return JsonConvert.SerializeObject(t); + } + + /// + /// 反序列化 JSON 字符串为指定类型的对象。 + /// + /// 要反序列化的 JSON 字符串。 + /// 目标对象的类型。 + /// 是否使用反射进行反序列化(默认为 true)。 + /// 反序列化后的对象。 + public static object Deserialize(this string json, Type type, bool reflection = true) + { + return JsonConvert.DeserializeObject(json, type); + } + + /// + /// 反序列化 JSON 字符串为指定类型的对象。 + /// + /// 目标对象的类型。 + /// 要反序列化的 JSON 字符串。 + /// 反序列化后的对象。 + public static T Deserialize(this string json) + { + return JsonConvert.DeserializeObject(json); + } + + /// + /// 克隆对象,通过将对象序列化为 JSON,然后再进行反序列化。 + /// + /// 要克隆的对象类型。 + /// 要克隆的对象。 + /// 克隆后的对象。 + public static T Clone(T t) + { + return t.ToJson().Deserialize(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs.meta new file mode 100644 index 0000000..a085a55 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/JsonHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad75f95d9b200be47aa496158eb5eccf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs b/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs new file mode 100644 index 0000000..08dae1f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs @@ -0,0 +1,438 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#pragma warning disable CS8603 // Possible null reference return. + +// ReSharper disable InconsistentNaming + +namespace Fantasy.Helper +{ + /// + /// 提供网络操作相关的帮助方法。 + /// + public static partial class NetworkHelper + { + /// + /// 根据字符串获取一个IPEndPoint + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IPEndPoint GetIPEndPoint(string address) + { + try + { + var addressSplit = address.Split(':'); + if (addressSplit.Length != 2) + { + throw new FormatException("Invalid format"); + } + + var ipString = addressSplit[0]; + var portString = addressSplit[1]; + + if (!IPAddress.TryParse(ipString, out var ipAddress)) + { + throw new FormatException("Invalid IP address"); + } + + if (!int.TryParse(portString, out var port) || port < 0 || port > 65535) + { + throw new FormatException("Invalid port number"); + } + + return new IPEndPoint(ipAddress, port); + } + catch (Exception e) + { + Log.Error($"Error parsing IP and Port:{e.Message}"); + return null; + } + } + + /// + /// 克隆一个IPEndPoint + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IPEndPoint Clone(this EndPoint endPoint) + { + var ip = (IPEndPoint)endPoint; + return new IPEndPoint(ip.Address, ip.Port); + } + + /// + /// 比较两个IPEndPoint是否相等 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IPEndPointEquals(this EndPoint endPoint, IPEndPoint ipEndPoint) + { + var ip = (IPEndPoint)endPoint; + return ip.Address.Equals(ipEndPoint.Address) && ip.Port == ipEndPoint.Port; + } + + /// + /// 比较两个IPEndPoint是否相等 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IPEndPointEquals(this IPEndPoint endPoint, IPEndPoint ipEndPoint) + { + return endPoint.Address.Equals(ipEndPoint.Address) && endPoint.Port == ipEndPoint.Port; + } +#if !FANTASY_WEBGL + /// + /// 将SocketAddress写入到Byte[]中 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void SocketAddressToByte(this SocketAddress socketAddress, byte[] buffer, int offset) + { + if (socketAddress == null) + { + throw new ArgumentNullException(nameof(socketAddress), "The SocketAddress cannot be null."); + } + + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer), "The buffer cannot be null."); + } + + if (buffer.Length < socketAddress.Size + offset + 8) + { + throw new ArgumentException("The buffer length is insufficient. It must be at least the size of the SocketAddress plus 8 bytes.", nameof(buffer)); + } + + var span = buffer.AsSpan(offset); + var addressFamilyValue = (int)socketAddress.Family; + var socketAddressSizeValue = socketAddress.Size; + + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(span), addressFamilyValue); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), 4), socketAddressSizeValue); + + for (var i = 0; i < socketAddress.Size - 2; i++) + { + Unsafe.Add(ref MemoryMarshal.GetReference(span), 8 + i) = socketAddress[i + 2]; + } + } + + /// + /// 将byre[]转换为SocketAddress + /// + /// + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ByteToSocketAddress(byte[] buffer, int offset, out SocketAddress socketAddress) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer), "The buffer cannot be null."); + } + + if (buffer.Length < 8) + { + throw new ArgumentException("Buffer length is insufficient. It must be at least 8 bytes.", nameof(buffer)); + } + + try + { + var span = buffer.AsSpan(offset); + ref var spanRef = ref MemoryMarshal.GetReference(span); + + var addressFamily = (AddressFamily)Unsafe.ReadUnaligned(ref spanRef); + var socketAddressSize = Unsafe.ReadUnaligned(ref Unsafe.Add(ref spanRef, 4)); + + if (buffer.Length < offset + 8 + socketAddressSize) + { + throw new ArgumentException("Buffer length is insufficient for the given SocketAddress size.", nameof(buffer)); + } + + socketAddress = new SocketAddress(addressFamily, socketAddressSize); + + for (var i = 0; i < socketAddressSize - 2; i++) + { + socketAddress[i + 2] = Unsafe.Add(ref spanRef, 8 + i); + } + + return 8 + offset + socketAddressSize; + } + catch (ArgumentNullException ex) + { + throw new InvalidOperationException("An argument provided to the method is null.", ex); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException("An argument provided to the method is invalid.", ex); + } + catch (Exception ex) + { + throw new InvalidOperationException("An unexpected error occurred while processing the buffer.", ex); + } + } + + /// + /// 将ReadOnlyMemory转换为SocketAddress + /// + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ByteToSocketAddress(ReadOnlyMemory buffer, int offset, out SocketAddress socketAddress) + { + if (buffer.Length < 8) + { + throw new ArgumentException("Buffer length is insufficient. It must be at least 8 bytes.", nameof(buffer)); + } + + try + { + var span = buffer.Span.Slice(offset); + ref var spanRef = ref MemoryMarshal.GetReference(span); + + var addressFamily = (AddressFamily)Unsafe.ReadUnaligned(ref spanRef); + var socketAddressSize = Unsafe.ReadUnaligned(ref Unsafe.Add(ref spanRef, 4)); + + if (buffer.Length < offset + 8 + socketAddressSize) + { + throw new ArgumentException("Buffer length is insufficient for the given SocketAddress size.", nameof(buffer)); + } + + socketAddress = new SocketAddress(addressFamily, socketAddressSize); + + for (var i = 0; i < socketAddressSize - 2; i++) + { + socketAddress[i + 2] = Unsafe.Add(ref spanRef, 8 + i); + } + + return 8 + offset + socketAddressSize; + } + catch (ArgumentNullException ex) + { + throw new InvalidOperationException("An argument provided to the method is null.", ex); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException("An argument provided to the method is invalid.", ex); + } + catch (Exception ex) + { + throw new InvalidOperationException("An unexpected error occurred while processing the buffer.", ex); + } + } + + /// + /// 根据SocketAddress获得IPEndPoint + /// + /// + /// + /// + public static unsafe IPEndPoint GetIPEndPoint(this SocketAddress socketAddress) + { + switch (socketAddress.Family) + { + case AddressFamily.InterNetwork: + { + var ipBytes = new byte[4]; + for (var i = 0; i < 4; i++) + { + ipBytes[i] = socketAddress[4 + i]; + } + var port = (socketAddress[2] << 8) + socketAddress[3]; + var ip = new IPAddress(ipBytes); + return new IPEndPoint(ip, port); + } + case AddressFamily.InterNetworkV6: + { + var ipBytes = new byte[16]; + Span socketAddressSpan = stackalloc byte[28]; + + for (var i = 0; i < 28; i++) + { + socketAddressSpan[i] = socketAddress[i]; + } + + ref var spanRef = ref MemoryMarshal.GetReference(socketAddressSpan); + + for (var i = 0; i < 16; i++) + { + ipBytes[i] = Unsafe.Add(ref spanRef, 8 + i); + } + + var port = (Unsafe.Add(ref spanRef, 2) << 8) + Unsafe.Add(ref spanRef, 3); + var scopeId = Unsafe.ReadUnaligned(ref Unsafe.Add(ref spanRef, 24)); + var ip = new IPAddress(ipBytes, scopeId); + return new IPEndPoint(ip, port); + } + default: + { + throw new NotSupportedException("Address family not supported."); + } + } + } +#endif + /// + /// 获取本机所有网络适配器的IP地址。 + /// + /// IP地址数组。 + public static string[] GetAddressIPs() + { + var list = new List(); + foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces()) + { + // 仅考虑以太网类型的网络适配器 + if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet) + { + continue; + } + + foreach (var add in networkInterface.GetIPProperties().UnicastAddresses) + { + list.Add(add.Address.ToString()); + } + } + + return list.ToArray(); + } + + /// + /// 将主机名和端口号转换为 实例。 + /// + /// 主机名。 + /// 端口号。 + /// 实例。 + public static IPEndPoint ToIPEndPoint(string host, int port) + { + return new IPEndPoint(IPAddress.Parse(host), port); + } + + /// + /// 将地址字符串转换为 实例。 + /// + /// 地址字符串,格式为 "主机名:端口号"。 + /// 实例。 + public static IPEndPoint ToIPEndPoint(string address) + { + var index = address.LastIndexOf(':'); + var host = address.Substring(0, index); + var p = address.Substring(index + 1); + var port = int.Parse(p); + return ToIPEndPoint(host, port); + } + + /// + /// 将 实例转换为字符串表示形式。 + /// + /// 实例。 + /// 表示 的字符串。 + public static string IPEndPointToStr(this IPEndPoint self) + { + return $"{self.Address}:{self.Port}"; + } + + /// + /// 针对 Windows 平台设置UDP连接重置选项。 + /// + /// 要设置选项的 实例。 + public static void SetSioUdpConnReset(this Socket socket) + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + /* + 目前这个问题只有Windows下才会出现。 + 服务器端在发送数据时捕获到了一个异常, + 这个异常导致原因应该是远程客户端的UDP监听已停止导致数据发送出错。 + 按理说UDP是无连接的,报这个异常是不合理的 + 这个异常让整UDP的服务监听也停止了。 + 这样就因为一个客户端的数据发送无法到达而导致了服务挂了,所有客户端都无法与服务器通信了 + 想详细了解看下https://blog.csdn.net/sunzhen6251/article/details/124168805*/ + const uint IOC_IN = 0x80000000; + const uint IOC_VENDOR = 0x18000000; + const int SIO_UDP_CONNRESET = unchecked((int) (IOC_IN | IOC_VENDOR | 12)); + + socket.IOControl(SIO_UDP_CONNRESET, new[] {Convert.ToByte(false)}, null); + } + + /// + /// 将 Socket 缓冲区大小设置为操作系统限制。 + /// + /// 要设置缓冲区大小的 Socket。 + public static void SetSocketBufferToOsLimit(this Socket socket) + { + socket.SetReceiveBufferToOSLimit(); + socket.SetSendBufferToOSLimit(); + } + + /// + /// 将 Socket 接收缓冲区大小设置为操作系统限制。 + /// 尝试增加接收缓冲区大小的次数 = 默认 + 最大增加 100 MB。 + /// + /// 要设置接收缓冲区大小的 Socket。 + /// 每次增加的步长大小。 + /// 尝试增加缓冲区大小的次数。 + public static void SetReceiveBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000) + { + // setting a too large size throws a socket exception. + // so let's keep increasing until we encounter it. + for (int i = 0; i < attempts; ++i) + { + // increase in 1 KB steps + try + { + socket.ReceiveBufferSize += stepSize; + } + catch (SocketException) + { + break; + } + } + } + + /// + /// 将 Socket 发送缓冲区大小设置为操作系统限制。 + /// 尝试增加发送缓冲区大小的次数 = 默认 + 最大增加 100 MB。 + /// + /// 要设置发送缓冲区大小的 Socket。 + /// 每次增加的步长大小。 + /// 尝试增加缓冲区大小的次数。 + public static void SetSendBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000) + { + // setting a too large size throws a socket exception. + // so let's keep increasing until we encounter it. + for (var i = 0; i < attempts; ++i) + { + // increase in 1 KB steps + try + { + socket.SendBufferSize += stepSize; + } + catch (SocketException) + { + break; + } + } + } +#endif + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs.meta new file mode 100644 index 0000000..b0cb04c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/NetworkHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6520aae6468437045b7bf13649b53210 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs b/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs new file mode 100644 index 0000000..b07ffb8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs @@ -0,0 +1,415 @@ +#if FANTASY_NET || !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +namespace Fantasy.Helper +{ + /// + /// 随机数操作助手类,提供各种随机数生成和操作方法。 + /// + public static partial class RandomHelper + { + [ThreadStatic] + private static Random _random; + + /// + /// 生成一个随机的无符号 64 位整数。 + /// + /// 无符号 64 位整数。 + public static ulong RandUInt64() + { + var byte8 = new FixedBytes8().AsSpan(); + var random = _random ??= new Random(); + random.NextBytes(byte8); + return BitConverter.ToUInt64(byte8); + } + + /// + /// 生成一个随机的 64 位整数。 + /// + /// 64 位整数。 + public static long RandInt64() + { + var byte8 = new FixedBytes8().AsSpan(); + var random = _random ??= new Random(); + random.NextBytes(byte8); + return BitConverter.ToInt64(byte8); + } + + /// + /// 生成一个随机的无符号 32 位整数。 + /// + /// 无符号 32 位整数。 + public static uint RandUInt32() + { + var random = _random ??= new Random(); + return (uint) random.Next(); + } + + /// + /// 生成一个随机的无符号 16 位整数。 + /// + /// 无符号 16 位整数。 + public static ushort RandUInt16() + { + var byte2 = new FixedBytes2().AsSpan(); + var random = _random ??= new Random(); + random.NextBytes(byte2); + return BitConverter.ToUInt16(byte2); + } + + /// + /// 在指定范围内生成一个随机整数(包含下限,不包含上限)。 + /// + /// 下限。 + /// 上限。 + /// 生成的随机整数。 + public static int RandomNumber(int lower, int upper) + { + var random = _random ??= new Random(); + return random.Next(lower, upper); + } + + /// + /// 生成一个随机的布尔值。 + /// + /// 随机的布尔值。 + public static bool RandomBool() + { + var random = _random ??= new Random(); + return (random.Next() & 1) == 0; + } + + /// + /// 从数组中随机选择一个元素。 + /// + /// 数组元素的类型。 + /// 要选择的数组。 + /// 随机选择的数组元素。 + public static T RandomArray(this T[] array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 从列表中随机选择一个元素。 + /// + /// 列表元素的类型。 + /// 要选择的列表。 + /// 随机选择的列表元素。 + public static T RandomArray(this List array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 打乱列表中元素的顺序。 + /// + /// 列表元素的类型。 + /// 要打乱顺序的列表。 + public static void BreakRank(List arr) + { + if (arr == null || arr.Count < 2) + { + return; + } + + var random = _random ??= new Random(); + for (var i = 0; i < arr.Count / 2; i++) + { + var index = random.Next(0, arr.Count); + (arr[index], arr[arr.Count - index - 1]) = (arr[arr.Count - index - 1], arr[index]); + } + } + + /// + /// 生成一个介于 0 和 1 之间的随机单精度浮点数。 + /// + /// 随机单精度浮点数。 + public static float RandFloat01() + { + var random = _random ??= new Random(); + var value = random.NextDouble(); + return (float) value; + } + + private static int Rand(int n) + { + var rd = new Random(); + // 注意,返回值是左闭右开,所以maxValue要加1 + return rd.Next(1, n + 1); + } + + /// + /// 根据权重随机选择一个索引。 + /// + /// 权重数组,每个元素表示相应索引的权重。 + /// 随机选择的索引值。 + public static int RandomByWeight(int[] weights) + { + var sum = weights.Sum(); + var numberRand = Rand(sum); + var sumTemp = 0; + for (var i = 0; i < weights.Length; i++) + { + sumTemp += weights[i]; + if (numberRand <= sumTemp) + { + return i; + } + } + + return -1; + } + + /// + /// 根据固定概率随机选择一个索引,即某个数值上限内随机多少次。 + /// + /// 概率数组,每个元素表示相应索引的概率。 + /// 随机选择的索引值。 + public static int RandomByFixedProbability(int[] args) + { + var random = _random ??= new Random(); + var argCount = args.Length; + var sum = args.Sum(); + var value = random.NextDouble() * sum; + while (sum > value) + { + sum -= args[argCount - 1]; + argCount--; + } + + return argCount; + } + + /// + /// 返回随机数。 + /// + /// 是否包含负数。 + /// 返回一个随机的单精度浮点数。 + public static float NextFloat(bool containNegative = false) + { + var random = _random ??= new Random(); + float f; + var buffer = new FixedBytes4().AsSpan(); + if (containNegative) + { + do + { + random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer); + } while ((f >= float.MinValue && f < float.MaxValue) == false); + + return f; + } + + do + { + random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer); + } while ((f >= 0 && f < float.MaxValue) == false); + + return f; + } + + /// + /// 返回一个小于所指定最大值的非负随机数。 + /// + /// 要生成的随机数的上限(随机数不能取该上限值)。 maxValue 必须大于或等于零。 + /// 大于等于零且小于 maxValue 的单精度浮点数,即:返回值的范围通常包括零但不包括 maxValue。 不过,如果 maxValue 等于零,则返回 maxValue。 + public static float NextFloat(float maxValue) + { + if (maxValue.Equals(0)) + { + return maxValue; + } + + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException("“maxValue”必须大于 0。", "maxValue"); + } + + var random = _random ??= new Random(); + float f; + var buffer = new FixedBytes4().AsSpan(); + + do + { + random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer); + } while ((f >= 0 && f < maxValue) == false); + + return f; + } + + /// + /// 返回一个指定范围内的随机数。 + /// + /// 返回的随机数的下界(随机数可取该下界值)。 + /// 返回的随机数的上界(随机数不能取该上界值)。 maxValue 必须大于或等于 minValue。 + /// 一个大于等于 minValue 且小于 maxValue 的单精度浮点数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue。 + public static float NextFloat(float minValue, float maxValue) + { + if (minValue.Equals(maxValue)) + { + return minValue; + } + + if (minValue > maxValue) + { + throw new ArgumentOutOfRangeException("“minValue”不能大于 maxValue。", "minValue"); + } + + var random = _random ??= new Random(); + var buffer = new FixedBytes4().AsSpan(); + float f; + + do + { + random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer); + } while ((f >= minValue && f < maxValue) == false); + + return f; + } + + /// + /// 在指定的矩形区域内随机生成一个二维向量位置。 + /// + /// X轴最小值。 + /// X轴最大值。 + /// Y轴最小值。 + /// Y轴最大值。 + /// 随机生成的二维向量位置。 + public static Vector2 NextVector2(float minX, float maxX, float minY, float maxY) + { + return new Vector2(NextFloat(minX, maxX), NextFloat(minY, maxY)); + } + + /// + /// 生成指定长度的随机数字代码。 + /// + /// 数字代码的长度。 + /// 生成的随机数字代码。 + public static string RandomNumberCode(int len = 6) + { + int num = 0; + for (int i = 0; i < len; i++) + { + int number = RandomNumber(0, 10); + num = num * 10 + number; + } + + return num.ToString(); + } + } + + #region FixedBytes + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes1 + { + private byte _e0; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes2 + { + private FixedBytes1 _e0; + private FixedBytes1 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes4 + { + private FixedBytes2 _e0; + private FixedBytes2 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes8 + { + private FixedBytes4 _e0; + private FixedBytes4 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes16 + { + private FixedBytes8 _e0; + private FixedBytes8 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes32 + { + private FixedBytes16 _e0; + private FixedBytes16 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes64 + { + private FixedBytes32 _e0; + private FixedBytes32 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes128 + { + private FixedBytes64 _e0; + private FixedBytes64 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes256 + { + private FixedBytes128 _e0; + private FixedBytes128 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes512 + { + private FixedBytes256 _e0; + private FixedBytes256 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + [StructLayout(LayoutKind.Sequential)] + public struct FixedBytes1024 + { + private FixedBytes512 _e0; + private FixedBytes512 _e1; + + public Span AsSpan() => MemoryMarshal.CreateSpan(ref Unsafe.As(ref Unsafe.AsRef(in this)), Unsafe.SizeOf()); + } + + #endregion +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs.meta new file mode 100644 index 0000000..d68b242 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/RandomHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aca395b773d7b5146b794abd3728e360 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs b/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs new file mode 100644 index 0000000..0820acf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs @@ -0,0 +1,295 @@ +#if FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace Fantasy.Helper +{ + /// + /// 随机数操作助手类,提供各种随机数生成和操作方法。 + /// + public static partial class RandomHelper + { + private static readonly Random Random = new Random(); + private static readonly byte[] Byte8 = new byte[8]; + private static readonly byte[] Byte2 = new byte[2]; + + /// + /// 生成一个随机的无符号 64 位整数。 + /// + /// 无符号 64 位整数。 + public static ulong RandUInt64() + { + Random.NextBytes(Byte8); + return BitConverter.ToUInt64(Byte8, 0); + } + + /// + /// 生成一个随机的 64 位整数。 + /// + /// 64 位整数。 + public static long RandInt64() + { + Random.NextBytes(Byte8); + return BitConverter.ToInt64(Byte8, 0); + } + + /// + /// 生成一个随机的无符号 32 位整数。 + /// + /// 无符号 32 位整数。 + public static uint RandUInt32() + { + return (uint) Random.Next(); + } + + /// + /// 生成一个随机的无符号 16 位整数。 + /// + /// 无符号 16 位整数。 + public static ushort RandUInt16() + { + Random.NextBytes(Byte2); + return BitConverter.ToUInt16(Byte2, 0); + } + + /// + /// 在指定范围内生成一个随机整数(包含下限,不包含上限)。 + /// + /// 下限。 + /// 上限。 + /// 生成的随机整数。 + public static int RandomNumber(int lower, int upper) + { + return Random.Next(lower, upper); + } + + /// + /// 生成一个随机的布尔值。 + /// + /// 随机的布尔值。 + public static bool RandomBool() + { + return Random.Next(2) == 0; + } + + /// + /// 从数组中随机选择一个元素。 + /// + /// 数组元素的类型。 + /// 要选择的数组。 + /// 随机选择的数组元素。 + public static T RandomArray(this T[] array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 从列表中随机选择一个元素。 + /// + /// 列表元素的类型。 + /// 要选择的列表。 + /// 随机选择的列表元素。 + public static T RandomArray(this List array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 打乱列表中元素的顺序。 + /// + /// 列表元素的类型。 + /// 要打乱顺序的列表。 + public static void BreakRank(List arr) + { + if (arr == null || arr.Count < 2) + { + return; + } + + for (var i = 0; i < arr.Count / 2; i++) + { + var index = Random.Next(0, arr.Count); + (arr[index], arr[arr.Count - index - 1]) = (arr[arr.Count - index - 1], arr[index]); + } + } + + /// + /// 生成一个介于 0 和 1 之间的随机单精度浮点数。 + /// + /// 随机单精度浮点数。 + public static float RandFloat01() + { + var value = Random.NextDouble(); + return (float) value; + } + + private static int Rand(int n) + { + var rd = new Random(); + // 注意,返回值是左闭右开,所以maxValue要加1 + return rd.Next(1, n + 1); + } + + /// + /// 根据权重随机选择一个索引。 + /// + /// 权重数组,每个元素表示相应索引的权重。 + /// 随机选择的索引值。 + public static int RandomByWeight(int[] weights) + { + var sum = weights.Sum(); + var numberRand = Rand(sum); + var sumTemp = 0; + for (var i = 0; i < weights.Length; i++) + { + sumTemp += weights[i]; + if (numberRand <= sumTemp) + { + return i; + } + } + + return -1; + } + + /// + /// 根据固定概率随机选择一个索引,即某个数值上限内随机多少次。 + /// + /// 概率数组,每个元素表示相应索引的概率。 + /// 随机选择的索引值。 + public static int RandomByFixedProbability(int[] args) + { + var argCount = args.Length; + var sum = args.Sum(); + var random = Random.NextDouble() * sum; + while (sum > random) + { + sum -= args[argCount - 1]; + argCount--; + } + + return argCount; + } + + /// + /// 返回随机数。 + /// + /// 是否包含负数。 + /// 返回一个随机的单精度浮点数。 + public static float NextFloat(bool containNegative = false) + { + float f; + var buffer = new byte[4]; + if (containNegative) + { + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= float.MinValue && f < float.MaxValue) == false); + + return f; + } + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= 0 && f < float.MaxValue) == false); + + return f; + } + + /// + /// 返回一个小于所指定最大值的非负随机数。 + /// + /// 要生成的随机数的上限(随机数不能取该上限值)。 maxValue 必须大于或等于零。 + /// 大于等于零且小于 maxValue 的单精度浮点数,即:返回值的范围通常包括零但不包括 maxValue。 不过,如果 maxValue 等于零,则返回 maxValue。 + public static float NextFloat(float maxValue) + { + if (maxValue.Equals(0)) + { + return maxValue; + } + + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException("“maxValue”必须大于 0。", "maxValue"); + } + + float f; + var buffer = new byte[4]; + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= 0 && f < maxValue) == false); + + return f; + } + + /// + /// 返回一个指定范围内的随机数。 + /// + /// 返回的随机数的下界(随机数可取该下界值)。 + /// 返回的随机数的上界(随机数不能取该上界值)。 maxValue 必须大于或等于 minValue。 + /// 一个大于等于 minValue 且小于 maxValue 的单精度浮点数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue。 + public static float NextFloat(float minValue, float maxValue) + { + if (minValue.Equals(maxValue)) + { + return minValue; + } + + if (minValue > maxValue) + { + throw new ArgumentOutOfRangeException("“minValue”不能大于 maxValue。", "minValue"); + } + + float f; + var buffer = new byte[4]; + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= minValue && f < maxValue) == false); + + return f; + } + + /// + /// 在指定的矩形区域内随机生成一个二维向量位置。 + /// + /// X轴最小值。 + /// X轴最大值。 + /// Y轴最小值。 + /// Y轴最大值。 + /// 随机生成的二维向量位置。 + public static Vector2 NextVector2(float minX, float maxX, float minY, float maxY) + { + return new Vector2(NextFloat(minX, maxX), NextFloat(minY, maxY)); + } + + /// + /// 生成指定长度的随机数字代码。 + /// + /// 数字代码的长度。 + /// 生成的随机数字代码。 + public static string RandomNumberCode(int len = 6) + { + int num = 0; + for (int i = 0; i < len; i++) + { + int number = RandomNumber(0, 10); + num = num * 10 + number; + } + + return num.ToString(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs.meta b/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs.meta new file mode 100644 index 0000000..d214ded --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/RandomHelperWebgl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6eac1bd84313c7041b098a0e251009c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs b/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs new file mode 100644 index 0000000..15027c5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs @@ -0,0 +1,74 @@ +#if !FANTASY_WEBGL +using System.Net; +using System.Net.Sockets; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Helper +{ + /// + /// Socket帮助类 + /// + public static partial class SocketHelper + { + // always pass the same IPEndPointNonAlloc instead of allocating a new + // one each time. + // + // use IPEndPointNonAlloc.temp to get the latest SocketAdddress written + // by ReceiveFrom_Internal! + // + // IMPORTANT: .temp will be overwritten in next call! + // hash or manually copy it if you need to store it, e.g. + // when adding a new connection. + public static int ReceiveFrom_NonAlloc( + this Socket socket, + byte[] buffer, + int offset, + int size, + SocketFlags socketFlags, + EndPoint remoteEndPoint) + { + // call ReceiveFrom with IPEndPointNonAlloc. + // need to wrap this in ReceiveFrom_NonAlloc because it's not + // obvious that IPEndPointNonAlloc.Create does NOT create a new + // IPEndPoint. it saves the result in IPEndPointNonAlloc.temp! +#if FANTASY_UNITY + EndPoint casted = remoteEndPoint; + return socket.ReceiveFrom(buffer, offset, size, socketFlags, ref casted); +#else + return socket.ReceiveFrom(buffer, offset, size, socketFlags, ref remoteEndPoint); +#endif + } + + // same as above, different parameters + public static int ReceiveFrom_NonAlloc(this Socket socket, byte[] buffer, ref EndPoint remoteEndPoint) + { +#if UNITY + EndPoint casted = remoteEndPoint; + return socket.ReceiveFrom(buffer, ref casted); +#else + return socket.ReceiveFrom(buffer, ref remoteEndPoint); +#endif + + } + + // SendTo allocates too: + // https://github.com/mono/mono/blob/f74eed4b09790a0929889ad7fc2cf96c9b6e3757/mcs/class/System/System.Net.Sockets/Socket.cs#L2240 + // -> the allocation is in EndPoint.Serialize() + // NOTE: technically this function isn't necessary. + // could just pass IPEndPointNonAlloc. + // still good for strong typing. + //public static int SendTo_NonAlloc( + // this Socket socket, + // byte[] buffer, + // int offset, + // int size, + // SocketFlags socketFlags, + // IPEndPointNonAlloc remoteEndPoint) + //{ + // EndPoint casted = remoteEndPoint; + // return socket.SendTo(buffer, offset, size, socketFlags, casted); + //} + } +} +#endif + + diff --git a/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs.meta new file mode 100644 index 0000000..a717a9e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/SocketHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bcada06adbfbe1741af616c849ac895a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs b/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs new file mode 100644 index 0000000..b0eb60a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs @@ -0,0 +1,83 @@ +using System; +#if FANTASY_UNITY +using UnityEngine; +#endif + +namespace Fantasy.Helper +{ + /// + /// 提供与时间相关的帮助方法。 + /// + public static partial class TimeHelper + { + /// + /// 一小时的毫秒值。 + /// + public const long Hour = 3600000; + /// + /// 一分钟的毫秒值。 + /// + public const long Minute = 60000; + /// + /// 一天的毫秒值。 + /// + public const long OneDay = 86400000; + // 1970年1月1日的Ticks + private const long Epoch = 621355968000000000L; + /// + /// 获取当前时间的毫秒数,从1970年1月1日开始计算。 + /// + public static long Now => (DateTime.UtcNow.Ticks - Epoch) / 10000; +#if FANTASY_UNITY || FANTASY_CONSOLE + /// + /// 与服务器时间的偏差。 + /// + public static long TimeDiff; + /// + /// 获取当前服务器时间的毫秒数,加上与服务器时间的偏差。 + /// + public static long ServerNow => Now + TimeDiff; +#if FANTASY_UNITY + /// + /// 获取当前Unity运行的总时间的毫秒数。 + /// + public static long UnityNow => (long) (Time.time * 1000); +#endif +#endif + /// + /// 根据时间获取时间戳 + /// + public static long Transition(DateTime dateTime) + { + return (dateTime.ToUniversalTime().Ticks - Epoch) / 10000; + } + + /// + /// 根据时间获取 时间戳 + /// + public static long TransitionToSeconds(DateTime dateTime) + { + return (dateTime.ToUniversalTime().Ticks - Epoch) / 10000000; + } + + /// + /// 将毫秒数转换为日期时间。 + /// + /// 要转换的毫秒数。 + /// 转换后的日期时间。 + public static DateTime Transition(this long timeStamp) + { + return new DateTime(Epoch + timeStamp * 10000, DateTimeKind.Utc).ToUniversalTime(); + } + + /// + /// 将毫秒数转换为本地时间的日期时间。 + /// + /// 要转换的毫秒数。 + /// 转换后的本地时间的日期时间。 + public static DateTime TransitionLocal(this long timeStamp) + { + return new DateTime(Epoch + timeStamp * 10000, DateTimeKind.Utc).ToLocalTime(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs.meta new file mode 100644 index 0000000..6b837c4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/TimeHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6aefd86e552e1243947b54cbdb7b952 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/UnityWebRequest.meta b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest.meta new file mode 100644 index 0000000..f185852 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 004b04d4a1b3c1540a49d4d136af8725 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs new file mode 100644 index 0000000..dbc0334 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs @@ -0,0 +1,244 @@ +#if FANTASY_UNITY +using System; +using Fantasy.Async; +using UnityEngine; +using UnityEngine.Networking; + +namespace Fantasy.Unity +{ + /// + /// UnityWebRequest的帮助类 + /// + public static class UnityWebRequestHelper + { + /// + /// 获取一个文本 + /// + /// + /// + /// + public static FTask GetText(string url, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequest.Get(url); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var text = unityWebRequest.downloadHandler.text; + task.SetResult(text); + } + else + { + Log.Error(unityWebRequest.error); + task.SetResult(null); + } + }; + + return task; + } + + /// + /// 获取一个Sprite + /// + /// + /// + /// + public static FTask GetSprite(string url, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequestTexture.GetTexture(Uri.EscapeUriString(url)); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var texture = DownloadHandlerTexture.GetContent(unityWebRequest); + var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 5, 1f); + task.SetResult(sprite); + } + else + { + Log.Error(unityWebRequest.error); + task.SetResult(null); + } + }; + + return task; + } + + /// + /// 获取一个Texture + /// + /// + /// + /// + public static FTask GetTexture(string url, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequestTexture.GetTexture(Uri.EscapeUriString(url)); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var texture = DownloadHandlerTexture.GetContent(unityWebRequest); + task.SetResult(texture); + } + else + { + Log.Error(unityWebRequest.error); + task.SetResult(null); + } + }; + + return task; + } + + /// + /// 获取Bytes + /// + /// + /// + /// + public static FTask GetBytes(string url, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequest.Get(url); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var bytes = unityWebRequest.downloadHandler.data; + task.SetResult(bytes); + } + else + { + Log.Error(unityWebRequest.error); + task.SetResult(null); + } + }; + + return task; + } + + /// + /// 获取AssetBundle + /// + /// + /// + /// + public static FTask GetAssetBundle(string url, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequestAssetBundle.GetAssetBundle(Uri.EscapeUriString(url)); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var assetBundle = DownloadHandlerAssetBundle.GetContent(unityWebRequest); + task.SetResult(assetBundle); + return; + } + + Log.Error(unityWebRequest.error); + task.SetResult(null); + }; + + return task; + } + + /// + /// 获取AudioClip + /// + /// + /// + /// + /// + public static FTask GetAudioClip(string url, AudioType audioType, FCancellationToken cancellationToken = null) + { + var task = FTask.Create(false); + var unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(Uri.EscapeUriString(url), audioType); + var unityWebRequestAsyncOperation = unityWebRequest.SendWebRequest(); + + if (cancellationToken != null) + { + cancellationToken.Add(() => + { + unityWebRequest.Abort(); + task.SetResult(null); + }); + } + + unityWebRequestAsyncOperation.completed += operation => + { + if (unityWebRequest.result == UnityWebRequest.Result.Success) + { + var audioClip = DownloadHandlerAudioClip.GetContent(unityWebRequest); + task.SetResult(audioClip); + } + else + { + Log.Error(unityWebRequest.error); + task.SetResult(null); + } + }; + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs.meta new file mode 100644 index 0000000..2dd6b76 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/UnityWebRequest/UnityWebRequestHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f9abae728230e6d4ba028a29c1634054 +timeCreated: 1726022012 \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs b/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs new file mode 100644 index 0000000..822db06 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Fantasy.Helper +{ + /// + /// WebSocket帮助类 + /// + public static partial class WebSocketHelper + { + /// + /// 根据字符串获取WebSocket的连接地址 + /// + /// 目标服务器地址格式为:127.0.0.1:2000 + /// 目标服务器是否为加密连接也就是https + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string GetWebSocketAddress(string address, bool isHttps) + { + var addressSplit = address.Split(':'); + if (addressSplit.Length != 2) + { + throw new FormatException("Invalid format"); + } + + var ipString = addressSplit[0]; + var portString = addressSplit[1]; + + if (!int.TryParse(portString, out var port) || port < 0 || port > 65535) + { + throw new FormatException("Invalid port number"); + } + + return isHttps ? $"wss://{ipString}:{portString}" : $"ws://{ipString}:{portString}"; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs.meta b/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs.meta new file mode 100644 index 0000000..38627ca --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/WebSocketHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fba2f038afaeea64ba843bc67387ee2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs b/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs new file mode 100644 index 0000000..a1a5aca --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs @@ -0,0 +1,24 @@ +using System.Runtime.InteropServices; + +namespace Fantasy.Helper +{ + /// + /// 精度设置 + /// + public static partial class WinPeriod + { + // 一般默认的精度不止1毫秒(不同操作系统有所不同),需要调用timeBeginPeriod与timeEndPeriod来设置精度 + [DllImport("winmm")] + private static extern void timeBeginPeriod(int t); + /// + /// 针对Windows平台设置精度 + /// + public static void Initialize() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + timeBeginPeriod(1); + } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs.meta b/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs.meta new file mode 100644 index 0000000..1adb67d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Helper/WinPeriod.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bddb55b775a33464288227282d42a7b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory.meta b/Runtime/CoreRuntime/Core/IdFactory.meta new file mode 100644 index 0000000..d4b40aa --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fae938f6a42bff6489ed0216bdc333b1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Default.meta b/Runtime/CoreRuntime/Core/IdFactory/Default.meta new file mode 100644 index 0000000..d0660d4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Default.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f1e2d81594277ad4f865497dd7569ea0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs b/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs new file mode 100644 index 0000000..ef30b18 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs @@ -0,0 +1,136 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个唯一实体的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct EntityIdStruct + { + // EntityId:39 + 16 + 18 = 64 + // +-------------------+-----------------------------+------------------------------------+ + // | time(30) 最大34年 | SceneId(16) 最多65535个Scene | sequence(18) 每秒每个进程能生产262143个 + // +-------------------+-----------------------------+------------------------------------+ + public uint Time { get; set; } + public uint SceneId { get; set; } + public uint Sequence { get; set; } + + public const uint MaskSequence = 0x3FFFF; + public const uint MaskSceneId = 0xFFFF; + public const uint MaskTime = 0x3FFFFFFF; + + /// + /// WorldEntityIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过1073741823 + /// sceneId不能超过65535 + /// sequence不能超过262143 + public EntityIdStruct(uint time, uint sceneId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + Sequence = sequence; + } + + public static implicit operator long(EntityIdStruct entityIdStruct) + { + ulong result = 0; + result |= entityIdStruct.Sequence; + result |= (ulong)entityIdStruct.SceneId << 18; + result |= (ulong)entityIdStruct.Time << 34; + return (long)result; + } + + public static implicit operator EntityIdStruct(long entityId) + { + var result = (ulong) entityId; + var entityIdStruct = new EntityIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 18; + entityIdStruct.SceneId = (uint)(result & MaskSceneId); + result >>= 16; + entityIdStruct.Time = (uint)(result & MaskTime); + return entityIdStruct; + } + } + + public sealed class EntityIdFactory : IEntityIdFactory + { + private readonly ushort _sceneId; + + private uint _lastTime; + private uint _lastSequence; + private static readonly long Epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + private static readonly long EpochThisYear = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000 - Epoch1970; + + private EntityIdFactory() { } + + public EntityIdFactory(uint sceneId) + { + switch (sceneId) + { + case > 65535: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + default: + { + _sceneId = (ushort)sceneId; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - EpochThisYear) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > EntityIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new EntityIdStruct(time, _sceneId, _lastSequence); + } + } + } + + public sealed class EntityIdFactoryTool : IIdFactoryTool + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetTime(ref long entityId) + { + var result = (ulong)entityId >> 34; + return (uint)(result & EntityIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetSceneId(ref long entityId) + { + var result = (ulong)entityId >> 18; + return (uint)(result & EntityIdStruct.MaskSceneId); + } + + public byte GetWorldId(ref long entityId) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs.meta new file mode 100644 index 0000000..063b820 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Default/EntityIdStruct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2de7631bf310474292a23a3517d1630 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs b/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs new file mode 100644 index 0000000..a5d5e10 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs @@ -0,0 +1,137 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个运行时的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct RuntimeIdStruct + { + // RuntimeId:23 + 8 + 8 + 25 = 64 + // +-------------------+-----------------------------+--------------------------------------+ + // | time(23) 最大60天 | SceneId(16) 最多65535个Scene | sequence(25) 每秒每个进程能生产33554431个 + // +-------------------+-----------------------------+--------------------------------------+ + public uint Time { get; private set; } + public uint SceneId { get; private set; } + public uint Sequence { get; private set; } + + public const uint MaskSequence = 0x1FFFFFF; + public const uint MaskSceneId = 0xFFFF; + public const uint MaskTime = 0x7FFFFF; + + /// + /// RuntimeIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过8388607 + /// sceneId不能超过65535 + /// sequence不能超过33554431 + public RuntimeIdStruct(uint time, uint sceneId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + Sequence = sequence; + } + + public static implicit operator long(RuntimeIdStruct runtimeIdStruct) + { + ulong result = runtimeIdStruct.Sequence; + result |= (ulong)runtimeIdStruct.SceneId << 25; + result |= (ulong)runtimeIdStruct.Time << 41; + return (long)result; + } + + public static implicit operator RuntimeIdStruct(long runtimeId) + { + var result = (ulong)runtimeId; + var runtimeIdStruct = new RuntimeIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 25; + runtimeIdStruct.SceneId = (byte)(result & MaskSceneId); + result >>= 16; + runtimeIdStruct.Time = (uint)(result & MaskTime); + return runtimeIdStruct; + } + } + + public sealed class RuntimeIdFactory : IRuntimeIdFactory + { + private readonly uint _sceneId; + + private uint _lastTime; + private uint _lastSequence; + private readonly long _epochNow; + private readonly long _epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + + private RuntimeIdFactory() { } + + public RuntimeIdFactory(uint sceneId) : this(TimeHelper.Now, sceneId) { } + + public RuntimeIdFactory(long epochNow, uint sceneId) + { + switch (sceneId) + { + case > 65535: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + default: + { + _sceneId = (ushort)sceneId; + _epochNow = epochNow - _epoch1970; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - _epochNow) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > RuntimeIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new RuntimeIdStruct(time, _sceneId, _lastSequence); + } + } + } + + public sealed class RuntimeIdFactoryTool : IIdFactoryTool + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetTime(ref long runtimeId) + { + var result = (ulong)runtimeId >> 41; + return (uint)(result & RuntimeIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetSceneId(ref long runtimeId) + { + var result = (ulong)runtimeId >> 25; + return (uint)(result & RuntimeIdStruct.MaskSceneId); + } + + public byte GetWorldId(ref long entityId) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs.meta new file mode 100644 index 0000000..d6548a5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Default/RuntimeIdStruct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c5799f2958e2eb4449088e44446faccf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs new file mode 100644 index 0000000..4251d53 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs @@ -0,0 +1,132 @@ +using System; +using System.Runtime.CompilerServices; +using Fantasy.Helper; +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +namespace Fantasy.IdFactory +{ + /// + /// Id生成器帮助类 + /// + public static class IdFactoryHelper + { + private static IdFactoryType _idFactoryType = IdFactoryType.World; + + /// + /// EntityId工具 + /// + public static IIdFactoryTool EntityIdTool { get; private set; } = new WorldEntityIdFactoryTool(); + + /// + /// RuntimeId工具 + /// + public static IIdFactoryTool RuntimeIdTool { get; private set; } = new WorldRuntimeIdFactoryTool(); + + /// + /// 初始化 + /// + /// + public static void Initialize(IdFactoryType idFactoryType) + { + _idFactoryType = idFactoryType; + + switch (_idFactoryType) + { + case IdFactoryType.Default: + { + EntityIdTool = new EntityIdFactoryTool(); + RuntimeIdTool = new RuntimeIdFactoryTool(); + return; + } + case IdFactoryType.World: + { + EntityIdTool = new WorldEntityIdFactoryTool(); + RuntimeIdTool = new WorldRuntimeIdFactoryTool(); + return; + } + } + } + + internal static IEntityIdFactory EntityIdFactory(uint sceneId, byte worldId) + { + switch (_idFactoryType) + { + case IdFactoryType.Default: + { + return new EntityIdFactory(sceneId); + } + case IdFactoryType.World: + { + return new WorldEntityIdFactory(sceneId, worldId); + } + default: + { + throw new NotSupportedException($"IdFactoryType {_idFactoryType} is not supported."); + } + } + } + + internal static IRuntimeIdFactory RuntimeIdFactory(long epochNow, uint sceneId, byte worldId) + { + switch (_idFactoryType) + { + case IdFactoryType.Default: + { + return new RuntimeIdFactory(sceneId); + } + case IdFactoryType.World: + { + if (epochNow == 0) + { + epochNow = TimeHelper.Now; + } + + return new WorldRuntimeIdFactory(epochNow, sceneId, worldId); + } + default: + { + throw new NotSupportedException($"IdFactoryType {_idFactoryType} is not supported."); + } + } + } + + internal static long EntityId(uint time, uint sceneId, byte wordId, uint sequence) + { + switch (_idFactoryType) + { + case IdFactoryType.Default: + { + return new EntityIdStruct(time, sceneId, sequence); + } + case IdFactoryType.World: + { + return new WorldEntityIdStruct(time, sceneId, wordId, sequence); + } + default: + { + throw new NotSupportedException($"IdFactoryType {_idFactoryType} is not supported."); + } + } + } + + internal static long RuntimeId(uint time, uint sceneId, byte wordId, uint sequence) + { + switch (_idFactoryType) + { + case IdFactoryType.Default: + { + return new RuntimeIdStruct(time, sceneId, sequence); + } + case IdFactoryType.World: + { + return new WorldRuntimeIdStruct(time, sceneId, wordId, sequence); + } + default: + { + throw new NotSupportedException($"IdFactoryType {_idFactoryType} is not supported."); + } + } + } + } +} + diff --git a/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs.meta new file mode 100644 index 0000000..171b2aa --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76bc4dca5ba52e448b782eb807fea8d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs new file mode 100644 index 0000000..d465b5b --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs @@ -0,0 +1,23 @@ +namespace Fantasy.IdFactory +{ + /// + /// ID生成器规则 + /// + public enum IdFactoryType + { + /// + /// 空。 + /// + None = 0, + /// + /// 默认生成器 + /// Scene最大为65535个。 + /// + Default = 1, + /// + /// ID中包含World,使用这种方式可以不用管理合区的ID重复的问题。 + /// 但Scene的数量也会限制到255个。 + /// + World = 2 + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs.meta new file mode 100644 index 0000000..5cebd4f --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/IdFactoryType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70d195390e5d03745b568b2feb0ccc75 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Interface.meta b/Runtime/CoreRuntime/Core/IdFactory/Interface.meta new file mode 100644 index 0000000..e131d86 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 251daaab57dff994eb1cbcf99b0a85c2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs new file mode 100644 index 0000000..d71c15b --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs @@ -0,0 +1,24 @@ +namespace Fantasy.IdFactory +{ + /// + /// EntityId生成器接口类 + /// + public interface IEntityIdFactory + { + /// + /// 创建一个新的Id + /// + public long Create { get; } + } + + /// + /// RuntimeId生成器接口类 + /// + public interface IRuntimeIdFactory + { + /// + /// 创建一个新的Id + /// + public long Create { get; } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs.meta new file mode 100644 index 0000000..85cfe09 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fcaa46761b6d81c439e89da65c1a5a8c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs new file mode 100644 index 0000000..8dd1e99 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs @@ -0,0 +1,27 @@ +namespace Fantasy.IdFactory +{ + /// + /// Id扩展工具接口 + /// + public interface IIdFactoryTool + { + /// + /// 获得创建时间 + /// + /// + /// + public uint GetTime(ref long entityId); + /// + /// 获得SceneId + /// + /// + /// + public uint GetSceneId(ref long entityId); + /// + /// 获得WorldId + /// + /// + /// + public byte GetWorldId(ref long entityId); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs.meta new file mode 100644 index 0000000..3846666 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/Interface/IIdFactoryTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eafa2a545ef12a14b94213081cb74413 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/World.meta b/Runtime/CoreRuntime/Core/IdFactory/World.meta new file mode 100644 index 0000000..1864982 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/World.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f3c2fcd754e51934286289b6b2085418 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs b/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs new file mode 100644 index 0000000..dbba88f --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs @@ -0,0 +1,153 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个唯一实体的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct WorldEntityIdStruct + { + // EntityId:39 + 8 + 8 + 18 = 64 + // +-------------------+--------------------------+-----------------------+------------------------------------+ + // | time(30) 最大34年 | SceneId(8) 最多255个Scene | WordId(8) 最多255个世界 | sequence(18) 每秒每个进程能生产262143个 + // +-------------------+--------------------------+-----------------------+------------------------------------+ + public uint Time { get; private set; } + public uint SceneId { get; private set; } + public byte WordId { get; private set; } + public uint Sequence { get; private set; } + + public const uint MaskSequence = 0x3FFFF; + public const uint MaskSceneId = 0xFF; + public const uint MaskWordId = 0xFF; + public const uint MaskTime = 0x3FFFFFFF; + + /// + /// WorldEntityIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过1073741823 + /// sceneId不能超过255 + /// wordId不能超过255 + /// sequence不能超过262143 + public WorldEntityIdStruct(uint time, uint sceneId, byte wordId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + WordId = wordId; + Sequence = sequence; + } + + public static implicit operator long(WorldEntityIdStruct entityIdStruct) + { + ulong result = 0; + result |= entityIdStruct.Sequence; + result |= (ulong)entityIdStruct.WordId << 18; + result |= (ulong)(entityIdStruct.SceneId % (entityIdStruct.WordId * 1000)) << 26; + result |= (ulong)entityIdStruct.Time << 34; + return (long)result; + } + + public static implicit operator WorldEntityIdStruct(long entityId) + { + var result = (ulong) entityId; + var entityIdStruct = new WorldEntityIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 18; + entityIdStruct.WordId = (byte)(result & MaskWordId); + result >>= 8; + entityIdStruct.SceneId = (uint)(result & MaskSceneId) + (uint)entityIdStruct.WordId * 1000; + result >>= 8; + entityIdStruct.Time = (uint)(result & MaskTime); + return entityIdStruct; + } + } + + public sealed class WorldEntityIdFactory : IEntityIdFactory + { + private readonly uint _sceneId; + private readonly byte _worldId; + + private uint _lastTime; + private uint _lastSequence; + private static readonly long Epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + private static readonly long EpochThisYear = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000 - Epoch1970; + + private WorldEntityIdFactory() { } + + public WorldEntityIdFactory(uint sceneId, byte worldId) + { + switch (sceneId) + { + case > 255255: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + case < 1001: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be less than 1001"); + } + default: + { + _sceneId = sceneId; + _worldId = worldId; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - EpochThisYear) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > WorldEntityIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new WorldEntityIdStruct(time, _sceneId, _worldId, _lastSequence); + } + } + } + + public sealed class WorldEntityIdFactoryTool : IIdFactoryTool + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetTime(ref long entityId) + { + var result = (ulong)entityId >> 34; + return (uint)(result & WorldEntityIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetSceneId(ref long entityId) + { + var result = (ulong)entityId >> 18; + var worldId = (uint)(result & WorldEntityIdStruct.MaskWordId) * 1000; + result >>= 8; + return (uint)(result & WorldEntityIdStruct.MaskSceneId) + worldId; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public byte GetWorldId(ref long entityId) + { + var result = (ulong)entityId >> 18; + return (byte)(result & WorldEntityIdStruct.MaskWordId); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs.meta new file mode 100644 index 0000000..607a1ea --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/World/WorldEntityIdFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d7564a13b69a6f4891aadf954a5e30d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs b/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs new file mode 100644 index 0000000..a5d582b --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs @@ -0,0 +1,155 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个运行时的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct WorldRuntimeIdStruct + { + // RuntimeId:23 + 8 + 8 + 25 = 64 + // +-------------------+--------------------------+-----------------------+--------------------------------------+ + // | time(23) 最大60天 | SceneId(8) 最多255个Scene | WordId(8) 最多255个世界 | sequence(25) 每秒每个进程能生产33554431个 + // +-------------------+--------------------------+-----------------------+--------------------------------------+ + public uint Time { get; private set; } + public uint SceneId { get; private set; } + public byte WordId { get; private set; } + public uint Sequence { get; private set; } + + public const uint MaskSequence = 0x1FFFFFF; + public const uint MaskSceneId = 0xFF; + public const uint MaskWordId = 0xFF; + public const uint MaskTime = 0x7FFFFF; + + /// + /// WorldRuntimeIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过8388607 + /// sceneId不能超过255 + /// wordId不能超过255 + /// sequence不能超过33554431 + public WorldRuntimeIdStruct(uint time, uint sceneId, byte wordId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + WordId = wordId; + Sequence = sequence; + } + + public static implicit operator long(WorldRuntimeIdStruct runtimeIdStruct) + { + ulong result = runtimeIdStruct.Sequence; + result |= (ulong)runtimeIdStruct.WordId << 25; + result |= (ulong)(runtimeIdStruct.SceneId % (runtimeIdStruct.WordId * 1000)) << 33; + result |= (ulong)runtimeIdStruct.Time << 41; + return (long)result; + } + + public static implicit operator WorldRuntimeIdStruct(long runtimeId) + { + var result = (ulong)runtimeId; + var runtimeIdStruct = new WorldRuntimeIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 25; + runtimeIdStruct.WordId = (byte)(result & MaskWordId); + result >>= 8; + runtimeIdStruct.SceneId = (uint)(result & MaskSceneId) + (uint)runtimeIdStruct.WordId * 1000; + result >>= 8; + runtimeIdStruct.Time = (uint)(result & MaskTime); + return runtimeIdStruct; + } + } + + public sealed class WorldRuntimeIdFactory : IRuntimeIdFactory + { + private readonly uint _sceneId; + private readonly byte _worldId; + + private uint _lastTime; + private uint _lastSequence; + private readonly long _epochNow; + private readonly long _epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + + private WorldRuntimeIdFactory() { } + + public WorldRuntimeIdFactory(uint sceneId, byte worldId) : this(TimeHelper.Now, sceneId, worldId) { } + + public WorldRuntimeIdFactory(long epochNow, uint sceneId, byte worldId) + { + switch (sceneId) + { + case > 255255: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + case < 1001: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be less than 1001"); + } + default: + { + _sceneId = sceneId; + _worldId = worldId; + _epochNow = epochNow - _epoch1970; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - _epochNow) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > WorldRuntimeIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new WorldRuntimeIdStruct(time, _sceneId, _worldId, _lastSequence); + } + } + } + + public sealed class WorldRuntimeIdFactoryTool : IIdFactoryTool + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetTime(ref long runtimeId) + { + var result = (ulong)runtimeId >> 41; + return (uint)(result & WorldRuntimeIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint GetSceneId(ref long runtimeId) + { + var result = (ulong)runtimeId >> 25; + var worldId = (uint)(result & WorldRuntimeIdStruct.MaskWordId) * 1000; + result >>= 8; + return (uint)(result & WorldRuntimeIdStruct.MaskSceneId) + worldId; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public byte GetWorldId(ref long runtimeId) + { + var result = (ulong)runtimeId >> 25; + return (byte)(result & WorldRuntimeIdStruct.MaskWordId); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs.meta b/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs.meta new file mode 100644 index 0000000..4083387 --- /dev/null +++ b/Runtime/CoreRuntime/Core/IdFactory/World/WorldRuntimeIdFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e05253b7b94f6c43987798ae6790c57 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/InnerErrorCode.cs b/Runtime/CoreRuntime/Core/InnerErrorCode.cs new file mode 100644 index 0000000..e549a22 --- /dev/null +++ b/Runtime/CoreRuntime/Core/InnerErrorCode.cs @@ -0,0 +1,66 @@ +namespace Fantasy.Network +{ + /// + /// 定义 Fantasy 框架中的内部错误代码。 + /// + public class InnerErrorCode + { + private InnerErrorCode() { } + /// + /// 表示 Rpc 消息发送失败的错误代码。 + /// + public const uint ErrRpcFail = 100000002; + /// + /// 表示未找到 Route 消息的错误代码。 + /// + public const uint ErrNotFoundRoute = 100000003; + /// + /// 表示发送 Route 消息超时的错误代码。 + /// + public const uint ErrRouteTimeout = 100000004; + /// + /// 表示未找到实体的错误代码。 + /// + public const uint ErrEntityNotFound = 100000008; + /// + /// 表示传送过程中发生错误的错误代码。 + /// + public const uint ErrTransfer = 100000009; + /// + /// 表示连接Roaming时候已经存在同RoamingType的Roaming了。 + /// + public const uint ErrLinkRoamingAlreadyExists = 100000009; + /// + /// 表示连接Roaming时候在漫游终端已经存在同Id的终端。 + /// + public const uint ErrAddRoamingTerminalAlreadyExists = 100000010; + /// + /// 表示未找到 Roaming 消息的错误代码。 + /// + public const uint ErrNotFoundRoaming = 100000011; + /// + /// 表示发送 Roaming 消息超时的错误代码。 + /// + public const uint ErrRoamingTimeout = 100000012; + /// + /// 表示再锁定 Roaming 消息的时候没有找到对应的Session错误代码。 + /// + public const uint ErrLockTerminusIdNotFoundSession = 100000013; + /// + /// 表示再锁定 Roaming 消息的时候没有找到对应的RoamingType错误代码。 + /// + public const uint ErrLockTerminusIdNotFoundRoamingType = 100000014; + /// + /// 表示再解除锁定 Roaming 消息的时候没有找到对应的Session错误代码。 + /// + public const uint ErrUnLockTerminusIdNotFoundSession = 100000015; + /// + /// 表示再解除锁定 Roaming 消息的时候没有找到对应的RoamingType错误代码。 + /// + public const uint ErrUnLockTerminusIdNotFoundRoamingType = 100000016; + /// + /// 表示再传送 Terminus 时对应的错误代码。 + /// + public const uint ErrTerminusStartTransfer = 100000017; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/InnerErrorCode.cs.meta b/Runtime/CoreRuntime/Core/InnerErrorCode.cs.meta new file mode 100644 index 0000000..81600c1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/InnerErrorCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f6d49bab6fcaff46b43935752e80f05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Log.meta b/Runtime/CoreRuntime/Core/Log.meta new file mode 100644 index 0000000..bb915d5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5209843c0faa1454ea3446c5075e39c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs b/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs new file mode 100644 index 0000000..0d57e22 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs @@ -0,0 +1,144 @@ +#if FANTASY_NET +using Fantasy.Platform.Net; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy; + +/// +/// 标准的控制台Log +/// +public sealed class ConsoleLog : ILog +{ + /// + /// 初始化方法 + /// + /// + public void Initialize(ProcessMode processMode) { } + + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + public void Trace(string message) + { + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine(message); + } + + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + public void Warning(string message) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine(message); + } + + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + public void Info(string message) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(message); + } + + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + public void Debug(string message) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine(message); + } + + /// + /// 记录错误级别的日志消息。 + /// + /// 日志消息。 + public void Error(string message) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine(message); + } + + /// + /// 记录严重错误级别的日志消息。 + /// + /// 日志消息。 + public void Fatal(string message) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine(message); + } + + /// + /// 记录跟踪级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Trace(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine(message, args); + } + + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Warning(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine(message, args); + } + + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Info(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(message, args); + } + + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Debug(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine(message, args); + } + + /// + /// 记录错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Error(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine(message, args); + } + + /// + /// 记录严重错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Fatal(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine(message, args); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs.meta b/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs.meta new file mode 100644 index 0000000..c08a02e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/ConsoleLog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96de1bb40fbda6047a4352ebf222e0ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Log/ILog.cs b/Runtime/CoreRuntime/Core/Log/ILog.cs new file mode 100644 index 0000000..b01e857 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/ILog.cs @@ -0,0 +1,74 @@ +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif +namespace Fantasy +{ + /// + /// 定义日志记录功能的接口。 + /// + public interface ILog + { +#if FANTASY_NET + /// + /// 初始化 + /// + /// + void Initialize(ProcessMode processMode); +#endif + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + void Trace(string message); + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + void Warning(string message); + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + void Info(string message); + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + void Debug(string message); + /// + /// 记录错误级别的日志消息。 + /// + /// 日志消息。 + void Error(string message); + /// + /// 记录跟踪级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Trace(string message, params object[] args); + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Warning(string message, params object[] args); + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Info(string message, params object[] args); + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Debug(string message, params object[] args); + /// + /// 记录错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Error(string message, params object[] args); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Log/ILog.cs.meta b/Runtime/CoreRuntime/Core/Log/ILog.cs.meta new file mode 100644 index 0000000..72c3c23 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/ILog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e55136184e77b1146a90b15eaac8d8bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Log/Log.cs b/Runtime/CoreRuntime/Core/Log/Log.cs new file mode 100644 index 0000000..8069fff --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/Log.cs @@ -0,0 +1,189 @@ +using System; +using System.Diagnostics; +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy +{ + /// + /// 提供日志记录功能的静态类。 + /// + public static class Log + { + private static ILog _logCore; + private static bool _isRegister; +#if FANTASY_NET + /// + /// 初始化Log系统 + /// + public static void Initialize() + { + if (!_isRegister) + { + Register(new ConsoleLog()); + return; + } + + var processMode = ProcessMode.None; + + switch (ProcessDefine.Options.Mode) + { + case "Develop": + { + processMode = ProcessMode.Develop; + break; + } + case "Release": + { + processMode = ProcessMode.Release; + break; + } + } + + _logCore.Initialize(processMode); + } +#endif + /// + /// 注册一个日志系统 + /// + /// + public static void Register(ILog log) + { + if (_isRegister) + { + return; + } + + _logCore = log; + _isRegister = true; + } + + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + public static void Trace(string msg) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{msg}\n{st}"); + } + + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + public static void Debug(string msg) + { + _logCore.Debug(msg); + } + + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + public static void Info(string msg) + { + _logCore.Info(msg); + } + + /// + /// 记录跟踪级别的日志消息,并附带调用栈信息。 + /// + /// 日志消息。 + public static void TraceInfo(string msg) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{msg}\n{st}"); + } + + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + public static void Warning(string msg) + { + _logCore.Warning(msg); + } + + /// + /// 记录错误级别的日志消息,并附带调用栈信息。 + /// + /// 日志消息。 + public static void Error(string msg) + { + var st = new StackTrace(1, true); + _logCore.Error($"{msg}\n{st}"); + } + + /// + /// 记录异常的错误级别的日志消息,并附带调用栈信息。 + /// + /// 异常对象。 + public static void Error(Exception e) + { + if (e.Data.Contains("StackTrace")) + { + _logCore.Error($"{e.Data["StackTrace"]}\n{e}"); + return; + } + var str = e.ToString(); + _logCore.Error(str); + } + + /// + /// 记录跟踪级别的格式化日志消息,并附带调用栈信息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Trace(string message, params object[] args) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{string.Format(message, args)}\n{st}"); + } + + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Warning(string message, params object[] args) + { + _logCore.Warning(string.Format(message, args)); + } + + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Info(string message, params object[] args) + { + _logCore.Info(string.Format(message, args)); + } + + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Debug(string message, params object[] args) + { + _logCore.Debug(string.Format(message, args)); + } + + /// + /// 记录错误级别的格式化日志消息,并附带调用栈信息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Error(string message, params object[] args) + { + var st = new StackTrace(1, true); + var s = string.Format(message, args) + '\n' + st; + _logCore.Error(s); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Log/Log.cs.meta b/Runtime/CoreRuntime/Core/Log/Log.cs.meta new file mode 100644 index 0000000..68fa9c8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 876c3c00c478c9940a155c1bd180114e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Log/UnityLog.cs b/Runtime/CoreRuntime/Core/Log/UnityLog.cs new file mode 100644 index 0000000..df95444 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/UnityLog.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; +#if UNITY_EDITOR +using System; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEditorInternal; +#else +using System; +#endif + +#if FANTASY_UNITY +namespace Fantasy +{ + public class UnityLog : ILog + { + public void Trace(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Debug(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Info(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Warning(string msg) + { + UnityEngine.Debug.LogWarning(msg); + } + + public void Error(string msg) + { + UnityEngine.Debug.LogError(msg); + } + + public void Error(Exception e) + { + UnityEngine.Debug.LogException(e); + } + + public void Trace(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Warning(string message, params object[] args) + { + UnityEngine.Debug.LogWarningFormat(message, args); + } + + public void Info(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Debug(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Error(string message, params object[] args) + { + UnityEngine.Debug.LogErrorFormat(message, args); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Log/UnityLog.cs.meta b/Runtime/CoreRuntime/Core/Log/UnityLog.cs.meta new file mode 100644 index 0000000..198d247 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Log/UnityLog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cd57fb1e54ce2844f9d2d1aaf9b87ad4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network.meta b/Runtime/CoreRuntime/Core/Network.meta new file mode 100644 index 0000000..d8ec8df --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 10a5702da12ecd84187b65341266b9c7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable.meta b/Runtime/CoreRuntime/Core/Network/Addressable.meta new file mode 100644 index 0000000..587f6de --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea813fc4a19ded74499e64aa2bc3db98 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs new file mode 100644 index 0000000..098ba8a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs @@ -0,0 +1,141 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Platform.Net; +namespace Fantasy.Network.Route +{ + /// + /// 提供操作地址映射的辅助方法。 + /// + public static class AddressableHelper + { + // 声明一个私有静态只读列表 AddressableScenes,用于存储地址映射的场景配置信息 + private static readonly List AddressableScenes = new List(); + + static AddressableHelper() + { + // 遍历场景配置信息,筛选出地址映射类型的场景,并添加到 AddressableScenes 列表中 + foreach (var sceneConfig in SceneConfigData.Instance.List) + { + if (sceneConfig.SceneTypeString == "Addressable") + { + AddressableScenes.Add(new AddressableScene(sceneConfig)); + } + } + } + + /// + /// 添加地址映射并返回操作结果。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 是否锁定。 + public static async FTask AddAddressable(Scene scene, long addressableId, long routeId, bool isLock = true) + { + // 获取指定索引的地址映射场景配置信息 + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + // 调用内部路由方法,发送添加地址映射的请求并等待响应 + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableAdd_Request + { + AddressableId = addressableId, RouteId = routeId, IsLock = isLock + }); + if (response.ErrorCode != 0) + { + Log.Error($"AddAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 获取地址映射的路由 ID。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 地址映射的路由 ID。 + public static async FTask GetAddressableRouteId(Scene scene, long addressableId) + { + // 获取指定索引的地址映射场景配置信息 + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + // 调用内部路由方法,发送获取地址映射路由 ID 的请求并等待响应 + var response = (I_AddressableGet_Response) await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableGet_Request + { + AddressableId = addressableId + }); + // 检查响应错误码,如果为零,返回路由 ID;否则,输出错误信息并返回 0 + if (response.ErrorCode == 0) + { + return response.RouteId; + } + + Log.Error($"GetAddressable error is {response.ErrorCode} addressableId:{addressableId}"); + return 0; + } + + /// + /// 移除指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + public static async FTask RemoveAddressable(Scene scene, long addressableId) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableRemove_Request + { + AddressableId = addressableId + }); + + if (response.ErrorCode != 0) + { + Log.Error($"RemoveAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 锁定指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + public static async FTask LockAddressable(Scene scene, long addressableId) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableLock_Request + { + AddressableId = addressableId + }); + + if (response.ErrorCode != 0) + { + Log.Error($"LockAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 解锁指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 解锁来源。 + public static async FTask UnLockAddressable(Scene scene, long addressableId, long routeId, string source) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableUnLock_Request + { + AddressableId = addressableId, + RouteId = routeId, + Source = source + }); + + if (response.ErrorCode != 0) + { + Log.Error($"UnLockAddressable error is {response.ErrorCode}"); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs.meta new file mode 100644 index 0000000..74bbf2b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a9abc369b722d6a428c30a0da0924698 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs new file mode 100644 index 0000000..8d08f08 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs @@ -0,0 +1,144 @@ +#if FANTASY_NET +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Route +{ + public class AddressableManageComponentAwakeSystem : AwakeSystem + { + protected override void Awake(AddressableManageComponent self) + { + self.AddressableLock = self.Scene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + } + } + + public class AddressableManageComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableManageComponent self) + { + foreach (var (_, waitCoroutineLock) in self.Locks) + { + waitCoroutineLock.Dispose(); + } + + self.Locks.Clear(); + self.Addressable.Clear(); + self.AddressableLock.Dispose(); + self.AddressableLock = null; + } + } + + public sealed class AddressableManageComponent : Entity + { + public CoroutineLock AddressableLock; + public readonly Dictionary Addressable = new(); + public readonly Dictionary Locks = new(); + + /// + /// 添加地址映射。 + /// + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 是否进行锁定。 + public async FTask Add(long addressableId, long routeId, bool isLock) + { + WaitCoroutineLock waitCoroutineLock = null; + + try + { + if (isLock) + { + waitCoroutineLock = await AddressableLock.Wait(addressableId); + } + + Addressable[addressableId] = routeId; +#if FANTASY_DEVELOP + Log.Debug($"AddressableManageComponent Add addressableId:{addressableId} routeId:{routeId}"); +#endif + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + waitCoroutineLock?.Dispose(); + } + } + + /// + /// 获取地址映射的路由 ID。 + /// + /// 地址映射的唯一标识。 + /// 地址映射的路由 ID。 + public async FTask Get(long addressableId) + { + using (await AddressableLock.Wait(addressableId)) + { + Addressable.TryGetValue(addressableId, out var routeId); + return routeId; + } + } + + /// + /// 移除地址映射。 + /// + /// 地址映射的唯一标识。 + public async FTask Remove(long addressableId) + { + using (await AddressableLock.Wait(addressableId)) + { + Addressable.Remove(addressableId); +#if FANTASY_DEVELOP + Log.Debug($"Addressable Remove addressableId: {addressableId} _addressable:{Addressable.Count}"); +#endif + } + } + + /// + /// 锁定地址映射。 + /// + /// 地址映射的唯一标识。 + public async FTask Lock(long addressableId) + { + var waitCoroutineLock = await AddressableLock.Wait(addressableId); + Locks.Add(addressableId, waitCoroutineLock); + } + + /// + /// 解锁地址映射。 + /// + /// 地址映射的唯一标识。 + /// 新的路由 ID。 + /// 解锁来源。 + public void UnLock(long addressableId, long routeId, string source) + { + if (!Locks.Remove(addressableId, out var coroutineLock)) + { + Log.Error($"Addressable unlock not found addressableId: {addressableId} Source:{source}"); + return; + } + + Addressable.TryGetValue(addressableId, out var oldAddressableId); + + if (routeId != 0) + { + Addressable[addressableId] = routeId; + } + + coroutineLock.Dispose(); +#if FANTASY_DEVELOP + Log.Debug($"Addressable UnLock key: {addressableId} oldAddressableId : {oldAddressableId} routeId: {routeId} Source:{source}"); +#endif + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs.meta new file mode 100644 index 0000000..588bf03 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableManageComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e4e5f06569ddf9448c455a0eb8d51e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs new file mode 100644 index 0000000..03e0def --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs @@ -0,0 +1,91 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + public class AddressableMessageComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableMessageComponent self) + { + if (self.AddressableId != 0) + { + AddressableHelper.RemoveAddressable(self.Scene, self.AddressableId).Coroutine(); + self.AddressableId = 0; + } + } + } + + /// + /// 可寻址消息组件、挂载了这个组件可以接收Addressable消息 + /// + public sealed class AddressableMessageComponent : Entity + { + /// + /// 可寻址消息组件的唯一标识。 + /// + public long AddressableId; + + /// + /// 注册可寻址消息组件。 + /// + /// 是否进行锁定。 + public FTask Register(bool isLock = true) + { + if (Parent == null) + { + throw new Exception("AddressableRouteComponent must be mounted under a component"); + } + + AddressableId = Parent.Id; + + if (AddressableId == 0) + { + throw new Exception("AddressableRouteComponent.Parent.Id is null"); + } + +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent Register addressableId:{AddressableId} RouteId:{Parent.RouteId}"); +#endif + return AddressableHelper.AddAddressable(Scene, AddressableId, Parent.RouteId, isLock); + } + + /// + /// 锁定可寻址消息组件。 + /// + public FTask Lock() + { +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent Lock {Parent.Id}"); +#endif + return AddressableHelper.LockAddressable(Scene, Parent.Id); + } + + /// + /// 解锁可寻址消息组件。 + /// + /// 解锁来源。 + public FTask UnLock(string source) + { +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent UnLock {Parent.Id} {Parent.RouteId}"); +#endif + return AddressableHelper.UnLockAddressable(Scene, Parent.Id, Parent.RouteId, source); + } + + /// + /// 锁定可寻址消息并且释放掉AddressableMessageComponent组件。 + /// 该方法不会自动取Addressable中心删除自己的信息。 + /// 用于传送或转移到其他服务器时使用 + /// + public async FTask LockAndRelease() + { + await Lock(); + AddressableId = 0; + Dispose(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs.meta new file mode 100644 index 0000000..edfc692 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableMessageComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0bfde37364b17514abbacde92f4483fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs new file mode 100644 index 0000000..bf439d7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs @@ -0,0 +1,218 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Scheduler; +using Fantasy.Timer; + +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + public class AddressableRouteComponentAwakeSystem : AwakeSystem + { + protected override void Awake(AddressableRouteComponent self) + { + ((Session)self.Parent).AddressableRouteComponent = self; + + var selfScene = self.Scene; + self.TimerComponent = selfScene.TimerComponent; + self.NetworkMessagingComponent = selfScene.NetworkMessagingComponent; + self.MessageDispatcherComponent = selfScene.MessageDispatcherComponent; + self.AddressableRouteLock = + selfScene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + } + } + + public class AddressableRouteComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableRouteComponent self) + { + self.AddressableRouteLock.Dispose(); + + self.AddressableRouteId = 0; + self.AddressableId = 0; + self.TimerComponent = null; + self.AddressableRouteLock = null; + self.NetworkMessagingComponent = null; + self.MessageDispatcherComponent = null; + } + } + + /// + /// 可寻址路由消息组件,挂载了这个组件可以接收和发送 Addressable 消息。 + /// + public sealed class AddressableRouteComponent : Entity + { + public long AddressableId; + public long AddressableRouteId; + public CoroutineLock AddressableRouteLock; + public TimerComponent TimerComponent; + public NetworkMessagingComponent NetworkMessagingComponent; + public MessageDispatcherComponent MessageDispatcherComponent; + + internal void Send(IAddressableRouteMessage message) + { + Call(message).Coroutine(); + } + + internal async FTask Send(Type requestType, APackInfo packInfo) + { + await Call(requestType, packInfo); + } + + internal async FTask Call(Type requestType, APackInfo packInfo) + { + if (IsDisposed) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoute); + } + + packInfo.IsDisposed = true; + var failCount = 0; + var runtimeId = RuntimeId; + IResponse iRouteResponse = null; + + try + { + using (await AddressableRouteLock.Wait(AddressableId, "AddressableRouteComponent Call MemoryStream")) + { + while (!IsDisposed) + { + if (AddressableRouteId == 0) + { + AddressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, AddressableId); + } + + if (AddressableRouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(requestType, + InnerErrorCode.ErrNotFoundRoute); + } + + iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(AddressableRouteId, requestType, packInfo); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrRouteTimeout: + { + return iRouteResponse; + } + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error($"AddressableComponent.Call failCount > 20 route send message fail, routeId: {RouteId} AddressableRouteComponent:{Id}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(100); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + AddressableRouteId = 0; + continue; + } + default: + { + return iRouteResponse; // 对于其他情况,直接返回响应,无需额外处理 + } + } + } + } + } + finally + { + packInfo.Dispose(); + } + + + return iRouteResponse; + } + + /// + /// 调用可寻址路由消息并等待响应。 + /// + /// 可寻址路由请求。 + private async FTask Call(IAddressableRouteMessage request) + { + if (IsDisposed) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoute); + } + + var failCount = 0; + var runtimeId = RuntimeId; + + using (await AddressableRouteLock.Wait(AddressableId, "AddressableRouteComponent Call")) + { + while (true) + { + if (AddressableRouteId == 0) + { + AddressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, AddressableId); + } + + if (AddressableRouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), + InnerErrorCode.ErrNotFoundRoute); + } + + var iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(AddressableRouteId, request); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error( + $"AddressableRouteComponent.Call failCount > 20 route send message fail, routeId: {RouteId} AddressableRouteComponent:{Id}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(500); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + AddressableRouteId = 0; + continue; + } + case InnerErrorCode.ErrRouteTimeout: + { + return iRouteResponse; + } + default: + { + return iRouteResponse; + } + } + } + } + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs.meta new file mode 100644 index 0000000..0af71d6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableRouteComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ff201d69f6da1e49a9971ee4499bf99 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs new file mode 100644 index 0000000..3105fca --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs @@ -0,0 +1,31 @@ +#if FANTASY_NET +using Fantasy.IdFactory; +using Fantasy.Platform.Net; + +namespace Fantasy.Network.Route +{ + /// + /// AddressableScene + /// + public sealed class AddressableScene + { + /// + /// Id + /// + public readonly long Id; + /// + /// RunTimeId + /// + public readonly long RunTimeId; + /// + /// 构造方法 + /// + /// sceneConfig + public AddressableScene(SceneConfig sceneConfig) + { + Id = IdFactoryHelper.EntityId(0, sceneConfig.Id, (byte)sceneConfig.WorldConfigId, 0); + RunTimeId = IdFactoryHelper.RuntimeId(0, sceneConfig.Id, (byte)sceneConfig.WorldConfigId, 0); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs.meta new file mode 100644 index 0000000..5db1ea1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/AddressableScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ee25be555d2b6644aaf8923ebcc910c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler.meta new file mode 100644 index 0000000..3f6f75c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2851a8eadbc9b42448fc18ddc9128cc2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs new file mode 100644 index 0000000..847625b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableAddHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableAddHandler : RouteRPC + { + /// + /// 在收到地址映射添加请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableAdd_Request 实例。 + /// 用于构建响应的 I_AddressableAdd_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableAdd_Request request, I_AddressableAdd_Response response, Action reply) + { + await scene.GetComponent().Add(request.AddressableId, request.RouteId, request.IsLock); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta new file mode 100644 index 0000000..fd048f7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e5090516b2b4c294d9685fa5c826fb1f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs new file mode 100644 index 0000000..f53c1f1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableGetHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableGetHandler : RouteRPC + { + /// + /// 在收到地址映射获取请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableGet_Request 实例。 + /// 用于构建响应的 I_AddressableGet_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableGet_Request request, I_AddressableGet_Response response, Action reply) + { + response.RouteId = await scene.GetComponent().Get(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta new file mode 100644 index 0000000..9ffa1ab --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9db088fa535e48429a01018cba33c05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs new file mode 100644 index 0000000..b964274 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableLockHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableLockHandler : RouteRPC + { + /// + /// 在收到地址映射锁定请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableLock_Request 实例。 + /// 用于构建响应的 I_AddressableLock_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableLock_Request request, I_AddressableLock_Response response, Action reply) + { + await scene.GetComponent().Lock(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta new file mode 100644 index 0000000..89faa2f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e05aef9a498189744be112fa380836b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs new file mode 100644 index 0000000..c4e9654 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableRemoveHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableRemoveHandler : RouteRPC + { + /// + /// 在收到地址映射移除请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableRemove_Request 实例。 + /// 用于构建响应的 I_AddressableRemove_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableRemove_Request request, I_AddressableRemove_Response response, Action reply) + { + await scene.GetComponent().Remove(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta new file mode 100644 index 0000000..6692956 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 50f53e364f5aed54d9d450b9ba7fc4bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs new file mode 100644 index 0000000..1ab3937 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs @@ -0,0 +1,27 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableUnLockHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableUnLockHandler : RouteRPC + { + /// + /// 在收到地址映射解锁请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableUnLock_Request 实例。 + /// 用于构建响应的 I_AddressableUnLock_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableUnLock_Request request, I_AddressableUnLock_Response response, Action reply) + { + scene.GetComponent().UnLock(request.AddressableId, request.RouteId, request.Source); + await FTask.CompletedTask; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta new file mode 100644 index 0000000..eb193cc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8dcf406c937e7548b621fdef7f339a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs b/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs new file mode 100644 index 0000000..6e6d4f7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using Fantasy.Serialize; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Network +{ + /// + /// MemoryStreamBuffer对象池类 + /// + public sealed class MemoryStreamBufferPool : IDisposable + { + private readonly int _poolSize; + private readonly int _maxMemoryStreamSize; + private readonly Queue _memoryStreamPool = new Queue(); + + /// + /// 构造方法 + /// + /// + /// + public MemoryStreamBufferPool(int maxMemoryStreamSize = 2048, int poolSize = 512) + { + _poolSize = poolSize; + _maxMemoryStreamSize = maxMemoryStreamSize; + } + + /// + /// 租借MemoryStream + /// + /// + /// + /// + public MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + if (size > _maxMemoryStreamSize) + { + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + if (size < _maxMemoryStreamSize) + { + size = _maxMemoryStreamSize; + } + + if (_memoryStreamPool.Count == 0) + { + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + if (_memoryStreamPool.TryDequeue(out var memoryStream)) + { + memoryStream.MemoryStreamBufferSource = memoryStreamBufferSource; + return memoryStream; + } + + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + /// + /// 归还ReturnMemoryStream + /// + /// + public void ReturnMemoryStream(MemoryStreamBuffer memoryStreamBuffer) + { + if (memoryStreamBuffer.Capacity > _maxMemoryStreamSize) + { + return; + } + + if (_memoryStreamPool.Count > _poolSize) + { + // 设置该值只能是内网或服务器转发的时候可能在连接之前发送的数据过多的情况下可以修改。 + // 设置过大会导致内存占用过大,所以要谨慎设置。 + return; + } + + memoryStreamBuffer.SetLength(0); + memoryStreamBuffer.MemoryStreamBufferSource = MemoryStreamBufferSource.None; + _memoryStreamPool.Enqueue(memoryStreamBuffer); + } + + /// + /// 销毁方法 + /// + public void Dispose() + { + foreach (var memoryStreamBuffer in _memoryStreamPool) + { + memoryStreamBuffer.MemoryStreamBufferSource = MemoryStreamBufferSource.None; + memoryStreamBuffer.Dispose(); + } + _memoryStreamPool.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs.meta b/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs.meta new file mode 100644 index 0000000..69c8603 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/MemoryStreamBufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0213c403ca254f40a3ac5c7d22c2d69 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message.meta b/Runtime/CoreRuntime/Core/Network/Message.meta new file mode 100644 index 0000000..7c0a186 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4faca0c2739c0f2488888c9b6cabe605 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher.meta b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher.meta new file mode 100644 index 0000000..12cacd6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 80bfeacfa28f6514fb21627cfa9f052d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface.meta b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface.meta new file mode 100644 index 0000000..b6e0092 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4e6f89ddd5d2d1b4cb4cc395c5adf890 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs new file mode 100644 index 0000000..d8f928e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs @@ -0,0 +1,220 @@ +// ReSharper disable InconsistentNaming + +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.Serialize; + +namespace Fantasy.Network.Interface +{ + /// + /// 表示消息处理器的接口,处理特定类型的消息。 + /// + public interface IMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type(); + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + FTask Handle(Session session, uint rpcId, uint messageTypeCode, object message); + } + + /// + /// 泛型消息基类,实现了 接口。 + /// + public abstract class Message : IMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(T); + } + + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + public async FTask Handle(Session session, uint rpcId, uint messageTypeCode, object message) + { + try + { + await Run(session, (T) message); + } + catch (Exception e) + { + Log.Error(e); + } + } + + /// + /// 运行消息处理逻辑。 + /// + /// 会话对象。 + /// 要处理的消息。 + /// 异步任务。 + protected abstract FTask Run(Session session, T message); + } + + /// + /// 泛型消息RPC基类,实现了 接口,用于处理请求和响应类型的消息。 + /// + public abstract class MessageRPC : IMessageHandler where TRequest : IRequest where TResponse : AMessage, IResponse, new() + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRequest); + } + + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + public async FTask Handle(Session session, uint rpcId, uint messageTypeCode, object message) + { + if (message is not TRequest request) + { + Log.Error($"消息类型转换错误: {message.GetType().Name} to {typeof(TRequest).Name}"); + return; + } + + var response = new TResponse(); + var isReply = false; + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(session, request, response, Reply); + } + catch (Exception e) + { + Log.Error(e); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行消息处理逻辑。 + /// + /// 会话对象。 + /// 请求消息。 + /// 响应消息。 + /// 发送响应的方法。 + /// 异步任务。 + protected abstract FTask Run(Session session, TRequest request, TResponse response, Action reply); + } +#if FANTASY_UNITY + public interface IMessageDelegateHandler + { + /// + /// 注册消息处理器。 + /// + /// + public void Register(object @delegate); + /// + /// 取消注册消息处理器。 + /// + /// + public int UnRegister(object @delegate); + /// + /// 处理消息的方法。 + /// + /// + /// + public void Handle(Session session, object message); + } + public delegate FTask MessageDelegate(Session session, T msg) where T : IMessage; + public sealed class MessageDelegateHandler : IMessageDelegateHandler, IDisposable where T : IMessage + { + private readonly List> _delegates = new List>(); + + public Type Type() + { + return typeof(T); + } + + public void Register(object @delegate) + { + var a = (MessageDelegate)@delegate; + + if (_delegates.Contains(a)) + { + Log.Error($"{typeof(T).Name} already register action delegateName:{a.Method.Name}"); + return; + } + + _delegates.Add(a); + } + + public int UnRegister(object @delegate) + { + _delegates.Remove((MessageDelegate)@delegate); + return _delegates.Count; + } + + public void Handle(Session session, object message) + { + foreach (var registerDelegate in _delegates) + { + try + { + registerDelegate(session, (T)message).Coroutine(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public void Dispose() + { + _delegates.Clear(); + } + } +#endif +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta new file mode 100644 index 0000000..99df4a0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 607e031f0e001ed43bedad74075f3a3a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs new file mode 100644 index 0000000..839cf6b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs @@ -0,0 +1,490 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Serialize; + +#if FANTASY_NET +// ReSharper disable InconsistentNaming + +namespace Fantasy.Network.Interface +{ + /// + /// 表示路由消息处理器的接口,处理特定类型的路由消息。 + /// + public interface IRouteMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type(); + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage); + } + + /// + /// 泛型路由基类,实现了 接口,用于处理特定实体和路由消息类型的路由。 + /// + /// 实体类型。 + /// 路由消息类型。 + public abstract class Route : IRouteMessageHandler where TEntity : Entity where TMessage : IRouteMessage + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TMessage); + } + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TMessage ruteMessage) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TMessage).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + try + { + await Run(tEntity, ruteMessage); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + } + } + + /// + /// 运行路由消息处理逻辑。 + /// + /// 实体对象。 + /// 要处理的路由消息。 + /// 异步任务。 + protected abstract FTask Run(TEntity entity, TMessage message); + } + + /// + /// 泛型路由RPC基类,实现了 接口,用于处理请求和响应类型的路由。 + /// + /// 实体类型。 + /// 路由请求类型。 + /// 路由响应类型。 + public abstract class RouteRPC : IRouteMessageHandler where TEntity : Entity where TRouteRequest : IRouteRequest where TRouteResponse : AMessage, IRouteResponse, new() + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRouteRequest); + } + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TRouteRequest tRouteRequest) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TRouteRequest).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + var isReply = false; + var response = new TRouteResponse(); + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(tEntity, tRouteRequest, response, Reply); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行路由消息处理逻辑。 + /// + /// 实体对象。 + /// 请求路由消息。 + /// 响应路由消息。 + /// 发送响应的方法。 + /// 异步任务。 + protected abstract FTask Run(TEntity entity, TRouteRequest request, TRouteResponse response, Action reply); + } + + /// + /// 泛型可寻址路由基类,实现了 接口,用于处理特定实体和可寻址路由消息类型的路由。 + /// + /// 实体类型。 + /// 可寻址路由消息类型。 + public abstract class Addressable : IRouteMessageHandler where TEntity : Entity where TMessage : IAddressableRouteMessage + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TMessage); + } + + /// + /// 处理可寻址路由消息。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 可寻址路由消息。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TMessage ruteMessage) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TMessage).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + try + { + await Run(tEntity, ruteMessage); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + } + finally + { + session.Send(new RouteResponse(), rpcId); + } + } + + /// + /// 运行处理可寻址路由消息。 + /// + /// 实体。 + /// 可寻址路由消息。 + protected abstract FTask Run(TEntity entity, TMessage message); + } + + /// + /// 泛型可寻址RPC路由基类,实现了 接口,用于处理特定实体和可寻址RPC路由请求类型的路由。 + /// + /// 实体类型。 + /// 可寻址RPC路由请求类型。 + /// 可寻址RPC路由响应类型。 + public abstract class AddressableRPC : IRouteMessageHandler where TEntity : Entity where TRouteRequest : IAddressableRouteRequest where TRouteResponse : IAddressableRouteResponse, new() + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRouteRequest); + } + + /// + /// 处理可寻址RPC路由请求。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 可寻址RPC路由请求。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TRouteRequest tRouteRequest) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TRouteRequest).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + var isReply = false; + var response = new TRouteResponse(); + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(tEntity, tRouteRequest, response, Reply); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行处理可寻址RPC路由请求。 + /// + /// 实体。 + /// 可寻址RPC路由请求。 + /// 可寻址RPC路由响应。 + /// 回复操作。 + protected abstract FTask Run(TEntity entity, TRouteRequest request, TRouteResponse response, Action reply); + } + + /// + /// 泛型漫游路由基类,实现了 接口,用于处理特定实体和漫游路由消息类型的路由。 + /// + /// 实体类型。 + /// 漫游消息类型。 + public abstract class Roaming : IRouteMessageHandler where TEntity : Entity where TMessage : IRoamingMessage + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TMessage); + } + + /// + /// 处理漫游消息。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 漫游消息。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TMessage ruteMessage) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TMessage).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + try + { + await Run(tEntity, ruteMessage); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + } + finally + { + session.Send(new RouteResponse(), rpcId); + } + } + + /// + /// 运行处理漫游消息。 + /// + /// 终点实体。 + /// 漫游消息。 + protected abstract FTask Run(TEntity terminus, TMessage message); + } + + /// + /// 漫游RPC路由基类,实现了 接口,用于处理特定实体和漫游RPC路由请求类型的路由。 + /// + /// 实体类型。 + /// 漫游RPC路由请求类型。 + /// 漫游RPC路由响应类型。 + public abstract class RoamingRPC : IRouteMessageHandler where TEntity : Entity where TRouteRequest : IRoamingRequest where TRouteResponse : IRoamingResponse, new() + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRouteRequest); + } + + /// + /// 处理漫游RPC路由请求。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 漫游RPC路由请求。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TRouteRequest tRouteRequest) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TRouteRequest).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"{this.GetType().Name} Route type conversion error: {entity.GetType().Name} to {typeof(TEntity).Name}"); + return; + } + + var isReply = false; + var response = new TRouteResponse(); + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(tEntity, tRouteRequest, response, Reply); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行处理漫游RPC路由请求。 + /// + /// 终点实体。 + /// 漫游RPC路由请求。 + /// 漫游RPC路由响应。 + /// 回复操作。 + protected abstract FTask Run(TEntity terminus, TRouteRequest request, TRouteResponse response, Action reply); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta new file mode 100644 index 0000000..04ba435 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad7f270253a654f41b705b26c6149e65 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs new file mode 100644 index 0000000..0a24770 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs @@ -0,0 +1,426 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.DataStructure.Dictionary; +using Fantasy.Entitas; +using Fantasy.InnerMessage; +using Fantasy.Network; +#pragma warning disable CS8604 // Possible null reference argument. + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Interface +{ + /// + /// 用于存储消息处理器的信息,包括类型和对象实例。 + /// + /// 消息处理器的类型 + internal sealed class HandlerInfo + { + /// + /// 获取或设置消息处理器对象。 + /// + public T Obj; + /// + /// 获取或设置消息处理器的类型。 + /// + public Type Type; + } + + /// + /// 网络消息分发组件。 + /// + public sealed class MessageDispatcherComponent : Entity, IAssembly + { + public long AssemblyIdentity { get; set; } + private readonly Dictionary _responseTypes = new Dictionary(); + private readonly DoubleMapDictionary _networkProtocols = new DoubleMapDictionary(); + private readonly Dictionary _messageHandlers = new Dictionary(); + private readonly OneToManyList _assemblyResponseTypes = new OneToManyList(); + private readonly OneToManyList _assemblyNetworkProtocols = new OneToManyList(); + private readonly OneToManyList> _assemblyMessageHandlers = new OneToManyList>(); +#if FANTASY_UNITY + private readonly Dictionary _messageDelegateHandlers = new Dictionary(); +#endif +#if FANTASY_NET + private readonly Dictionary _customRouteMap = new Dictionary(); + private readonly OneToManyList _assemblyCustomRouteMap = new OneToManyList(); + private readonly Dictionary _routeMessageHandlers = new Dictionary(); + private readonly OneToManyList> _assemblyRouteMessageHandlers = new OneToManyList>(); +#endif + private CoroutineLock _receiveRouteMessageLock; + + #region Initialize + + internal async FTask Initialize() + { + _receiveRouteMessageLock = Scene.CoroutineLockComponent.Create(GetType().TypeHandle.Value.ToInt64()); + await AssemblySystem.Register(this); + return this; + } + + public async FTask Load(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + private void LoadInner(long assemblyIdentity) + { + // 遍历所有实现了IMessage接口的类型,获取OpCode并添加到_networkProtocols字典中 + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IMessage))) + { + var obj = (IMessage) Activator.CreateInstance(type); + var opCode = obj.OpCode(); + + _networkProtocols.Add(opCode, type); + + var responseType = type.GetProperty("ResponseType"); + + // 如果类型具有ResponseType属性,将其添加到_responseTypes字典中 + if (responseType != null) + { + _responseTypes.Add(type, responseType.PropertyType); + _assemblyResponseTypes.Add(assemblyIdentity, type); + } + + _assemblyNetworkProtocols.Add(assemblyIdentity, opCode); + } + + // 遍历所有实现了IMessageHandler接口的类型,创建实例并添加到_messageHandlers字典中 + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IMessageHandler))) + { + var obj = (IMessageHandler) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var key = obj.Type(); + _messageHandlers.Add(key, obj); + _assemblyMessageHandlers.Add(assemblyIdentity, new HandlerInfo() + { + Obj = obj, Type = key + }); + } + + // 如果编译符号FANTASY_NET存在,遍历所有实现了IRouteMessageHandler接口的类型,创建实例并添加到_routeMessageHandlers字典中 +#if FANTASY_NET + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IRouteMessageHandler))) + { + var obj = (IRouteMessageHandler) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var key = obj.Type(); + _routeMessageHandlers.Add(key, obj); + _assemblyRouteMessageHandlers.Add(assemblyIdentity, new HandlerInfo() + { + Obj = obj, Type = key + }); + } + + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(ICustomRoute))) + { + var obj = (ICustomRoute) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var opCode = obj.OpCode(); + _customRouteMap[opCode] = obj.RouteType; + _assemblyCustomRouteMap.Add(assemblyIdentity, opCode); + } +#endif + } + + public async FTask ReLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask OnUnLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene?.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + private void OnUnLoadInner(long assemblyIdentity) + { + // 移除程序集对应的ResponseType类型和OpCode信息 + if (_assemblyResponseTypes.TryGetValue(assemblyIdentity, out var removeResponseTypes)) + { + foreach (var removeResponseType in removeResponseTypes) + { + _responseTypes.Remove(removeResponseType); + } + + _assemblyResponseTypes.RemoveByKey(assemblyIdentity); + } + + if (_assemblyNetworkProtocols.TryGetValue(assemblyIdentity, out var removeNetworkProtocols)) + { + foreach (var removeNetworkProtocol in removeNetworkProtocols) + { + _networkProtocols.RemoveByKey(removeNetworkProtocol); + } + + _assemblyNetworkProtocols.RemoveByKey(assemblyIdentity); + } + + // 移除程序集对应的消息处理器信息 + if (_assemblyMessageHandlers.TryGetValue(assemblyIdentity, out var removeMessageHandlers)) + { + foreach (var removeMessageHandler in removeMessageHandlers) + { + _messageHandlers.Remove(removeMessageHandler.Type); + } + + _assemblyMessageHandlers.RemoveByKey(assemblyIdentity); + } + + // 如果编译符号FANTASY_NET存在,移除程序集对应的路由消息处理器信息 +#if FANTASY_NET + if (_assemblyRouteMessageHandlers.TryGetValue(assemblyIdentity, out var removeRouteMessageHandlers)) + { + foreach (var removeRouteMessageHandler in removeRouteMessageHandlers) + { + _routeMessageHandlers.Remove(removeRouteMessageHandler.Type); + } + + _assemblyRouteMessageHandlers.RemoveByKey(assemblyIdentity); + } + + if (_assemblyCustomRouteMap.TryGetValue(assemblyIdentity, out var removeCustomRouteMap)) + { + foreach (var removeCustom in removeCustomRouteMap) + { + _customRouteMap.Remove(removeCustom); + } + + _assemblyCustomRouteMap.RemoveByKey(assemblyIdentity); + } +#endif + } + +#if FANTASY_UNITY + /// + /// 手动注册一个消息处理器。 + /// + /// + /// + public void RegisterHandler(MessageDelegate @delegate) where T : IMessage + { + var type = typeof(T); + + if (!_messageDelegateHandlers.TryGetValue(type, out var messageDelegate)) + { + messageDelegate = new MessageDelegateHandler(); + _messageDelegateHandlers.Add(type,messageDelegate); + } + + messageDelegate.Register(@delegate); + } + + /// + /// 手动卸载一个消息处理器,必须是通过RegisterHandler方法注册的消息处理器。 + /// + /// + /// + public void UnRegisterHandler(MessageDelegate @delegate) where T : IMessage + { + var type = typeof(T); + + if (!_messageDelegateHandlers.TryGetValue(type, out var messageDelegate)) + { + return; + } + + if (messageDelegate.UnRegister(@delegate) != 0) + { + return; + } + + _messageDelegateHandlers.Remove(type); + } +#endif + #endregion + + /// + /// 处理普通消息,将消息分发给相应的消息处理器。 + /// + /// 会话对象 + /// 消息类型 + /// 消息对象 + /// RPC标识 + /// 协议码 + public void MessageHandler(Session session, Type type, object message, uint rpcId, uint protocolCode) + { +#if FANTASY_UNITY + if(_messageDelegateHandlers.TryGetValue(type,out var messageDelegateHandler)) + { + messageDelegateHandler.Handle(session, message); + return; + } +#endif + if (!_messageHandlers.TryGetValue(type, out var messageHandler)) + { + Log.Warning($"Scene:{session.Scene.Id} Found Unhandled Message: {message.GetType()}"); + return; + } + + // 调用消息处理器的Handle方法并启动协程执行处理逻辑 + messageHandler.Handle(session, rpcId, protocolCode, message).Coroutine(); + } + + // 如果编译符号FANTASY_NET存在,定义处理路由消息的方法 +#if FANTASY_NET + /// + /// 处理路由消息,将消息分发给相应的路由消息处理器。 + /// + /// 会话对象 + /// 消息类型 + /// 实体对象 + /// 消息对象 + /// RPC标识 + public async FTask RouteMessageHandler(Session session, Type type, Entity entity, object message, uint rpcId) + { + if (!_routeMessageHandlers.TryGetValue(type, out var routeMessageHandler)) + { + Log.Warning($"Scene:{session.Scene.Id} Found Unhandled RouteMessage: {message.GetType()}"); + + if (message is IRouteRequest request) + { + FailRouteResponse(session, request.GetType(), InnerErrorCode.ErrEntityNotFound, rpcId); + } + + return; + } + + var runtimeId = entity.RuntimeId; + var sessionRuntimeId = session.RuntimeId; + + if (entity is Scene) + { + // 如果是Scene的话、就不要加锁了、如果加锁很一不小心就可能会造成死锁 + await routeMessageHandler.Handle(session, entity, rpcId, message); + return; + } + + // 使用协程锁来确保多线程安全 + using (await _receiveRouteMessageLock.Wait(runtimeId)) + { + if (sessionRuntimeId != session.RuntimeId) + { + return; + } + + if (runtimeId != entity.RuntimeId) + { + if (message is IRouteRequest request) + { + FailRouteResponse(session, request.GetType(), InnerErrorCode.ErrEntityNotFound, rpcId); + } + + return; + } + + await routeMessageHandler.Handle(session, entity, rpcId, message); + } + } + + internal bool GetCustomRouteType(long protocolCode, out int routeType) + { + return _customRouteMap.TryGetValue(protocolCode, out routeType); + } +#endif + internal void FailRouteResponse(Session session, Type requestType, uint error, uint rpcId) + { + var response = CreateRouteResponse(requestType, error); + session.Send(response, rpcId); + } + + internal IResponse CreateResponse(Type requestType, uint error) + { + IResponse response; + + if (_responseTypes.TryGetValue(requestType, out var responseType)) + { + response = (IResponse) Activator.CreateInstance(responseType); + } + else + { + response = new Response(); + } + + response.ErrorCode = error; + return response; + } + + internal IRouteResponse CreateRouteResponse(Type requestType, uint error) + { + IRouteResponse response; + + if (_responseTypes.TryGetValue(requestType, out var responseType)) + { + response = (IRouteResponse) Activator.CreateInstance(responseType); + } + else + { + response = new RouteResponse(); + } + + response.ErrorCode = error; + return response; + } + + /// + /// 根据消息类型获取对应的OpCode。 + /// + /// 消息类型 + /// 消息对应的OpCode + public uint GetOpCode(Type type) + { + return _networkProtocols.GetKeyByValue(type); + } + + /// + /// 根据OpCode获取对应的消息类型。 + /// + /// OpCode + /// OpCode对应的消息类型 + public Type GetOpCodeType(uint code) + { + return _networkProtocols.GetValueByKey(code); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta new file mode 100644 index 0000000..2aa6059 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6537629100954864281af135b2d732e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs b/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs new file mode 100644 index 0000000..aea7d08 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs @@ -0,0 +1,95 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 表示通用消息接口。 + /// + public interface IMessage + { + /// + /// 获取消息的操作代码。 + /// + /// 操作代码。 + uint OpCode(); + } + + /// + /// 表示请求消息接口。 + /// + public interface IRequest : IMessage + { + + } + + /// + /// 表示响应消息接口。 + /// + public interface IResponse : IMessage + { + /// + /// 获取或设置错误代码。 + /// + uint ErrorCode { get; set; } + } + // 普通路由消息 + /// + /// 表示普通路由消息的接口,继承自请求接口。 + /// + public interface IRouteMessage : IRequest + { + + } + + /// + /// 普通路由请求接口,继承自普通路由消息接口。 + /// + public interface IRouteRequest : IRouteMessage { } + /// + /// 普通路由响应接口,继承自响应接口。 + /// + public interface IRouteResponse : IResponse { } + // 可寻址协议 + /// + /// 表示可寻址协议的普通路由消息接口,继承自普通路由消息接口。 + /// + public interface IAddressableRouteMessage : IRouteMessage { } + /// + /// 可寻址协议的普通路由请求接口,继承自可寻址协议的普通路由消息接口。 + /// + public interface IAddressableRouteRequest : IRouteRequest { } + /// + /// 可寻址协议的普通路由响应接口,继承自普通路由响应接口。 + /// + public interface IAddressableRouteResponse : IRouteResponse { } + // 自定义Route协议 + public interface ICustomRoute : IMessage + { + int RouteType { get; } + } + /// + /// 表示自定义Route协议的普通路由消息接口,继承自普通路由消息接口。 + /// + public interface ICustomRouteMessage : IRouteMessage, ICustomRoute { } + /// + /// 自定义Route协议的普通路由请求接口,继承自自定义Route协议的普通路由消息接口。 + /// + public interface ICustomRouteRequest : IRouteRequest, ICustomRoute { } + /// + /// 自定义Route协议的普通路由响应接口,继承自普通路由响应接口。 + /// + public interface ICustomRouteResponse : IRouteResponse { } + /// + /// 表示漫游协议的普通路由消息接口,继承自普通路由消息接口。 + /// + public interface IRoamingMessage : IRouteMessage, ICustomRoute { } + /// + /// 漫游协议的普通路由请求接口,继承自自定义Route协议的普通路由消息接口。 + /// + public interface IRoamingRequest : IRoamingMessage { } + /// + /// 漫游协议的普通路由响应接口,继承自普通路由响应接口。 + /// + public interface IRoamingResponse : IRouteResponse { } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs.meta new file mode 100644 index 0000000..2a81279 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/IMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9212aebffde69994388cd84451ff3a7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs b/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs new file mode 100644 index 0000000..643c92b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs @@ -0,0 +1,319 @@ +using Fantasy.Network.Interface; +using Fantasy.Serialize; +using MongoDB.Bson.Serialization.Attributes; +using ProtoBuf; +#if FANTASY_NET +using Fantasy.Network.Roaming; +#endif +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// ReSharper disable InconsistentNaming +// ReSharper disable PropertyCanBeMadeInitOnly.Global +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.InnerMessage +{ + [ProtoContract] + public sealed partial class BenchmarkMessage : AMessage, IMessage + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkMessage; + } + } + [ProtoContract] + public partial class BenchmarkRequest : AMessage, IRequest + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkRequest; + } + [ProtoIgnore] + public BenchmarkResponse ResponseType { get; set; } + [ProtoMember(1)] + public long RpcId { get; set; } + } + + [ProtoContract] + public partial class BenchmarkResponse : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + public sealed partial class Response : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.DefaultResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public sealed partial class RouteResponse : AMessage, IRouteResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.DefaultRouteResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class PingRequest : AMessage, IRequest + { + public uint OpCode() + { + return Fantasy.Network.OpCode.PingRequest; + } + [ProtoIgnore] + public PingResponse ResponseType { get; set; } + [ProtoMember(1)] + public long RpcId { get; set; } + } + + [ProtoContract] + public partial class PingResponse : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.PingResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + [ProtoMember(3)] + public long Now; + } + [ProtoContract] + public partial class I_AddressableAdd_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableAdd_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableAddRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + [ProtoMember(2)] + public long RouteId { get; set; } + [ProtoMember(3)] + public bool IsLock { get; set; } + } + [ProtoContract] + public partial class I_AddressableAdd_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableAddResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableGet_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableGet_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableGetRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableGet_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableGetResponse; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + [ProtoMember(1)] + public long RouteId { get; set; } + } + [ProtoContract] + public partial class I_AddressableRemove_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableRemove_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableRemoveRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableRemove_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableRemoveResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableLock_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableLock_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableLockRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableLock_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableLockResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableUnLock_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableUnLock_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableUnLockRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + [ProtoMember(2)] + public long RouteId { get; set; } + [ProtoMember(3)] + public string Source { get; set; } + } + [ProtoContract] + public partial class I_AddressableUnLock_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableUnLockResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } +#if FANTASY_NET + [ProtoContract] + public sealed class I_LinkRoamingRequest : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_LinkRoamingResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.LinkRoamingRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long RoamingId { get; set; } + [ProtoMember(2)] + public int RoamingType { get; set; } + [ProtoMember(3)] + public long ForwardSessionRouteId { get; set; } + [ProtoMember(4)] + public long SceneRouteId { get; set; } + } + [ProtoContract] + public sealed class I_LinkRoamingResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.LinkRoamingResponse; } + [ProtoMember(1)] + public long TerminusId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public sealed class I_UnLinkRoamingRequest : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_UnLinkRoamingResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.UnLinkRoamingRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long RoamingId { get; set; } + [ProtoMember(2)] + public bool DisposeRoaming { get; set; } + } + [ProtoContract] + public sealed class I_UnLinkRoamingResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.UnLinkRoamingResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_LockTerminusIdRequest : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_LockTerminusIdResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.LockTerminusIdRequest; } + [ProtoMember(1)] + public long SessionRuntimeId { get; set; } + [ProtoMember(2)] + public int RoamingType { get; set; } + } + [ProtoContract] + public partial class I_LockTerminusIdResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.LockTerminusIdResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public sealed class I_UnLockTerminusIdRequest : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_UnLockTerminusIdResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.UnLockTerminusIdRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long SessionRuntimeId { get; set; } + [ProtoMember(2)] + public int RoamingType { get; set; } + [ProtoMember(3)] + public long TerminusId { get; set; } + [ProtoMember(4)] + public long TargetSceneRouteId { get; set; } + } + [ProtoContract] + public sealed class I_UnLockTerminusIdResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.UnLockTerminusIdResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + /// + /// 漫游传送终端的请求 + /// + public partial class I_TransferTerminusRequest : AMessage, IRouteRequest + { + [BsonIgnore] + public I_TransferTerminusResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.TransferTerminusRequest; } + public Terminus Terminus { get; set; } + } + public partial class I_TransferTerminusResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.TransferTerminusResponse; } + public uint ErrorCode { get; set; } + } + /// + /// 用于服务器之间获取漫游的TerminusId。 + /// + [ProtoContract] + public partial class I_GetTerminusIdRequest : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_GetTerminusIdResponse ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.GetTerminusIdRequest; } + [ProtoMember(1)] + public int RoamingType { get; set; } + [ProtoMember(2)] + public long SessionRuntimeId { get; set; } + } + [ProtoContract] + public partial class I_GetTerminusIdResponse : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.GetTerminusIdResponse; } + [ProtoMember(1)] + public long TerminusId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } +#endif +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs.meta new file mode 100644 index 0000000..6ca33ee --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/InnerMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4194a58bd97a63a4d8e6d5589c877488 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser.meta new file mode 100644 index 0000000..a47dfcb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 34916bf7b508ced4dac44f9d7898c2c0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler.meta new file mode 100644 index 0000000..a97718c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dcdc78c9c51d2d548bdaf8dcee224fd6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs new file mode 100644 index 0000000..7441ee8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs @@ -0,0 +1,392 @@ +using System; +using System.Buffers; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.PacketParser +{ + /// + /// BufferPacketParser消息格式化器抽象类 + /// 这个不会用在TCP协议中、因此不用考虑分包和粘包的问题。 + /// 目前这个只会用在KCP协议中、因为KCP出来的就是一个完整的包、所以可以一次性全部解析出来。 + /// 如果是用在其他协议上可能会出现问题。 + /// + public abstract class BufferPacketParser : APacketParser + { + protected uint RpcId; + protected long RouteId; + protected uint ProtocolCode; + protected int MessagePacketLength; + public override void Dispose() + { + RpcId = 0; + RouteId = 0; + ProtocolCode = 0; + MessagePacketLength = 0; + base.Dispose(); + } + /// + /// 解包方法 + /// + /// buffer + /// count + /// packInfo + /// + public abstract bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo); + } +#if FANTASY_NET + /// + /// 服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class InnerBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override unsafe bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.InnerPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + var span = buffer.AsSpan(); + ref var bufferRef = ref MemoryMarshal.GetReference(span); + + MessagePacketLength = Unsafe.ReadUnaligned(ref bufferRef); + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength)); + RpcId = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation)); + RouteId = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRouteRouteIdLocation)); + + packInfo = InnerPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.RouteId = RouteId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, ref routeId, message) : Pack(ref rpcId, ref routeId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer(); + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); + + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation), rpcId); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRouteRouteIdLocation), routeId); + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); + + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation), rpcId); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRouteRouteIdLocation), routeId); + + return memoryStream; + } + } +#endif + /// + /// 客户端和服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class OuterBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.OuterPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + var span = buffer.AsSpan(); + ref var bufferRef = ref MemoryMarshal.GetReference(span); + + MessagePacketLength = Unsafe.ReadUnaligned(ref bufferRef); + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength)); + RpcId = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation)); + + packInfo = OuterPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer(); +#if FANTASY_UNITY + ref var bufferRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); +#else + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); +#endif + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation), rpcId); + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); +#if FANTASY_UNITY + ref var bufferRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); +#else + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); +#endif + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation), rpcId); + + return memoryStream; + } + } + /// + /// Webgl专用的客户端和服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class OuterWebglBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.OuterPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + var span = buffer.AsSpan(); + ref var bufferRef = ref MemoryMarshal.GetReference(span); + + MessagePacketLength = Unsafe.ReadUnaligned(ref bufferRef); + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength)); + RpcId = Unsafe.ReadUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation)); + + packInfo = OuterPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer().AsSpan(); +#if FANTASY_NET + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), in rpcId); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), ref rpcId); +#endif + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.UnPack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); +#if FANTASY_UNITY + ref var bufferRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); +#else + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); +#endif + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation), rpcId); + return memoryStream; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta new file mode 100644 index 0000000..8a38f70 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d46abd6856426794bb7ff68190a2397f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs new file mode 100644 index 0000000..24c368b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs @@ -0,0 +1,170 @@ +// using System.Runtime.CompilerServices; +// // ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// +// namespace Fantasy +// { +// // 这个对处理分包和粘包逻辑不完整、考虑现在没有任何地方使用了、就先不修改了。 +// // 后面用到了再修改、现在这个只是留做备份、万一以后用到了呢。 +// public abstract class CircularBufferPacketParser : APacketParser +// { +// protected uint RpcId; +// protected long RouteId; +// protected uint ProtocolCode; +// protected int MessagePacketLength; +// protected bool IsUnPackHead = true; +// protected readonly byte[] MessageHead = new byte[Packet.InnerPacketHeadLength]; +// public abstract bool UnPack(CircularBuffer buffer, out APackInfo packInfo); +// } +// +// #if FANTASY_NET +// public sealed class InnerCircularBufferPacketParser : CircularBufferPacketParser, IInnerPacketParser +// { +// public override bool UnPack(CircularBuffer buffer, out APackInfo packInfo) +// { +// packInfo = null; +// +// // 在对象没有被释放的情况下循环解析数据 +// while (!IsDisposed) +// { +// if (IsUnPackHead) +// { +// // 如果缓冲区中的数据长度小于内部消息头的长度,无法解析 +// if (buffer.Length < Packet.InnerPacketHeadLength) +// { +// return false; +// } +// +// // 从缓冲区中读取内部消息头的数据 +// _ = buffer.Read(MessageHead, 0, Packet.InnerPacketHeadLength); +// MessagePacketLength = BitConverter.ToInt32(MessageHead, 0); +// +// // 检查消息体长度是否超出限制 +// if (MessagePacketLength > Packet.PacketBodyMaxLength) +// { +// throw new ScanException( +// $"The received information exceeds the maximum limit = {MessagePacketLength}"); +// } +// +// // 解析协议编号、RPC ID 和 Route ID +// ProtocolCode = BitConverter.ToUInt32(MessageHead, Packet.PacketLength); +// RpcId = BitConverter.ToUInt32(MessageHead, Packet.InnerPacketRpcIdLocation); +// RouteId = BitConverter.ToInt64(MessageHead, Packet.InnerPacketRouteRouteIdLocation); +// IsUnPackHead = false; +// } +// +// try +// { +// // 如果缓冲区中的数据长度小于消息体的长度,无法解析 +// if (MessagePacketLength < 0 || buffer.Length < MessagePacketLength) +// { +// return false; +// } +// +// IsUnPackHead = true; +// packInfo = InnerPackInfo.Create(Network); +// var memoryStream = packInfo.RentMemoryStream(MessagePacketLength); +// memoryStream.SetLength(MessagePacketLength); +// buffer.Read(memoryStream, MessagePacketLength); +// packInfo.RpcId = RpcId; +// packInfo.RouteId = RouteId; +// packInfo.ProtocolCode = ProtocolCode; +// packInfo.MessagePacketLength = MessagePacketLength; +// return true; +// } +// catch (Exception e) +// { +// // 在发生异常时,释放 packInfo 并记录日志 +// packInfo?.Dispose(); +// Log.Error(e); +// return false; +// } +// } +// +// return false; +// } +// +// public override MemoryStream Pack(ref uint rpcId, ref long routeTypeOpCode, ref long routeId, +// MemoryStream memoryStream, object message) +// { +// return memoryStream == null +// ? Pack(ref rpcId, ref routeId, message) +// : Pack(ref rpcId, ref routeId, memoryStream); +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private unsafe MemoryStream Pack(ref uint rpcId, ref long routeId, MemoryStream memoryStream) +// { +// var buffer = memoryStream.GetBuffer(); +// +// fixed (byte* bufferPtr = buffer) +// { +// var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; +// var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; +// *(uint*)rpcIdPtr = rpcId; +// *(long*)routeIdPtr = routeId; +// } +// +// memoryStream.Seek(0, SeekOrigin.Begin); +// return memoryStream; +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private unsafe MemoryStream Pack(ref uint rpcId, ref long routeId, object message) +// { +// var memoryStream = Network.RentMemoryStream(); +// memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); +// +// switch (message) +// { +// case IBsonMessage: +// { +// MongoHelper.SerializeTo(message, memoryStream); +// break; +// } +// default: +// { +// ProtoBuffHelper.ToStream(message, memoryStream); +// break; +// } +// } +// +// var opCode = Scene.MessageDispatcherComponent.GetOpCode(message.GetType()); +// var packetBodyCount = (int)(memoryStream.Position - Packet.InnerPacketHeadLength); +// +// if (packetBodyCount == 0) +// { +// // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 +// // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 +// packetBodyCount = -1; +// } +// +// // 检查消息体长度是否超出限制 +// if (packetBodyCount > Packet.PacketBodyMaxLength) +// { +// throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); +// } +// +// var buffer = memoryStream.GetBuffer(); +// +// fixed (byte* bufferPtr = buffer) +// { +// var opCodePtr = bufferPtr + Packet.PacketLength; +// var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; +// var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; +// *(int*)bufferPtr = packetBodyCount; +// *(uint*)opCodePtr = opCode; +// *(uint*)rpcIdPtr = rpcId; +// *(long*)routeIdPtr = routeId; +// } +// +// memoryStream.Seek(0, SeekOrigin.Begin); +// return memoryStream; +// } +// } +// #endif +// } +// +// +// +// diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta new file mode 100644 index 0000000..c8ab6c6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c1d524a15b1dd6448b98b2e288d1b35 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs new file mode 100644 index 0000000..80d52b5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs @@ -0,0 +1,73 @@ +#if FANTASY_NET +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +namespace Fantasy.PacketParser +{ + /// + /// 打包Outer消息的帮助类 + /// + public static class OuterBufferPacketParserHelper + { + /// + /// 打包一个网络消息 + /// + /// scene + /// 如果是RPC消息需要传递一个rpcId + /// 打包的网络消息 + /// 序列化后流的长度 + /// 打包完成会返回一个MemoryStreamBuffer + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static MemoryStreamBuffer Pack(Scene scene, uint rpcId, IMessage message, out int memoryStreamLength) + { + memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = new MemoryStreamBuffer(); + memoryStream.MemoryStreamBufferSource = MemoryStreamBufferSource.Pack; + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); + + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation), rpcId); + + return memoryStream; + } + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta new file mode 100644 index 0000000..e9f10e2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 652fe619fcc63054e8cfe961ada5dc3a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs new file mode 100644 index 0000000..cd57fdd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs @@ -0,0 +1,376 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.PacketParser +{ + internal abstract class ReadOnlyMemoryPacketParser : APacketParser + { + /// + /// 一个网络消息包 + /// + protected APackInfo PackInfo; + + protected int Offset; + protected int MessageHeadOffset; + protected int MessageBodyOffset; + protected int MessagePacketLength; + protected bool IsUnPackHead = true; + protected readonly byte[] MessageHead = new byte[20]; + public ReadOnlyMemoryPacketParser() { } + + public abstract bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo); + + public override void Dispose() + { + Offset = 0; + MessageHeadOffset = 0; + MessageBodyOffset = 0; + MessagePacketLength = 0; + IsUnPackHead = true; + PackInfo = null; + Array.Clear(MessageHead, 0, 20); + base.Dispose(); + } + } + +#if FANTASY_NET + internal sealed class InnerReadOnlyMemoryPacketParser : ReadOnlyMemoryPacketParser + { + public override bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo) + { + packInfo = null; + var readOnlySpan = buffer.Span; + var bufferLength = buffer.Length - Offset; + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + if (IsUnPackHead) + { + // 在当前buffer中拿到包头的数据 + var innerPacketHeadLength = Packet.InnerPacketHeadLength - MessageHeadOffset; + var copyLength = Math.Min(bufferLength, innerPacketHeadLength); + + readOnlySpan.Slice(Offset, copyLength).CopyTo(MessageHead.AsSpan(MessageHeadOffset, copyLength)); + + Offset += copyLength; + MessageHeadOffset += copyLength; + // 检查是否有完整包头 + if (MessageHeadOffset == Packet.InnerPacketHeadLength) + { + // 通过现代API直接读取协议编号、messagePacketLength protocolCode rpcId routeId + ref var messageRef = ref MemoryMarshal.GetArrayDataReference(MessageHead); + MessagePacketLength = Unsafe.ReadUnaligned(ref messageRef); + // 检查消息体长度是否超出限制 + if (MessagePacketLength > Packet.PacketBodyMaxLength) + { + throw new ScanException( + $"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + PackInfo = InnerPackInfo.Create(Network); + var memoryStream = PackInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, + Packet.InnerPacketHeadLength + MessagePacketLength); + PackInfo.RpcId = + Unsafe.ReadUnaligned(ref Unsafe.Add(ref messageRef, Packet.InnerPacketRpcIdLocation)); + PackInfo.ProtocolCode = + Unsafe.ReadUnaligned(ref Unsafe.Add(ref messageRef, Packet.PacketLength)); + PackInfo.RouteId = + Unsafe.ReadUnaligned(ref Unsafe.Add(ref messageRef, + Packet.InnerPacketRouteRouteIdLocation)); + memoryStream.Write(MessageHead); + IsUnPackHead = false; + bufferLength -= copyLength; + MessageHeadOffset = 0; + } + else + { + Offset = 0; + return false; + } + } + + if (MessagePacketLength == -1) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + return true; + } + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + // 处理包消息体 + var innerPacketBodyLength = MessagePacketLength - MessageBodyOffset; + var copyBodyLength = Math.Min(bufferLength, innerPacketBodyLength); + // 写入数据到消息体中 + PackInfo.MemoryStream.Write(readOnlySpan.Slice(Offset, copyBodyLength)); + Offset += copyBodyLength; + MessageBodyOffset += copyBodyLength; + // 检查是否是完整的消息体 + if (MessageBodyOffset == MessagePacketLength) + { + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + MessageBodyOffset = 0; + return true; + } + + Offset = 0; + return false; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, ref routeId, message) : Pack(ref rpcId, ref routeId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer(); + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); + + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation), rpcId); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRouteRouteIdLocation), routeId); + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + // 其实可以不用设置-1、解包的时候判断如果是0也可以、但我仔细想了下,还是用-1代表更加清晰。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); + + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRpcIdLocation), rpcId); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.InnerPacketRouteRouteIdLocation), routeId); + + return memoryStream; + } + } +#endif + internal sealed class OuterReadOnlyMemoryPacketParser : ReadOnlyMemoryPacketParser + { + public override bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo) + { + packInfo = null; + var readOnlySpan = buffer.Span; + var bufferLength = buffer.Length - Offset; + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + if (IsUnPackHead) + { + // 在当前buffer中拿到包头的数据 + var outerPacketHeadLength = Packet.OuterPacketHeadLength - MessageHeadOffset; + var copyLength = Math.Min(bufferLength, outerPacketHeadLength); + + readOnlySpan.Slice(Offset, copyLength).CopyTo(MessageHead.AsSpan(MessageHeadOffset, copyLength)); + + Offset += copyLength; + MessageHeadOffset += copyLength; + // 检查是否有完整包头 + if (MessageHeadOffset == Packet.OuterPacketHeadLength) + { + // 通过现代API直接读取协议编号、messagePacketLength protocolCode rpcId routeId +#if FANTASY_UNITY + ref var messageRef = ref MemoryMarshal.GetReference(buffer.Span); +#else + ref var messageRef = ref MemoryMarshal.GetArrayDataReference(MessageHead); +#endif + MessagePacketLength = Unsafe.ReadUnaligned(ref messageRef); + // 检查消息体长度是否超出限制 + if (MessagePacketLength > Packet.PacketBodyMaxLength) + { + throw new ScanException( + $"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + PackInfo = OuterPackInfo.Create(Network); + PackInfo.ProtocolCode = + Unsafe.ReadUnaligned(ref Unsafe.Add(ref messageRef, Packet.PacketLength)); + PackInfo.RpcId = + Unsafe.ReadUnaligned(ref Unsafe.Add(ref messageRef, Packet.OuterPacketRpcIdLocation)); + var memoryStream = PackInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, + Packet.OuterPacketHeadLength + MessagePacketLength); + memoryStream.Write(MessageHead); + IsUnPackHead = false; + bufferLength -= copyLength; + MessageHeadOffset = 0; + } + else + { + Offset = 0; + return false; + } + } + + if (MessagePacketLength == -1) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + return true; + } + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + // 处理包消息体 + var outerPacketBodyLength = MessagePacketLength - MessageBodyOffset; + var copyBodyLength = Math.Min(bufferLength, outerPacketBodyLength); + // 写入数据到消息体中 + PackInfo.MemoryStream.Write(readOnlySpan.Slice(Offset, copyBodyLength)); + Offset += copyBodyLength; + MessageBodyOffset += copyBodyLength; + // 检查是否是完整的消息体 + if (MessageBodyOffset == MessagePacketLength) + { + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + MessageBodyOffset = 0; + return true; + } + + Offset = 0; + return false; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer(); +#if FANTASY_UNITY + ref var bufferRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); +#else + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); +#endif + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation), rpcId); + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); +#if FANTASY_UNITY + ref var bufferRef = ref MemoryMarshal.GetReference(buffer.AsSpan()); +#else + ref var bufferRef = ref MemoryMarshal.GetArrayDataReference(buffer); +#endif + Unsafe.WriteUnaligned(ref bufferRef, packetBodyCount); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.PacketLength), opCode); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref bufferRef, Packet.OuterPacketRpcIdLocation), rpcId); + + return memoryStream; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta new file mode 100644 index 0000000..7b43c1d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9f744f826366eee4daf8d5b433b74e77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface.meta new file mode 100644 index 0000000..b3e084d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8091e658c33ebb74fb22cdee862efad2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs new file mode 100644 index 0000000..1ea6d6b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.PacketParser.Interface +{ + public abstract class APackInfo : IDisposable + { + internal ANetwork Network; + + public uint RpcId; + public long RouteId; + public long PackInfoId; + public bool IsDisposed; + private uint _protocolCode; + + public uint ProtocolCode + { + get => _protocolCode; + set + { + _protocolCode = value; + OpCodeIdStruct = value; + } + } + public OpCodeIdStruct OpCodeIdStruct { get; private set; } + public MemoryStreamBuffer MemoryStream { get; protected set; } + public abstract object Deserialize(Type messageType); + public abstract MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0); + public virtual void Dispose() + { + if (IsDisposed) + { + return; + } + + RpcId = 0; + RouteId = 0; + PackInfoId = 0; + ProtocolCode = 0; + _protocolCode = 0; + OpCodeIdStruct = default; + + if (MemoryStream != null) + { + Network.MemoryStreamBufferPool.ReturnMemoryStream(MemoryStream); + MemoryStream = null; + } + + IsDisposed = true; + Network = null; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta new file mode 100644 index 0000000..750ddc1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 045aa8d1bc6e44c49a81e00777b6a9ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs new file mode 100644 index 0000000..579cf6f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs @@ -0,0 +1,30 @@ +using System; +using System.Buffers; +using System.IO; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.PacketParser.Interface +{ + /// + /// 抽象的包解析器基类,用于解析网络通信数据包。 + /// + public abstract class APacketParser : IDisposable + { + internal Scene Scene; + internal ANetwork Network; + internal MessageDispatcherComponent MessageDispatcherComponent; + protected bool IsDisposed { get; private set; } + public abstract MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message); + public virtual void Dispose() + { + IsDisposed = true; + Scene = null; + MessageDispatcherComponent = null; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta new file mode 100644 index 0000000..76118e4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87dda8f636461c64e82d15409d3cd2c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs new file mode 100644 index 0000000..27c5dbb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs @@ -0,0 +1,125 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network +{ + public struct OpCodeIdStruct + { + // OpCodeIdStruct:5 + 4 + 23 = 32 + // +-------------------------+-------------------------------------------+-----------------------------+ + // | protocol(5) 最多31种类型 | OpCodeProtocolType(4) 最多15种不同的网络协议 | Index(23) 最多8388607个协议 | + // +-------------------------+-------------------------------------------+-----------------------------+ + public uint OpCodeProtocolType { get; private set; } + public uint Protocol { get; private set; } + public uint Index { get; private set; } + + public OpCodeIdStruct(uint opCodeProtocolType, uint protocol, uint index) + { + OpCodeProtocolType = opCodeProtocolType; + Protocol = protocol; + Index = index; + } + + public static implicit operator uint(OpCodeIdStruct opCodeIdStruct) + { + var result = opCodeIdStruct.Index; + result |= opCodeIdStruct.OpCodeProtocolType << 23; + result |= opCodeIdStruct.Protocol << 27; + return result; + } + + public static implicit operator OpCodeIdStruct(uint opCodeId) + { + var opCodeIdStruct = new OpCodeIdStruct() + { + Index = opCodeId & 0x7FFFFF + }; + opCodeId >>= 23; + opCodeIdStruct.OpCodeProtocolType = opCodeId & 0xF; + opCodeId >>= 4; + opCodeIdStruct.Protocol = opCodeId & 0x1F; + return opCodeIdStruct; + } + } + + public static class OpCodeProtocolType + { + public const uint Bson = 1; + public const uint ProtoBuf = 0; + } + + public static class OpCodeType + { + public const uint OuterMessage = 1; + public const uint OuterRequest = 2; + public const uint OuterResponse = 3; + + public const uint InnerMessage = 4; + public const uint InnerRequest = 5; + public const uint InnerResponse = 6; + + public const uint InnerRouteMessage = 7; + public const uint InnerRouteRequest = 8; + public const uint InnerRouteResponse = 9; + + public const uint OuterAddressableMessage = 10; + public const uint OuterAddressableRequest = 11; + public const uint OuterAddressableResponse = 12; + + public const uint InnerAddressableMessage = 13; + public const uint InnerAddressableRequest = 14; + public const uint InnerAddressableResponse = 15; + + public const uint OuterCustomRouteMessage = 16; + public const uint OuterCustomRouteRequest = 17; + public const uint OuterCustomRouteResponse = 18; + + public const uint OuterRoamingMessage = 19; + public const uint OuterRoamingRequest = 20; + public const uint OuterRoamingResponse = 21; + + public const uint InnerRoamingMessage = 22; + public const uint InnerRoamingRequest = 23; + public const uint InnerRoamingResponse = 24; + + public const uint OuterPingRequest = 30; + public const uint OuterPingResponse = 31; + } + + public static class OpCode + { + public static readonly uint BenchmarkMessage = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterMessage, 8388607); + public static readonly uint BenchmarkRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterRequest, 8388607); + public static readonly uint BenchmarkResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterResponse, 8388607); + public static readonly uint PingRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterPingRequest, 1); + public static readonly uint PingResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterPingResponse, 1); + public static readonly uint DefaultResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerResponse, 1); + public static readonly uint DefaultRouteResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 7); + public static readonly uint AddressableAddRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 1); + public static readonly uint AddressableAddResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 1); + public static readonly uint AddressableGetRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 2); + public static readonly uint AddressableGetResponse = Create(OpCodeProtocolType.ProtoBuf,OpCodeType.InnerRouteResponse,2); + public static readonly uint AddressableRemoveRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 3); + public static readonly uint AddressableRemoveResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 3); + public static readonly uint AddressableLockRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 4); + public static readonly uint AddressableLockResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 4); + public static readonly uint AddressableUnLockRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 5); + public static readonly uint AddressableUnLockResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 5); + public static readonly uint LinkRoamingRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 6); + public static readonly uint LinkRoamingResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 6); + public static readonly uint UnLinkRoamingRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 8); + public static readonly uint UnLinkRoamingResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 8); + public static readonly uint LockTerminusIdRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 9); + public static readonly uint LockTerminusIdResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 9); + public static readonly uint UnLockTerminusIdRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 10); + public static readonly uint UnLockTerminusIdResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 10); + public static readonly uint GetTerminusIdRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 11); + public static readonly uint GetTerminusIdResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 11); + + public static readonly uint TransferTerminusRequest = Create(OpCodeProtocolType.Bson, OpCodeType.InnerRouteRequest, 1); + public static readonly uint TransferTerminusResponse = Create(OpCodeProtocolType.Bson, OpCodeType.InnerRouteResponse, 1); + + public static uint Create(uint opCodeProtocolType, uint protocol, uint index) + { + return new OpCodeIdStruct(opCodeProtocolType, protocol, index); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs.meta new file mode 100644 index 0000000..e69adf7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/OpCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dcffa6e04bf055e44a15355095c52e70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack.meta new file mode 100644 index 0000000..df7b590 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 05517789a7d230543ade9ee0d3d29488 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs new file mode 100644 index 0000000..e9870e7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs @@ -0,0 +1,79 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +#if FANTASY_NET +namespace Fantasy.PacketParser +{ + public sealed class InnerPackInfo : APackInfo + { + private readonly Dictionary> _createInstances = new Dictionary>(); + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + var network = Network; + base.Dispose(); + network.ReturnInnerPackInfo(this); + } + + public static InnerPackInfo Create(ANetwork network) + { + var innerPackInfo = network.RentInnerPackInfo(); + innerPackInfo.Network = network; + innerPackInfo.IsDisposed = false; + return innerPackInfo; + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + return MemoryStream ??= Network.MemoryStreamBufferPool.RentMemoryStream(memoryStreamBufferSource, size); + } + + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + MemoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (MemoryStream.Length == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.Add(messageType, createInstance); + return createInstance(); + } + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + var obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta new file mode 100644 index 0000000..7cd5c4c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9aeda9c6b2ff48449911c77dc70bcb0b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs new file mode 100644 index 0000000..8ce08b7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs @@ -0,0 +1,73 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System; +using System.IO; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +namespace Fantasy.PacketParser +{ + public sealed class OuterPackInfo : APackInfo + { + public override void Dispose() + { + if (IsDisposed) + { + return; + } + var network = Network; + base.Dispose(); + network.ReturnOuterPackInfo(this); + } + + public static OuterPackInfo Create(ANetwork network) + { + var outerPackInfo = network.RentOuterPackInfo(); + outerPackInfo.Network = network; + outerPackInfo.IsDisposed = false; + return outerPackInfo; + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + if (MemoryStream == null) + { + MemoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(memoryStreamBufferSource, size); + } + + return MemoryStream; + } + + /// + /// 将消息数据从内存反序列化为指定的消息类型实例。 + /// + /// 目标消息类型。 + /// 反序列化后的消息类型实例。 + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + MemoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + var obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta new file mode 100644 index 0000000..75eb99f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36a00cda82cbc5f49a8ddef8ce4c8ce5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs new file mode 100644 index 0000000..f010858 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs @@ -0,0 +1,160 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.PacketParser +{ + public sealed class ProcessPackInfo : APackInfo + { + private int _disposeCount; + public Type MessageType { get; private set; } + private static readonly ConcurrentQueue Caches = new ConcurrentQueue(); + private readonly ConcurrentDictionary> _createInstances = new ConcurrentDictionary>(); + + public override void Dispose() + { + if (--_disposeCount > 0 || IsDisposed) + { + return; + } + + _disposeCount = 0; + MessageType = null; + base.Dispose(); + + if (Caches.Count > 2000) + { + return; + } + + Caches.Enqueue(this); + } + + public static unsafe ProcessPackInfo Create(Scene scene, T message, int disposeCount, uint rpcId = 0, long routeId = 0) where T : IRouteMessage + { + if (!Caches.TryDequeue(out var packInfo)) + { + packInfo = new ProcessPackInfo(); + } + + var type = typeof(T); + var memoryStreamLength = 0; + packInfo._disposeCount = disposeCount; + packInfo.MessageType = type; + packInfo.IsDisposed = false; + var memoryStream = new MemoryStreamBuffer(); + memoryStream.MemoryStreamBufferSource = MemoryStreamBufferSource.Pack; + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(type, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{type} Does not support processing protocol"); + } + + var opCode = scene.MessageDispatcherComponent.GetOpCode(packInfo.MessageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); + + fixed (byte* bufferPtr = buffer) + { + var opCodePtr = bufferPtr + Packet.PacketLength; + var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; + var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; + *(int*)bufferPtr = packetBodyCount; + *(uint*)opCodePtr = opCode; + *(uint*)rpcIdPtr = rpcId; + *(long*)routeIdPtr = routeId; + } + + memoryStream.Seek(0, SeekOrigin.Begin); + packInfo.MemoryStream = memoryStream; + return packInfo; + } + + public unsafe void Set(uint rpcId, long routeId) + { + var buffer = MemoryStream.GetBuffer(); + + fixed (byte* bufferPtr = buffer) + { + var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; + var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; + *(uint*)rpcIdPtr = rpcId; + *(long*)routeIdPtr = routeId; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + throw new NotImplementedException(); + } + + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + object obj = null; + MemoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (MemoryStream.Length == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.TryAdd(messageType, createInstance); + return createInstance(); + } + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta new file mode 100644 index 0000000..4885206 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4bac18e4bcab355419c075af9a7b8017 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs new file mode 100644 index 0000000..7198af7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs @@ -0,0 +1,49 @@ +namespace Fantasy.PacketParser +{ + /// + /// 提供关于消息包的常量定义。 + /// + public struct Packet + { + /// + /// 消息体最大长度 + /// + public const int PacketBodyMaxLength = ushort.MaxValue * 16; + /// + /// 消息体长度在消息头占用的长度 + /// + public const int PacketLength = sizeof(int); + /// + /// 协议编号在消息头占用的长度 + /// + public const int ProtocolCodeLength = sizeof(uint); + /// + /// RouteId长度 + /// + public const int PacketRouteIdLength = sizeof(long); + /// + /// RpcId在消息头占用的长度 + /// + public const int RpcIdLength = sizeof(uint); + /// + /// OuterRPCId所在的位置 + /// + public const int OuterPacketRpcIdLocation = PacketLength + ProtocolCodeLength; + /// + /// InnerRPCId所在的位置 + /// + public const int InnerPacketRpcIdLocation = PacketLength + ProtocolCodeLength; + /// + /// RouteId所在的位置 + /// + public const int InnerPacketRouteRouteIdLocation = PacketLength + ProtocolCodeLength + RpcIdLength; + /// + /// 外网消息头长度(消息体长度在消息头占用的长度 + 协议编号在消息头占用的长度 + RPCId长度 + RouteId长度) + /// + public const int OuterPacketHeadLength = PacketLength + ProtocolCodeLength + RpcIdLength + PacketRouteIdLength; + /// + /// 内网消息头长度(消息体长度在消息头占用的长度 + 协议编号在消息头占用的长度 + RPCId长度 + RouteId长度) + /// + public const int InnerPacketHeadLength = PacketLength + ProtocolCodeLength + RpcIdLength + PacketRouteIdLength; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs.meta new file mode 100644 index 0000000..75c10f2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/Packet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b95488856bca4ba468419280bfcc699a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs new file mode 100644 index 0000000..679f95d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs @@ -0,0 +1,173 @@ +using System; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; + +// ReSharper disable PossibleNullReferenceException +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.PacketParser +{ + internal static class PacketParserFactory + { +#if FANTASY_NET + internal static ReadOnlyMemoryPacketParser CreateServerReadOnlyMemoryPacket(ANetwork network) + { + ReadOnlyMemoryPacketParser readOnlyMemoryPacketParser = null; + + switch (network.NetworkTarget) + { + case NetworkTarget.Inner: + { + readOnlyMemoryPacketParser = new InnerReadOnlyMemoryPacketParser(); + break; + } + case NetworkTarget.Outer: + { + readOnlyMemoryPacketParser = new OuterReadOnlyMemoryPacketParser(); + break; + } + } + + readOnlyMemoryPacketParser.Scene = network.Scene; + readOnlyMemoryPacketParser.Network = network; + readOnlyMemoryPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return readOnlyMemoryPacketParser; + } + + public static BufferPacketParser CreateServerBufferPacket(ANetwork network) + { + BufferPacketParser bufferPacketParser = null; + + switch (network.NetworkTarget) + { + case NetworkTarget.Inner: + { + bufferPacketParser = new InnerBufferPacketParser(); + break; + } + case NetworkTarget.Outer: + { + bufferPacketParser = new OuterBufferPacketParser(); + break; + } + } + + bufferPacketParser.Scene = network.Scene; + bufferPacketParser.Network = network; + bufferPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return bufferPacketParser; + } +#endif + internal static ReadOnlyMemoryPacketParser CreateClientReadOnlyMemoryPacket(ANetwork network) + { + ReadOnlyMemoryPacketParser readOnlyMemoryPacketParser = null; + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + readOnlyMemoryPacketParser = new InnerReadOnlyMemoryPacketParser(); + break; + } +#endif + case NetworkTarget.Outer: + { + readOnlyMemoryPacketParser = new OuterReadOnlyMemoryPacketParser(); + break; + } + } + + readOnlyMemoryPacketParser.Scene = network.Scene; + readOnlyMemoryPacketParser.Network = network; + readOnlyMemoryPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return readOnlyMemoryPacketParser; + } + +#if !FANTASY_WEBGL + public static BufferPacketParser CreateClientBufferPacket(ANetwork network) + { + BufferPacketParser bufferPacketParser = null; + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + bufferPacketParser = new InnerBufferPacketParser(); + break; + } +#endif + case NetworkTarget.Outer: + { + bufferPacketParser = new OuterBufferPacketParser(); + break; + } + } + + bufferPacketParser.Scene = network.Scene; + bufferPacketParser.Network = network; + bufferPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return bufferPacketParser; + } +#endif + public static T CreateClient(ANetwork network) where T : APacketParser + { + var packetParserType = typeof(T); + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + APacketParser innerPacketParser = null; + + if (packetParserType == typeof(ReadOnlyMemoryPacketParser)) + { + innerPacketParser = new InnerReadOnlyMemoryPacketParser(); + } + else if (packetParserType == typeof(BufferPacketParser)) + { + innerPacketParser = new InnerBufferPacketParser(); + } + // else if(packetParserType == typeof(CircularBufferPacketParser)) + // { + // innerPacketParser = new InnerCircularBufferPacketParser(); + // } + + innerPacketParser.Scene = network.Scene; + innerPacketParser.Network = network; + innerPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return (T)innerPacketParser; + } +#endif + case NetworkTarget.Outer: + { + APacketParser outerPacketParser = null; + + if (packetParserType == typeof(ReadOnlyMemoryPacketParser)) + { + outerPacketParser = new OuterReadOnlyMemoryPacketParser(); + } + else if (packetParserType == typeof(BufferPacketParser)) + { +#if FANTASY_WEBGL + outerPacketParser = new OuterWebglBufferPacketParser(); +#else + outerPacketParser = new OuterBufferPacketParser(); +#endif + } + outerPacketParser.Scene = network.Scene; + outerPacketParser.Network = network; + outerPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return (T)outerPacketParser; + } + default: + throw new ArgumentOutOfRangeException(); + } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta new file mode 100644 index 0000000..0a6b58c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7170905e7ca56204ca12fce800c2ae34 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler.meta new file mode 100644 index 0000000..b3a3c42 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fbb3ed5849f2c4d4bb754d096e8fb3fa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs new file mode 100644 index 0000000..baf981a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs @@ -0,0 +1,96 @@ +using System; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Scheduler +{ +#if FANTASY_UNITY || FANTASY_CONSOLE + /// + /// 提供了一个用于客户端网络消息调度和处理的抽象基类。 + /// + public sealed class ClientMessageScheduler : ANetworkMessageScheduler + { + public ClientMessageScheduler(Scene scene) : base(scene) { } + + public override async FTask Scheduler(Session session, APackInfo packInfo) + { + await FTask.CompletedTask; + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.OuterMessage: + case OpCodeType.OuterRequest: + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterRoamingMessage: + case OpCodeType.OuterRoamingRequest: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + + return; + } + case OpCodeType.OuterResponse: + case OpCodeType.OuterPingResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + case OpCodeType.OuterRoamingResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + // 这个一般是客户端Session.Call发送时使用的、目前这个逻辑只有Unity客户端时使用 + + var aResponse = (IResponse)packInfo.Deserialize(messageType); + + if (!session.RequestCallback.Remove(packInfo.RpcId, out var action)) + { + Log.Error($"not found rpc {packInfo.RpcId}, response message: {aResponse.GetType().Name}"); + return; + } + + action.SetResult(aResponse); + } + + return; + } + default: + { + packInfo.Dispose(); + throw new NotSupportedException($"Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } + } + } +#endif +#if FANTASY_NET + internal sealed class ClientMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + public override FTask Scheduler(Session session, APackInfo packInfo) + { + throw new NotSupportedException($"ClientMessageScheduler Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } +#endif +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta new file mode 100644 index 0000000..bb7e6cf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e139ceb0d811615488f61e32553a22fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs new file mode 100644 index 0000000..b1b55f6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs @@ -0,0 +1,211 @@ +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System.Runtime.CompilerServices; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +#pragma warning disable CS8604 // Possible null reference argument. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Scheduler +{ + /// + /// 提供了一个机制来调度和处理内部网络消息。 + /// + internal sealed class InnerMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + public override async FTask Scheduler(Session session, APackInfo packInfo) + { + var protocol = packInfo.OpCodeIdStruct.Protocol; + + switch (protocol) + { + case OpCodeType.InnerMessage: + case OpCodeType.InnerRequest: + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + try + { + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + catch (Exception e) + { + Log.Error($"ANetworkMessageScheduler OuterResponse error messageProtocolCode:{packInfo.ProtocolCode} messageType:{messageType} SessionId {session.Id} IsDispose {session.IsDisposed} {e}"); + } + finally + { + packInfo.Dispose(); + } + + return; + } + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.InnerRoamingResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + case OpCodeType.OuterRoamingResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + NetworkMessagingComponent.ResponseHandler(packInfo.RpcId, (IResponse)packInfo.Deserialize(messageType)); + } + + return; + } + case OpCodeType.InnerRouteMessage: + case OpCodeType.InnerAddressableMessage: + case OpCodeType.InnerRoamingMessage: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + if (!Scene.TryGetEntity(packInfo.RouteId, out var entity)) + { + Scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, packInfo.RpcId); + return; + } + + var obj = packInfo.Deserialize(messageType); + await Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId); + } + + return; + } + case OpCodeType.InnerRouteRequest: + case OpCodeType.InnerAddressableRequest: + case OpCodeType.InnerRoamingRequest: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + if (!Scene.TryGetEntity(packInfo.RouteId, out var entity)) + { + Scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, packInfo.RpcId); + return; + } + + var obj = packInfo.Deserialize(messageType); + await Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId); + } + + return; + } + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterRoamingMessage: + case OpCodeType.OuterRoamingRequest: + { + var entity = Scene.GetEntity(packInfo.RouteId); + + switch (entity) + { + case null: + { + // 执行到这里有两种情况: + using (packInfo) + { + switch (Scene.SceneConfig.SceneTypeString) + { + case "Gate": + { + // 1、当前是Gate进行,需要转发消息给客户端,但当前这个Session已经断开了。 + // 这种情况不需要做任何处理。 + return; + } + default: + { + // 2、当前是其他Scene、消息通过Gate发送到这个Scene上面,但这个Scene上面没有这个Entity。 + // 因为这个是Gate转发消息到这个Scene的,如果没有找到Entity要返回错误给Gate。 + // 出现这个情况一定要打印日志,因为出现这个问题肯定是上层逻辑导致的,不应该出现这样的问题。 + var packInfoRouteId = packInfo.RouteId; + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + switch (protocol) + { + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterAddressableMessage: + { + Scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, packInfo.RpcId); + return; + } + } + + throw new Exception($"The Entity associated with RouteId = {packInfoRouteId} was not found! messageType = {messageType.FullName} protocol = {protocol}"); + } + } + } + } + case Session gateSession: + { + using (packInfo) + { + // 这里如果是Session只可能是Gate的Session、如果是的话、肯定是转发消息 + gateSession.Send(packInfo.MemoryStream, packInfo.RpcId); + } + + return; + } + default: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var obj = packInfo.Deserialize(messageType); + await Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId); + } + + return; + } + } + } + default: + { + var infoProtocolCode = packInfo.ProtocolCode; + packInfo.Dispose(); + throw new NotSupportedException($"InnerMessageScheduler Received unsupported message protocolCode:{infoProtocolCode}"); + } + } + } + } +} +#endif + diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta new file mode 100644 index 0000000..10ece21 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18e7a16a11194fd4e888ec7ef2d6151c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface.meta new file mode 100644 index 0000000..0f0fc39 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 27153833d136d9842a3a7420f45a5d35 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs new file mode 100644 index 0000000..b296cff --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs @@ -0,0 +1,30 @@ +using System; +using System.IO; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// ReSharper disable UnassignedField.Global +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.Scheduler +{ + public abstract class ANetworkMessageScheduler + { + protected readonly Scene Scene; + protected readonly MessageDispatcherComponent MessageDispatcherComponent; +#if FANTASY_NET + protected readonly NetworkMessagingComponent NetworkMessagingComponent; +#endif + protected ANetworkMessageScheduler(Scene scene) + { + Scene = scene; + MessageDispatcherComponent = scene.MessageDispatcherComponent; +#if FANTASY_NET + NetworkMessagingComponent = scene.NetworkMessagingComponent; +#endif + } + public abstract FTask Scheduler(Session session, APackInfo packInfo); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta new file mode 100644 index 0000000..a6dbd2e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bcde8d44e18d4e04c93484335fc9f65b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper.meta new file mode 100644 index 0000000..fa2d9ae --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b515f4157588f1740a5f4913ac489126 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs new file mode 100644 index 0000000..c645183 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs @@ -0,0 +1,107 @@ +using System; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; + +#pragma warning disable CS8625 +#pragma warning disable CS8618 + +namespace Fantasy.Scheduler +{ + /// + /// 网络消息发送者的类。 + /// + public struct MessageSender : IDisposable + { + /// + /// 获取或设置 RPC ID。 + /// + public uint RpcId { get; private set; } + /// + /// 获取或设置路由 ID。 + /// + public long RouteId { get; private set; } + /// + /// 获取或设置创建时间。 + /// + public long CreateTime { get; private set; } + /// + /// 获取或设置消息类型。 + /// + public Type MessageType { get; private set; } + /// + /// 获取或设置请求消息。 + /// + public IMessage Request { get; private set; } + /// + /// 获取或设置任务。 + /// + public FTask Tcs { get; private set; } + + /// + /// 释放资源。 + /// + public void Dispose() + { + RpcId = 0; + RouteId = 0; + CreateTime = 0; + Tcs = null; + Request = null; + MessageType = null; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 请求消息类型。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, Type requestType, FTask tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.MessageType = requestType; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 请求消息。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, IRequest request, FTask tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.Request = request; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 路由 ID。 + /// 路由消息请求。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, long routeId, IRouteMessage request, FTask tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.RouteId = routeId; + routeMessageSender.Request = request; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta new file mode 100644 index 0000000..80d07b1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83529804aaedbe44fad389e4d11e75a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs new file mode 100644 index 0000000..7580dd9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs @@ -0,0 +1,273 @@ +#if FANTASY_NET +using Fantasy.Entitas; +using System.Runtime.CompilerServices; +using Fantasy.Async; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Network.Route; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Timer; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Scheduler +{ + public struct NetworkMessageUpdate + { + public NetworkMessagingComponent NetworkMessagingComponent; + } + + public class NetworkMessagingComponentAwakeSystem : AwakeSystem + { + protected override void Awake(NetworkMessagingComponent self) + { + var selfScene = self.Scene; + self.TimerComponent = selfScene.TimerComponent; + self.MessageDispatcherComponent = selfScene.MessageDispatcherComponent; + self.AddressableRouteMessageLock = selfScene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + + self.TimerId = self.TimerComponent.Net.RepeatedTimer(10000, new NetworkMessageUpdate() + { + NetworkMessagingComponent = self + }); + } + } + + public class NetworkMessagingComponentDestroySystem : DestroySystem + { + protected override void Destroy(NetworkMessagingComponent self) + { + if (self.TimerId != 0) + { + self.TimerComponent.Net.Remove(ref self.TimerId); + } + + foreach (var (rpcId, messageSender) in self.RequestCallback.ToDictionary()) + { + self.ReturnMessageSender(rpcId, messageSender); + } + + self.AddressableRouteMessageLock.Dispose(); + + self.RequestCallback.Clear(); + self.TimeoutRouteMessageSenders.Clear(); + self.TimerComponent = null; + self.MessageDispatcherComponent = null; + self.AddressableRouteMessageLock = null; + } + } + public sealed class NetworkMessagingComponent : Entity + { + public long TimerId; + private uint _rpcId; + public CoroutineLock AddressableRouteMessageLock; + public TimerComponent TimerComponent; + public MessageDispatcherComponent MessageDispatcherComponent; + public readonly SortedDictionary RequestCallback = new(); + public readonly Dictionary TimeoutRouteMessageSenders = new(); + + public void SendInnerRoute(long routeId, IRouteMessage message) + { + if (routeId == 0) + { + Log.Error($"SendInnerRoute appId == 0"); + return; + } + + Scene.GetSession(routeId).Send(message, 0, routeId); + } + + internal void SendInnerRoute(long routeId, Type messageType, APackInfo packInfo) + { + if (routeId == 0) + { + Log.Error($"SendInnerRoute routeId == 0"); + return; + } + + Scene.GetSession(routeId).Send(0, routeId, messageType, packInfo); + } + + public void SendInnerRoute(ICollection routeIdCollection, IRouteMessage message) + { + if (routeIdCollection.Count <= 0) + { + Log.Error("SendInnerRoute routeIdCollection.Count <= 0"); + return; + } + + using var processPackInfo = ProcessPackInfo.Create(Scene, message, routeIdCollection.Count); + foreach (var routeId in routeIdCollection) + { + processPackInfo.Set(0, routeId); + Scene.GetSession(routeId).Send(processPackInfo, 0, routeId); + } + } + + public async FTask SendAddressable(long addressableId, IRouteMessage message) + { + await CallAddressable(addressableId, message); + } + + internal async FTask CallInnerRoute(long routeId, Type requestType, APackInfo packInfo) + { + if (routeId == 0) + { + Log.Error($"CallInnerRoute routeId == 0"); + return null; + } + + var rpcId = ++_rpcId; + var session = Scene.GetSession(routeId); + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, requestType, requestCallback)); + session.Send(rpcId, routeId, requestType, packInfo); + return await requestCallback; + } + + public async FTask CallInnerRouteBySession(Session session, long routeId, IRouteMessage request) + { + var rpcId = ++_rpcId; + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, request, requestCallback)); + session.Send(request, rpcId, routeId); + return await requestCallback; + } + + public async FTask CallInnerRoute(long routeId, IRouteMessage request) + { + if (routeId == 0) + { + Log.Error($"CallInnerRoute routeId == 0"); + return null; + } + + var rpcId = ++_rpcId; + var session = Scene.GetSession(routeId); + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, request, requestCallback)); + session.Send(request, rpcId, routeId); + return await requestCallback; + } + + public async FTask CallAddressable(long addressableId, IRouteMessage request) + { + var failCount = 0; + + using (await AddressableRouteMessageLock.Wait(addressableId, "CallAddressable")) + { + var addressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, addressableId); + + while (true) + { + if (addressableRouteId == 0) + { + addressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, addressableId); + } + + if (addressableRouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoute); + } + + var iRouteResponse = await CallInnerRoute(addressableRouteId, request); + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error($"AddressableComponent.Call failCount > 20 route send message fail, routeId: {addressableRouteId} AddressableMessageComponent:{addressableId}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(500); + addressableRouteId = 0; + continue; + } + case InnerErrorCode.ErrRouteTimeout: + { + Log.Error($"CallAddressableRoute ErrorCode.ErrRouteTimeout Error:{iRouteResponse.ErrorCode} Message:{request}"); + return iRouteResponse; + } + default: + { + return iRouteResponse; + } + } + } + } + } + + public void ResponseHandler(uint rpcId, IResponse response) + { + if (!RequestCallback.Remove(rpcId, out var routeMessageSender)) + { + throw new Exception($"not found rpc, response.RpcId:{rpcId} response message: {response.GetType().Name} Process:{Scene.Process.Id} Scene:{Scene.SceneConfigId}"); + } + + ResponseHandler(routeMessageSender, response); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ResponseHandler(MessageSender messageSender, IResponse response) + { + if (response.ErrorCode == InnerErrorCode.ErrRouteTimeout) + { +#if FANTASY_DEVELOP + messageSender.Tcs.SetException(new Exception($"Rpc error: request, 注意RouteId消息超时,请注意查看是否死锁或者没有reply: RouteId: {messageSender.RouteId} {messageSender.Request.ToJson()}, response: {response}")); +#else + messageSender.Tcs.SetException(new Exception($"Rpc error: request, 注意RouteId消息超时,请注意查看是否死锁或者没有reply: RouteId: {messageSender.RouteId} {messageSender.Request}, response: {response}")); +#endif + messageSender.Dispose(); + return; + } + + messageSender.Tcs.SetResult(response); + messageSender.Dispose(); + } + + public void ReturnMessageSender(uint rpcId, MessageSender messageSender) + { + try + { + switch (messageSender.Request) + { + case IRouteMessage iRouteMessage: + { + // IRouteMessage是个特殊的RPC协议、这里不处理就可以了。 + break; + } + case IRequest iRequest: + { + var response = MessageDispatcherComponent.CreateResponse(iRequest.GetType(), InnerErrorCode.ErrRpcFail); + var responseRpcId = messageSender.RpcId; + ResponseHandler(responseRpcId, response); + Log.Warning($"timeout rpcId:{rpcId} responseRpcId:{responseRpcId} {iRequest.ToJson()}"); + break; + } + default: + { + Log.Error(messageSender.Request != null + ? $"Unsupported protocol type {messageSender.Request.GetType()} rpcId:{rpcId} messageSender.Request != null" + : $"Unsupported protocol type:{messageSender.MessageType.FullName} rpcId:{rpcId}"); + RequestCallback.Remove(rpcId); + break; + } + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta new file mode 100644 index 0000000..aae33cf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1cf61a8d09226f44cb226e26213a6956 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs new file mode 100644 index 0000000..7dd2ea3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs @@ -0,0 +1,60 @@ +using Fantasy.Helper; +using Fantasy.Timer; + +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +namespace Fantasy.Scheduler +{ + /// + /// 网络消息更新检查超时。 + /// + public sealed class OnNetworkMessageUpdateCheckTimeout : TimerHandler + { + /// + /// 超时时间(毫秒)。 + /// + private const long Timeout = 40000; + + /// + /// 处理网络消息更新检查超时。 + /// + /// + /// + protected override void Handler(NetworkMessageUpdate self) + { + var timeNow = TimeHelper.Now; + var selfNetworkMessagingComponent = self.NetworkMessagingComponent; + + // 遍历请求回调字典,检查是否有超时的请求,将超时请求添加到超时消息发送列表中。 + + foreach (var (rpcId, value) in selfNetworkMessagingComponent.RequestCallback) + { + if (timeNow < value.CreateTime + Timeout) + { + break; + } + + selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Add(rpcId, value); + } + + // 如果没有超时的请求,直接返回。 + + if (selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Count == 0) + { + return; + } + + // 处理超时的请求,根据请求类型生成相应的响应消息,并进行处理。 + + foreach (var (rpcId, routeMessageSender) in selfNetworkMessagingComponent.TimeoutRouteMessageSenders) + { + selfNetworkMessagingComponent.ReturnMessageSender(rpcId, routeMessageSender); + } + + // 清空超时消息发送列表。 + + selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta new file mode 100644 index 0000000..984bec2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6392d692b4adea94ab90b536e75394f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs new file mode 100644 index 0000000..2c963ff --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs @@ -0,0 +1,366 @@ +using System; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.PacketParser.Interface; +#if FANTASY_NET +using System.Text; +using Fantasy.Network.Interface; +using Fantasy.Network.Route; +using Fantasy.PacketParser; +using Fantasy.Helper; +using Fantasy.InnerMessage; +using Fantasy.Roaming; +#endif + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.Scheduler +{ + /// + /// 提供了一个机制来调度和处理外部网络消息。 + /// +#if FANTASY_UNITY + public sealed class OuterMessageScheduler : ANetworkMessageScheduler + { + public OuterMessageScheduler(Scene scene) : base(scene) { } + + /// + /// 在Unity环境下,处理外部消息的方法。 + /// + /// 网络会话。 + /// 消息封包信息。 + public override FTask Scheduler(Session session, APackInfo packInfo) + { + throw new NotSupportedException($"Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } +#endif +#if FANTASY_NET + internal sealed class OuterMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + private readonly PingResponse _pingResponse = new PingResponse(); + public override async FTask Scheduler(Session session, APackInfo packInfo) + { + if (session.IsDisposed) + { + return; + } + + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.OuterPingRequest: + { + // 注意心跳目前只有外网才才会有、内网之间不需要心跳。 + + session.LastReceiveTime = TimeHelper.Now; + _pingResponse.Now = session.LastReceiveTime; + + using (packInfo) + { + session.Send(_pingResponse, packInfo.RpcId); + } + + return; + } + case OpCodeType.OuterMessage: + case OpCodeType.OuterRequest: + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + try + { + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + catch (Exception e) + { + Log.Error($"ANetworkMessageScheduler OuterResponse error messageProtocolCode:{packInfo.ProtocolCode} messageType:{messageType} SessionId {session.Id} IsDispose {session.IsDisposed} {e}"); + } + finally + { + packInfo.Dispose(); + } + + return; + } + case OpCodeType.OuterResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + NetworkMessagingComponent.ResponseHandler(packInfo.RpcId, (IResponse)packInfo.Deserialize(messageType)); + } + + return; + } + case OpCodeType.OuterAddressableMessage: + { + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var addressableRouteComponent = session.AddressableRouteComponent; + + if (addressableRouteComponent == null) + { + throw new Exception("OuterMessageScheduler error session does not have an AddressableRouteComponent component"); + } + + await addressableRouteComponent.Send(messageType, packInfo); + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterAddressableRequest: + { + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var addressableRouteComponent = session.AddressableRouteComponent; + + if (addressableRouteComponent == null) + { + throw new Exception("OuterMessageScheduler error session does not have an AddressableRouteComponent component"); + } + + var rpcId = packInfo.RpcId; + var runtimeId = session.RuntimeId; + var response = await addressableRouteComponent.Call(messageType, packInfo); + // session可能已经断开了,所以这里需要判断 + if (session.RuntimeId == runtimeId) + { + session.Send(response, rpcId); + } + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterCustomRouteMessage: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var routeComponent = session.RouteComponent; + + if (routeComponent == null) + { + throw new Exception($"OuterMessageScheduler CustomRouteType session does not have an routeComponent component messageType:{messageType.FullName} ProtocolCode:{packInfo.ProtocolCode}"); + } + + if (!routeComponent.TryGetRouteId(routeType, out var routeId)) + { + throw new Exception($"OuterMessageScheduler RouteComponent cannot find RouteId with RouteType {routeType}"); + } + + NetworkMessagingComponent.SendInnerRoute(routeId, messageType, packInfo); + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterCustomRouteRequest: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var routeComponent = session.RouteComponent; + + if (routeComponent == null) + { + throw new Exception("OuterMessageScheduler CustomRouteType session does not have an routeComponent component"); + } + + if (!routeComponent.TryGetRouteId(routeType, out var routeId)) + { + throw new Exception($"OuterMessageScheduler RouteComponent cannot find RouteId with RouteType {routeType}"); + } + + var rpcId = packInfo.RpcId; + var runtimeId = session.RuntimeId; + var response = await NetworkMessagingComponent.CallInnerRoute(routeId, messageType, packInfo); + // session可能已经断开了,所以这里需要判断 + if (session.RuntimeId == runtimeId) + { + session.Send(response, rpcId); + } + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterRoamingMessage: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var sessionRoamingComponent = session.SessionRoamingComponent; + + if (sessionRoamingComponent == null) + { + throw new Exception($"OuterMessageScheduler Roaming session does not have an sessionRoamingComponent component messageType:{messageType.FullName} ProtocolCode:{packInfo.ProtocolCode}"); + } + + await sessionRoamingComponent.Send(routeType, messageType, packInfo); + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterRoamingRequest: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var sessionRoamingComponent = session.SessionRoamingComponent; + + if (sessionRoamingComponent == null) + { + throw new Exception("OuterMessageScheduler Roaming session does not have an sessionRoamingComponent component"); + } + + var rpcId = packInfo.RpcId; + var runtimeId = session.RuntimeId; + var response = await sessionRoamingComponent.Call(routeType, messageType, packInfo); + // session可能已经断开了,所以这里需要判断 + if (session.RuntimeId == runtimeId) + { + session.Send(response, rpcId); + } + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + default: + { + var ipAddress = session.IsDisposed ? "null" : session.RemoteEndPoint.ToString(); + packInfo.Dispose(); + throw new NotSupportedException($"OuterMessageScheduler Received unsupported message protocolCode:{packInfo.ProtocolCode}\n1、请检查该协议所在的程序集是否在框架初始化的时候添加到框架中。\n2、如果看到这个消息表示你有可能用的老版本的导出工具,请更换为最新的导出工具。\n IP地址:{ipAddress}"); + } + } + } + } +#endif +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta new file mode 100644 index 0000000..5e4ad35 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eba707e9ed6106c40b5fb5a27dadeca1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol.meta b/Runtime/CoreRuntime/Core/Network/Protocol.meta new file mode 100644 index 0000000..5dd0011 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9f437153b8ac3a48bb753af2dfd1cf3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Exception.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Exception.meta new file mode 100644 index 0000000..d5728a4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Exception.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 801278df7ca03874886ed65b0acebba9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs b/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs new file mode 100644 index 0000000..43c695a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs @@ -0,0 +1,21 @@ +using System; + +namespace Fantasy.Network +{ + /// + /// 在扫描过程中发生的异常。 + /// + public class ScanException : Exception + { + /// + /// 初始化 类的新实例。 + /// + public ScanException() { } + + /// + /// 使用指定的错误消息初始化 类的新实例。 + /// + /// 错误消息。 + public ScanException(string msg) : base(msg) { } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs.meta new file mode 100644 index 0000000..822b3f6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Exception/ScanException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69acfd039d47fe74e80239223528ea9d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/HTTP.meta b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP.meta new file mode 100644 index 0000000..f412c62 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3d5dc01db80fa8640bce3535ac847d27 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs new file mode 100644 index 0000000..9ca4eba --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs @@ -0,0 +1,128 @@ +#if FANTASY_NET +using System.IO; +using System.Net; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +#pragma warning disable CS8604 // Possible null reference argument. + +// ReSharper disable PossibleMultipleEnumeration + +namespace Fantasy.Network.HTTP +{ + /// + /// HTTP服务器 + /// + public sealed class HTTPServerNetwork : ANetwork + { + /// + /// 初始化入口 + /// + /// + /// + /// + public void Initialize(NetworkTarget networkTarget, string bindIp, int port) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.HTTP, networkTarget); + + try + { + StartAsync(bindIp, port); + } + catch (HttpListenerException e) + { + if (e.ErrorCode == 5) + { + var sb = new StringBuilder(); + sb.AppendLine("CMD管理员中输入下面其中一个命令,具体根据您是HTTPS或HTTP决定:"); + sb.AppendLine($"HTTP请输入如下:netsh http add urlacl url=http://{bindIp}:{port}/ user=Everyone"); + sb.AppendLine($"HTTPS请输入如下:netsh http add urlacl url=https://{bindIp}:{port}/ user=Everyone"); + throw new Exception(sb.ToString(), e); + } + + Log.Error(e); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private void StartAsync(string bindIp, int port) + { + var builder = WebApplication.CreateBuilder(); + // 配置日志级别为 Warning 或更高 + builder.Logging.ClearProviders(); + builder.Logging.AddConsole(); + builder.Logging.SetMinimumLevel(LogLevel.Warning); + // 将Scene注册到 DI 容器中,传递给控制器 + builder.Services.AddSingleton(Scene); + // 注册Scene同步过滤器 + builder.Services.AddScoped(); + // 注册控制器服务 + var addControllers = builder.Services.AddControllers() + .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; }); + foreach (var assembly in AssemblySystem.ForEachAssembly) + { + addControllers.AddApplicationPart(assembly); + } + var listenUrl = ""; + var app = builder.Build(); + // 检测当前路径下是否有证书文件 + var certificatePath = Path.Combine(AppContext.BaseDirectory, $"certificate{bindIp}{port}"); + if (Directory.Exists(certificatePath)) + { + // 加载包含证书链的 PEM 文件 + var pemCertChain = File.ReadAllText(Path.Combine(certificatePath, "chain.pem")); + var pemPrivateKey = File.ReadAllText(Path.Combine(certificatePath, "private-key.pem")); + // 配置 HTTPS 监听并使用证书 + builder.WebHost.ConfigureKestrel(kestrelServerOptions => + { + kestrelServerOptions.ConfigureHttpsDefaults(https => + { + https.ServerCertificate = X509Certificate2.CreateFromPem(pemCertChain, pemPrivateKey); + }); + }); + listenUrl = $"https://{bindIp}:{port}/"; + app.Urls.Add(listenUrl); + app.UseHttpsRedirection(); + } + else + { + // 不安全的HTTP地址 + listenUrl = $"http://{bindIp}:{port}/"; + app.Urls.Add(listenUrl); + } + // 启用开发者工具 + if (app.Environment.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + // 路由注册 + app.MapControllers(); + // 开启监听 + app.RunAsync(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} HTTPServer Listen {listenUrl}"); + } + + /// + /// 移除Channel + /// + /// + /// + public override void RemoveChannel(uint channelId) + { + throw new NotImplementedException(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta new file mode 100644 index 0000000..15ace66 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4793c5b90f31f7b47812144291f29bf4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs new file mode 100644 index 0000000..2688bdc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs @@ -0,0 +1,54 @@ +#if FANTASY_NET +using Fantasy.Async; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Fantasy.Network.HTTP; + +/// +/// 让所有实现SceneContextFilter的控制器,都在执行的Scene下执行 +/// +public sealed class SceneContextFilter : IAsyncActionFilter +{ + private readonly Scene _scene; + + /// + /// 构造函数 + /// + /// + public SceneContextFilter(Scene scene) + { + _scene = scene; + } + + /// + /// OnActionExecutionAsync + /// + /// + /// + /// + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var tcs = FTask.Create(); + + _scene.ThreadSynchronizationContext.Post(() => + { + Action().Coroutine(); + }); + + await tcs; + return; + + async FTask Action() + { + try + { + await next(); + } + finally + { + tcs.SetResult(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta new file mode 100644 index 0000000..f0424c8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fa25319b281e8b40b2948283e2324bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Interface.meta new file mode 100644 index 0000000..7ccd7fa --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3a5347480f119d144bd6a5923e23e926 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs new file mode 100644 index 0000000..322c811 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 抽象客户端网络基类。 + /// + public abstract class AClientNetwork : ANetwork, INetworkChannel + { + protected bool IsInit; + public Session Session { get; protected set; } + public abstract Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000); + public abstract void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + public override void Dispose() + { + IsInit = false; + + if (Session != null) + { + if (!Session.IsDisposed) + { + Session.Dispose(); + } + + Session = null; + } + + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta new file mode 100644 index 0000000..b7a5e82 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f8ddd3e14b9d5b4a8807f46893ce98e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs new file mode 100644 index 0000000..fdb85f2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using Fantasy.Entitas; +using Fantasy.PacketParser; +using Fantasy.Scheduler; +using Fantasy.Serialize; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 抽象网络基类。 + /// + public abstract class ANetwork : Entity + { + private long _outerPackInfoId; + private Queue _outerPackInfoPool; + public readonly MemoryStreamBufferPool MemoryStreamBufferPool = new MemoryStreamBufferPool(); + + public NetworkType NetworkType { get; private set; } + public NetworkTarget NetworkTarget { get; private set; } + public NetworkProtocolType NetworkProtocolType { get; private set; } + public ANetworkMessageScheduler NetworkMessageScheduler { get; private set; } + + protected void Initialize(NetworkType networkType, NetworkProtocolType networkProtocolType, NetworkTarget networkTarget) + { + NetworkType = networkType; + NetworkTarget = networkTarget; + NetworkProtocolType = networkProtocolType; +#if FANTASY_NET + if (networkProtocolType == NetworkProtocolType.HTTP) + { + return; + } + if (networkTarget == NetworkTarget.Inner) + { + _innerPackInfoPool = new Queue(); + NetworkMessageScheduler = new InnerMessageScheduler(Scene); + return; + } +#endif + switch (networkType) + { + case NetworkType.Client: + { + _outerPackInfoPool = new Queue(); + NetworkMessageScheduler = new ClientMessageScheduler(Scene); + break; + } +#if FANTASY_NET + case NetworkType.Server: + { + _outerPackInfoPool = new Queue(); + NetworkMessageScheduler = new OuterMessageScheduler(Scene); + break; + } +#endif + } + } + + public abstract void RemoveChannel(uint channelId); + public OuterPackInfo RentOuterPackInfo() + { + if (_outerPackInfoPool.Count == 0) + { + return new OuterPackInfo() + { + PackInfoId = ++_outerPackInfoId + }; + } + + if (!_outerPackInfoPool.TryDequeue(out var outerPackInfo)) + { + return new OuterPackInfo() + { + PackInfoId = ++_outerPackInfoId + }; + } + + outerPackInfo.PackInfoId = ++_outerPackInfoId; + return outerPackInfo; + } + + public void ReturnOuterPackInfo(OuterPackInfo outerPackInfo) + { + if (_outerPackInfoPool.Count > 512) + { + // 池子里最多缓存256个、其实这样设置有点多了、其实用不了512个。 + // 反而设置越大内存会占用越多。 + return; + } + + _outerPackInfoPool.Enqueue(outerPackInfo); + } +#if FANTASY_NET + private long _innerPackInfoId; + private Queue _innerPackInfoPool; + public InnerPackInfo RentInnerPackInfo() + { + if (_innerPackInfoPool.Count == 0) + { + return new InnerPackInfo() + { + PackInfoId = ++_innerPackInfoId + }; + } + + if (!_innerPackInfoPool.TryDequeue(out var innerPackInfo)) + { + return new InnerPackInfo() + { + PackInfoId = ++_innerPackInfoId + }; + } + + innerPackInfo.PackInfoId = ++_innerPackInfoId; + return innerPackInfo; + } + + public void ReturnInnerPackInfo(InnerPackInfo innerPackInfo) + { + if (_innerPackInfoPool.Count > 256) + { + // 池子里最多缓存256个、其实这样设置有点多了、其实用不了256个。 + // 反而设置越大内存会占用越多。 + return; + } + + _innerPackInfoPool.Enqueue(innerPackInfo); + } +#endif + public override void Dispose() + { + NetworkType = NetworkType.None; + NetworkTarget = NetworkTarget.None; + NetworkProtocolType = NetworkProtocolType.None; + MemoryStreamBufferPool.Dispose(); + _outerPackInfoPool?.Clear(); +#if FANTASY_NET + _innerPackInfoPool?.Clear(); +#endif + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs.meta new file mode 100644 index 0000000..56f79d0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48c4dd326f2155b48b7d0e9bfc5d76e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs new file mode 100644 index 0000000..788a235 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs @@ -0,0 +1,55 @@ +#if FANTASY_NET +using System.IO; +using System.Net; +using Fantasy.Serialize; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + public abstract class ANetworkServerChannel : INetworkChannel + { + /// + /// 获取通道的唯一标识 ID。 + /// + public readonly uint Id; + /// + /// 获取通道的远程终端点。 + /// + public readonly EndPoint RemoteEndPoint; + /// + /// 获取或设置通道所属的场景。 + /// + public Scene Scene { get; protected set; } + /// + /// 获取或设置通道所属的会话。 + /// + public Session Session { get; protected set; } + /// + /// 获取通道是否已经被释放。 + /// + public bool IsDisposed { get; protected set; } + + protected ANetworkServerChannel(ANetwork network, uint id, EndPoint remoteEndPoint) + { + Id = id; + Scene = network.Scene; + RemoteEndPoint = remoteEndPoint; + Session = Session.Create(network.NetworkMessageScheduler, this, network.NetworkTarget); + } + + public virtual void Dispose() + { + IsDisposed = true; + + if (!Session.IsDisposed) + { + Session.Dispose(); + } + } + + public abstract void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta new file mode 100644 index 0000000..caebddd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a7174c7f3095c69479f924b340672ad0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs new file mode 100644 index 0000000..52f341a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs @@ -0,0 +1,14 @@ +using System; +using System.IO; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Interface +{ + public interface INetworkChannel : IDisposable + { + public Session Session { get;} + public bool IsDisposed { get;} + public void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta new file mode 100644 index 0000000..a98c91a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a00ec04a1211c5449b57150aefbfe4d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP.meta new file mode 100644 index 0000000..9d28c71 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ca84ece303fd6c14aa5170f72c5ea35c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base.meta new file mode 100644 index 0000000..7d7566a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4706aed58f095334ca7249af99d40520 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs new file mode 100644 index 0000000..47316cb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs @@ -0,0 +1,451 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using kcp; +using static kcp.KCP; + +#pragma warning disable CS8601 +#pragma warning disable CS8602 +#pragma warning disable CS8625 + +// ReSharper disable ALL + +namespace KCP +{ + /// + /// Kcp callback + /// + /// KCP output destination + /// KCP output size (excluding reserved) + internal delegate void KcpCallback(byte[] buffer, int length); + + /// + /// Kcp + /// + internal sealed unsafe class Kcp : IDisposable + { + /// + /// Kcp + /// + private IKCPCB* _kcp; + + /// + /// Output function + /// + private KcpCallback _output; + + /// + /// Buffer + /// + private byte[] _buffer; + + /// + /// Reserved overhead + /// + private int _reserved; + + /// + /// Disposed + /// + private int _disposed; + + /// + /// Structure + /// + /// ConversationId + /// Output + /// Reserved overhead + public Kcp(uint conv, KcpCallback output, int reserved) + { + _kcp = ikcp_create(conv, reserved, ref _buffer); + _output = output; + _reserved = reserved; + } + + /// + /// Set + /// + public bool IsSet => _kcp != null; + + /// + /// Conversation id + /// + public uint ConversationId => _kcp->conv; + + /// + /// Maximum transmission unit + /// + public uint MaximumTransmissionUnit => _kcp->mtu; + + /// + /// Maximum segment size + /// + public uint MaximumSegmentSize => _kcp->mss; + + /// + /// Connection state + /// + public uint State => _kcp->state; + + /// + /// The sequence number of the first unacknowledged packet + /// + public uint SendUna => _kcp->snd_una; + + /// + /// The sequence number for the next packet to be sent + /// + public uint SendNext => _kcp->snd_nxt; + + /// + /// The sequence number for the next packet expected to be received + /// + public uint ReceiveNext => _kcp->rcv_nxt; + + /// + /// Slow start threshold for congestion control + /// + public uint SlowStartThreshold => _kcp->ssthresh; + + /// + /// Round-trip time variance + /// + public int RxRttval => _kcp->rx_rttval; + + /// + /// Smoothed round-trip time + /// + public int RxSrtt => _kcp->rx_srtt; + + /// + /// Retransmission timeout + /// + public int RxRto => _kcp->rx_rto; + + /// + /// Minimum retransmission timeout + /// + public int RxMinrto => _kcp->rx_minrto; + + /// + /// Send window size + /// + public uint SendWindowSize => _kcp->snd_wnd; + + /// + /// Receive window size + /// + public uint ReceiveWindowSize => _kcp->rcv_wnd; + + /// + /// Remote window size + /// + public uint RemoteWindowSize => _kcp->rmt_wnd; + + /// + /// Congestion window size + /// + public uint CongestionWindowSize => _kcp->cwnd; + + /// + /// Probe variable for fast recovery + /// + public uint Probe => _kcp->probe; + + /// + /// Current timestamp + /// + public uint Current => _kcp->current; + + /// + /// Flush interval + /// + public uint Interval => _kcp->interval; + + /// + /// Timestamp for the next flush + /// + public uint TimestampFlush => _kcp->ts_flush; + + /// + /// Number of retransmissions + /// + public uint Transmissions => _kcp->xmit; + + /// + /// Number of packets in the receive buffer + /// + public uint ReceiveBufferCount => _kcp->nrcv_buf; + + /// + /// Number of packets in the receive queue + /// + public uint ReceiveQueueCount => _kcp->nrcv_que; + + /// + /// Number of packets wait to receive + /// + public uint WaitReceiveCount => _kcp->nrcv_buf + _kcp->nrcv_que; + + /// + /// Number of packets in the send buffer + /// + public uint SendBufferCount => _kcp->nsnd_buf; + + /// + /// Number of packets in the send queue + /// + public uint SendQueueCount => _kcp->nsnd_que; + + /// + /// Number of packets wait to send + /// + public uint WaitSendCount => _kcp->nsnd_buf + _kcp->nsnd_que; + + /// + /// Whether Nagle's algorithm is disabled + /// + public uint NoDelay => _kcp->nodelay; + + /// + /// Whether the KCP connection has been updated + /// + public uint Updated => _kcp->updated; + + /// + /// Timestamp for the next probe + /// + public uint TimestampProbe => _kcp->ts_probe; + + /// + /// Probe wait time + /// + public uint ProbeWait => _kcp->probe_wait; + + /// + /// Incremental increase + /// + public uint Increment => _kcp->incr; + + /// + /// Pointer to the acknowledge list + /// + public uint* AckList => _kcp->acklist; + + /// + /// Count of acknowledges + /// + public uint AckCount => _kcp->ackcount; + + /// + /// Number of acknowledge blocks + /// + public uint AckBlock => _kcp->ackblock; + + /// + /// Buffer + /// + public byte[] Buffer => _buffer; + + /// + /// Fast resend trigger count + /// + public int FastResend => _kcp->fastresend; + + /// + /// Fast resend limit + /// + public int FastResendLimit => _kcp->fastlimit; + + /// + /// Whether congestion control is disabled + /// + public int NoCongestionWindow => _kcp->nocwnd; + + /// + /// Whether stream mode is enabled + /// + public int StreamMode => _kcp->stream; + + /// + /// Output function pointer + /// + public KcpCallback Output => _output; + + /// + /// Reserved overhead + /// + public int Reserved => _reserved; + + /// + /// Dispose + /// + public void Dispose() + { + if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) + return; + ikcp_release(_kcp); + _kcp = null; + _output = null; + _buffer = null; + GC.SuppressFinalize(this); + } + + /// + /// Set output + /// + /// Output + public void SetOutput(KcpCallback output) => _output = output; + + /// + /// Destructure + /// + ~Kcp() => Dispose(); + + /// + /// Send + /// + /// Buffer + /// Sent bytes + public int Send(ReadOnlySpan buffer) + { + fixed (byte* pinnedBuffer = &MemoryMarshal.GetReference(buffer)) + { + return ikcp_send(_kcp, pinnedBuffer, buffer.Length); + } + } + + /// + /// Send + /// + /// Buffer + /// Length + /// Sent bytes + public int Send(byte* buffer, int length) => ikcp_send(_kcp, buffer, length); + + /// + /// Input + /// + /// Buffer + /// Input bytes + public int Input(ReadOnlySpan buffer) + { + fixed (byte* pinnedBuffer = &MemoryMarshal.GetReference(buffer)) + { + return ikcp_input(_kcp, pinnedBuffer, buffer.Length); + } + } + + /// + /// Input + /// + /// Buffer + /// Length + /// Input bytes + public int Input(byte* buffer, int length) => ikcp_input(_kcp, buffer, length); + + /// + /// Peek size + /// + /// Peeked size + public int PeekSize() => ikcp_peeksize(_kcp); + + /// + /// Receive + /// + /// Buffer + /// Received bytes + public int Receive(Span buffer) + { + fixed (byte* pinnedBuffer = &MemoryMarshal.GetReference(buffer)) + { + return ikcp_recv(_kcp, pinnedBuffer, buffer.Length); + } + } + + /// + /// Receive + /// + /// Buffer + /// Length + /// Received bytes + public int Receive(byte* buffer, int length) => ikcp_recv(_kcp, buffer, length); + + /// + /// Update + /// + /// Timestamp + public void Update(uint current) + { + fixed (byte* ptr = &_buffer[_reserved]) + { + ikcp_update(_kcp, current, ptr, _buffer, _output); + } + } + + /// + /// Check + /// + /// Timestamp + /// Next flush timestamp + public uint Check(uint current) => ikcp_check(_kcp, current); + + /// + /// Flush + /// + public void Flush() + { + fixed (byte* ptr = &_buffer[_reserved]) + { + ikcp_flush(_kcp, ptr, _buffer, _output); + } + } + + /// + /// Set maximum transmission unit + /// + /// Maximum transmission unit + /// Set + public int SetMtu(int mtu) => ikcp_setmtu(_kcp, mtu, _reserved, ref _buffer); + + /// + /// Set flush interval + /// + /// Flush interval + public void SetInterval(int interval) => ikcp_interval(_kcp, interval); + + /// + /// Set no delay + /// + /// Whether Nagle's algorithm is disabled + /// Flush interval + /// Fast resend trigger count + /// No congestion window + public void SetNoDelay(int nodelay, int interval, int resend, int nc) => ikcp_nodelay(_kcp, nodelay, interval, resend, nc); + + /// + /// Set window size + /// + /// Send window size + /// Receive window size + public void SetWindowSize(int sndwnd, int rcvwnd) => ikcp_wndsize(_kcp, sndwnd, rcvwnd); + + /// + /// Set fast resend limit + /// + /// Fast resend limit + public void SetFastResendLimit(int fastlimit) => _kcp->fastlimit = Math.Clamp(fastlimit, 0, 5); + + /// + /// Set whether stream mode is enabled + /// + /// Whether stream mode is enabled + public void SetStreamMode(int stream) => _kcp->stream = stream == 1 ? 1 : 0; + + /// + /// Set minimum retransmission timeout + /// + /// Minimum retransmission timeout + public void SetMinrto(int minrto) => _kcp->rx_minrto = (int)Math.Clamp(minrto, 1, IKCP_RTO_MAX); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta new file mode 100644 index 0000000..d850959 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd012614ad89dd54880fd585fd5f3270 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c.meta new file mode 100644 index 0000000..977f7f4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ad3630a70cace25469a755a89579fecc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs new file mode 100644 index 0000000..c5c36f0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs @@ -0,0 +1,1367 @@ +#if NET6_0_OR_GREATER +using System.Numerics; +#endif +using System.Runtime.CompilerServices; +using KCP; + +#pragma warning disable CA2211 +#pragma warning disable CS1591 +#pragma warning disable CS8602 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace kcp +{ + /// + /// https://github.com/skywind3000/kcp + /// + internal static unsafe partial class KCP + { + //===================================================================== + // KCP BASIC + //===================================================================== + public const uint IKCP_RTO_NDL = 30; // no delay min rto + public const uint IKCP_RTO_MIN = 100; // normal min rto + public const uint IKCP_RTO_DEF = 200; + public const uint IKCP_RTO_MAX = 60000; + public const uint IKCP_CMD_PUSH = 81; // cmd: push data + public const uint IKCP_CMD_ACK = 82; // cmd: ack + public const uint IKCP_CMD_WASK = 83; // cmd: window probe (ask) + public const uint IKCP_CMD_WINS = 84; // cmd: window size (tell) + public const uint IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK + public const uint IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS + public const uint IKCP_WND_SND = 32; + public const uint IKCP_WND_RCV = 128; // must >= max fragment size + public const uint IKCP_MTU_DEF = 1400; + public const uint IKCP_ACK_FAST = 3; + public const uint IKCP_INTERVAL = 100; + public const uint IKCP_OVERHEAD = 24; + public const uint IKCP_DEADLINK = 20; + public const uint IKCP_THRESH_INIT = 2; + public const uint IKCP_THRESH_MIN = 2; + public const uint IKCP_PROBE_INIT = 7000; // 7 secs to probe window size + public const uint IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window + public const uint IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack + + //--------------------------------------------------------------------- + // encode / decode + //--------------------------------------------------------------------- + + /* encode 8 bits unsigned int */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_encode8u(byte* p, byte c) + { + *(byte*)p++ = c; + return p; + } + + /* decode 8 bits unsigned int */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_decode8u(byte* p, byte* c) + { + *c = *(byte*)p++; + return p; + } + + /* encode 16 bits unsigned int (lsb) */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_encode16u(byte* p, ushort w) + { +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *(byte*)(p + 0) = (byte)(w & 255); + *(byte*)(p + 1) = (byte)(w >> 8); +#else + memcpy(p, &w, (nuint)2); +#endif + p += 2; + return p; + } + + /* decode 16 bits unsigned int (lsb) */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_decode16u(byte* p, ushort* w) + { +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *w = *(byte*)(p + 1); + *w = (ushort)(*(byte*)(p + 0) + (*w << 8)); +#else + memcpy(w, p, (nuint)2); +#endif + p += 2; + return p; + } + + /* encode 32 bits unsigned int (lsb) */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_encode32u(byte* p, uint l) + { +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *(byte*)(p + 0) = (byte)((l >> 0) & 0xff); + *(byte*)(p + 1) = (byte)((l >> 8) & 0xff); + *(byte*)(p + 2) = (byte)((l >> 16) & 0xff); + *(byte*)(p + 3) = (byte)((l >> 24) & 0xff); +#else + memcpy(p, &l, (nuint)4); +#endif + p += 4; + return p; + } + + /* decode 32 bits unsigned int (lsb) */ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte* ikcp_decode32u(byte* p, uint* l) + { +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *l = *(byte*)(p + 3); + *l = *(byte*)(p + 2) + (*l << 8); + *l = *(byte*)(p + 1) + (*l << 8); + *l = *(byte*)(p + 0) + (*l << 8); +#else + memcpy(l, p, (nuint)4); +#endif + p += 4; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint _imin_(uint a, uint b) + { + return a <= b ? a : b; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint _imax_(uint a, uint b) + { + return a >= b ? a : b; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint _ibound_(uint lower, uint middle, uint upper) + { + return _imin_(_imax_(lower, middle), upper); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint _iceilpow2_(uint x) + { +#if NET6_0_OR_GREATER + return BitOperations.RoundUpToPowerOf2(x); +#else + --x; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + ++x; + return x; +#endif + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long _itimediff(uint later, uint earlier) + { + return ((int)(later - earlier)); + } + + // //--------------------------------------------------------------------- + // // manage segment + // //--------------------------------------------------------------------- + // public static delegate* managed ikcp_malloc_hook = null; + // public static delegate* managed ikcp_free_hook = null; + + // // internal malloc + // public static void* ikcp_malloc(nuint size) + // { + // if (ikcp_malloc_hook != null) + // return ikcp_malloc_hook(size); + // return malloc(size); + // } + + // // internal free + // public static void ikcp_free(void* ptr) + // { + // if (ikcp_free_hook != null) + // { + // ikcp_free_hook(ptr); + // } + // else + // { + // free(ptr); + // } + // } + + // // redefine allocator + // public static void ikcp_allocator(delegate* managed new_malloc, delegate* managed new_free) + // { + // ikcp_malloc_hook = new_malloc; + // ikcp_free_hook = new_free; + // } + + // allocate a new kcp segment + public static IKCPSEG* ikcp_segment_new(IKCPCB* kcp, int size) + { + return (IKCPSEG*)malloc((nuint)(sizeof(IKCPSEG) + size)); + } + + // delete a segment + public static void ikcp_segment_delete(IKCPCB* kcp, IKCPSEG* seg) + { + free(seg); + } + + // output segment + public static void ikcp_output(IKCPCB* kcp, int size, byte[] destination, KcpCallback output) + { + assert(kcp != null); + assert(output != null); + + if (size == 0) return; + output(destination, size); + } + + //--------------------------------------------------------------------- + // create a new kcpcb + //--------------------------------------------------------------------- + public static IKCPCB* ikcp_create(uint conv, int reserved, ref byte[] buffer) + { + IKCPCB* kcp = (IKCPCB*)malloc((nuint)sizeof(IKCPCB)); + if (kcp == null) return null; + kcp->conv = conv; + kcp->snd_una = 0; + kcp->snd_nxt = 0; + kcp->rcv_nxt = 0; + kcp->ts_recent = 0; + kcp->ts_lastack = 0; + kcp->ts_probe = 0; + kcp->probe_wait = 0; + kcp->snd_wnd = IKCP_WND_SND; + kcp->rcv_wnd = IKCP_WND_RCV; + kcp->rmt_wnd = IKCP_WND_RCV; + kcp->cwnd = 0; + kcp->incr = 0; + kcp->probe = 0; + kcp->mtu = IKCP_MTU_DEF; + kcp->mss = kcp->mtu - IKCP_OVERHEAD; + kcp->stream = 0; + + buffer = new byte[(reserved + kcp->mtu + IKCP_OVERHEAD) * 3]; + + iqueue_init(&kcp->snd_queue); + iqueue_init(&kcp->rcv_queue); + iqueue_init(&kcp->snd_buf); + iqueue_init(&kcp->rcv_buf); + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->state = 0; + kcp->acklist = null; + kcp->ackblock = 0; + kcp->ackcount = 0; + kcp->rx_srtt = 0; + kcp->rx_rttval = 0; + kcp->rx_rto = (int)IKCP_RTO_DEF; + kcp->rx_minrto = (int)IKCP_RTO_MIN; + kcp->current = 0; + kcp->interval = IKCP_INTERVAL; + kcp->ts_flush = IKCP_INTERVAL; + kcp->nodelay = 0; + kcp->updated = 0; + kcp->ssthresh = IKCP_THRESH_INIT; + kcp->fastresend = 0; + kcp->fastlimit = (int)IKCP_FASTACK_LIMIT; + kcp->nocwnd = 0; + kcp->xmit = 0; + kcp->dead_link = IKCP_DEADLINK; + + return kcp; + } + + //--------------------------------------------------------------------- + // release a new kcpcb + //--------------------------------------------------------------------- + public static void ikcp_release(IKCPCB* kcp) + { + assert(kcp != null); + if (kcp != null) + { + IKCPSEG* seg; + while (!iqueue_is_empty(&kcp->snd_buf)) + { + seg = iqueue_entry(kcp->snd_buf.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + seg = iqueue_entry(kcp->rcv_buf.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->snd_queue)) + { + seg = iqueue_entry(kcp->snd_queue.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->rcv_queue)) + { + seg = iqueue_entry(kcp->rcv_queue.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + if (kcp->acklist != null) + { + free(kcp->acklist); + } + + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->ackcount = 0; + kcp->acklist = null; + free(kcp); + } + } + + //--------------------------------------------------------------------- + // user/upper level recv: returns size, returns below zero for EAGAIN + //--------------------------------------------------------------------- + public static int ikcp_recv(IKCPCB* kcp, byte* buffer, int len) + { + IQUEUEHEAD* p; + int ispeek = (len < 0) ? 1 : 0; + int peeksize; + int recover = 0; + IKCPSEG* seg; + assert(kcp != null); + + if (iqueue_is_empty(&kcp->rcv_queue)) + return -1; + + if (len < 0) len = -len; + + peeksize = ikcp_peeksize(kcp); + + if (peeksize < 0) + return -2; + + if (peeksize > len) + return -3; + + if (kcp->nrcv_que >= kcp->rcv_wnd) + recover = 1; + + // merge fragment + for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue;) + { + int fragment; + seg = iqueue_entry(p); + p = p->next; + + if (buffer != null) + { + memcpy(buffer, seg->data, (nuint)seg->len); + buffer += seg->len; + } + + len += (int)seg->len; + fragment = (int)seg->frg; + + if (ispeek == 0) + { + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + kcp->nrcv_que--; + } + + if (fragment == 0) + break; + } + + assert(len == peeksize); + + // move available data from rcv_buf -> rcv_queue + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + seg = iqueue_entry(kcp->rcv_buf.next); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) + { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } + else + { + break; + } + } + + // fast recover + if (kcp->nrcv_que < kcp->rcv_wnd && (recover != 0)) + { + // ready to send back IKCP_CMD_WINS in ikcp_flush + // tell remote my window size + kcp->probe |= IKCP_ASK_TELL; + } + + return len; + } + + //--------------------------------------------------------------------- + // peek data size + //--------------------------------------------------------------------- + public static int ikcp_peeksize(IKCPCB* kcp) + { + IQUEUEHEAD* p; + IKCPSEG* seg; + int length = 0; + + assert(kcp != null); + + if (iqueue_is_empty(&kcp->rcv_queue)) return -1; + + seg = iqueue_entry(kcp->rcv_queue.next); + if (seg->frg == 0) return (int)seg->len; + + if (kcp->nrcv_que < seg->frg + 1) return -1; + + for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) + { + seg = iqueue_entry(p); + length += (int)seg->len; + if (seg->frg == 0) break; + } + + return length; + } + + //--------------------------------------------------------------------- + // user/upper level send, returns below zero for error + //--------------------------------------------------------------------- + public static int ikcp_send(IKCPCB* kcp, byte* buffer, int len) + { + IKCPSEG* seg; + int count, i; + int sent = 0; + + assert(kcp->mss > 0); + if (len < 0) return -1; + + // append to previous segment in streaming mode (if possible) + if (kcp->stream != 0) + { + if (!iqueue_is_empty(&kcp->snd_queue)) + { + IKCPSEG* old = iqueue_entry(kcp->snd_queue.prev); + if (old->len < kcp->mss) + { + int capacity = (int)(kcp->mss - old->len); + int extend = (len < capacity) ? len : capacity; + seg = ikcp_segment_new(kcp, (int)(old->len + extend)); + assert(seg != null); + if (seg == null) + { + return -2; + } + + iqueue_add_tail(&seg->node, &kcp->snd_queue); + memcpy(seg->data, old->data, (nuint)old->len); + if (buffer != null) + { + memcpy(seg->data + old->len, buffer, (nuint)extend); + buffer += extend; + } + + seg->len = (uint)(old->len + extend); + seg->frg = 0; + len -= extend; + iqueue_del_init(&old->node); + ikcp_segment_delete(kcp, old); + sent = extend; + } + } + + if (len <= 0) + { + return sent; + } + } + + if (len <= (int)kcp->mss) count = 1; + else count = (int)((len + kcp->mss - 1) / kcp->mss); + + if (kcp->stream == 0 && count > 255) return -2; + + if (count >= (int)kcp->rcv_wnd) + { + if (kcp->stream != 0 && sent > 0) + return sent; + return -2; + } + + if (count == 0) count = 1; + + // fragment + for (i = 0; i < count; i++) + { + int size = len > (int)kcp->mss ? (int)kcp->mss : len; + seg = ikcp_segment_new(kcp, size); + assert(seg != null); + if (seg == null) + { + return -2; + } + + if ((buffer != null) && len > 0) + { + memcpy(seg->data, buffer, (nuint)size); + } + + seg->len = (uint)size; + seg->frg = (uint)((kcp->stream == 0) ? (count - i - 1) : 0); + iqueue_init(&seg->node); + iqueue_add_tail(&seg->node, &kcp->snd_queue); + kcp->nsnd_que++; + if (buffer != null) + { + buffer += size; + } + + len -= size; + sent += size; + } + + return sent; + } + + //--------------------------------------------------------------------- + // parse ack + //--------------------------------------------------------------------- + public static void ikcp_update_ack(IKCPCB* kcp, int rtt) + { + int rto = 0; + if (kcp->rx_srtt == 0) + { + kcp->rx_srtt = rtt; + kcp->rx_rttval = rtt / 2; + } + else + { + long delta = rtt - kcp->rx_srtt; + if (delta < 0) delta = -delta; + kcp->rx_rttval = (int)((3 * kcp->rx_rttval + delta) / 4); + kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8; + if (kcp->rx_srtt < 1) kcp->rx_srtt = 1; + } + + rto = (int)(kcp->rx_srtt + _imax_(kcp->interval, (uint)(4 * kcp->rx_rttval))); + kcp->rx_rto = (int)_ibound_((uint)kcp->rx_minrto, (uint)rto, IKCP_RTO_MAX); + } + + public static void ikcp_shrink_buf(IKCPCB* kcp) + { + IQUEUEHEAD* p = kcp->snd_buf.next; + if (p != &kcp->snd_buf) + { + IKCPSEG* seg = iqueue_entry(p); + kcp->snd_una = seg->sn; + } + else + { + kcp->snd_una = kcp->snd_nxt; + } + } + + public static void ikcp_parse_ack(IKCPCB* kcp, uint sn) + { + IQUEUEHEAD* p, next; + + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + IKCPSEG* seg = iqueue_entry(p); + next = p->next; + if (sn == seg->sn) + { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + break; + } + + if (_itimediff(sn, seg->sn) < 0) + { + break; + } + } + } + + public static void ikcp_parse_una(IKCPCB* kcp, uint una) + { + IQUEUEHEAD* p, next; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + IKCPSEG* seg = iqueue_entry(p); + next = p->next; + if (_itimediff(una, seg->sn) > 0) + { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + } + else + { + break; + } + } + } + + public static void ikcp_parse_fastack(IKCPCB* kcp, uint sn, uint ts) + { + IQUEUEHEAD* p, next; + + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + IKCPSEG* seg = iqueue_entry(p); + next = p->next; + if (_itimediff(sn, seg->sn) < 0) + { + break; + } + else if (sn != seg->sn) + { +#if !IKCP_FASTACK_CONSERVE + seg->fastack++; +#else + if (_itimediff(ts, seg->ts) >= 0) + seg->fastack++; +#endif + } + } + } + + //--------------------------------------------------------------------- + // ack append + //--------------------------------------------------------------------- + public static void ikcp_ack_push(IKCPCB* kcp, uint sn, uint ts) + { + uint newsize = kcp->ackcount + 1; + uint* ptr; + + if (newsize > kcp->ackblock) + { + uint* acklist; + uint newblock; + + newblock = newsize <= 8 ? 8 : _iceilpow2_(newsize); + acklist = (uint*)malloc((nuint)(newblock * sizeof(uint) * 2)); + + if (acklist == null) + { + assert(acklist != null); + abort(); + } + + if (kcp->acklist != null) + { + uint x; + for (x = 0; x < kcp->ackcount; x++) + { + acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0]; + acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1]; + } + + free(kcp->acklist); + } + + kcp->acklist = acklist; + kcp->ackblock = newblock; + } + + ptr = &kcp->acklist[kcp->ackcount * 2]; + ptr[0] = sn; + ptr[1] = ts; + kcp->ackcount++; + } + + public static void ikcp_ack_get(IKCPCB* kcp, int p, uint* sn, uint* ts) + { + if (sn != null) sn[0] = kcp->acklist[p * 2 + 0]; + if (ts != null) ts[0] = kcp->acklist[p * 2 + 1]; + } + + //--------------------------------------------------------------------- + // parse data + //--------------------------------------------------------------------- + public static void ikcp_parse_data(IKCPCB* kcp, IKCPSEG* newseg) + { + IQUEUEHEAD* p, prev; + uint sn = newseg->sn; + int repeat = 0; + + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 || + _itimediff(sn, kcp->rcv_nxt) < 0) + { + ikcp_segment_delete(kcp, newseg); + return; + } + + for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) + { + IKCPSEG* seg = iqueue_entry(p); + prev = p->prev; + if (seg->sn == sn) + { + repeat = 1; + break; + } + + if (_itimediff(sn, seg->sn) > 0) + { + break; + } + } + + if (repeat == 0) + { + iqueue_init(&newseg->node); + iqueue_add(&newseg->node, p); + kcp->nrcv_buf++; + } + else + { + ikcp_segment_delete(kcp, newseg); + } + + // move available data from rcv_buf -> rcv_queue + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + IKCPSEG* seg = iqueue_entry(kcp->rcv_buf.next); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) + { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } + else + { + break; + } + } + } + + //--------------------------------------------------------------------- + // input data + //--------------------------------------------------------------------- + public static int ikcp_input(IKCPCB* kcp, byte* data, long size) + { + uint prev_una = kcp->snd_una; + uint maxack = 0, latest_ts = 0; + int flag = 0; + + if (data == null || (int)size < (int)IKCP_OVERHEAD) return -1; + + while (true) + { + uint ts, sn, len, una, conv; + ushort wnd; + byte cmd, frg; + IKCPSEG* seg; + + if (size < (int)IKCP_OVERHEAD) break; + + data = ikcp_decode32u(data, &conv); + if (conv != kcp->conv) return -1; + + data = ikcp_decode8u(data, &cmd); + data = ikcp_decode8u(data, &frg); + data = ikcp_decode16u(data, &wnd); + data = ikcp_decode32u(data, &ts); + data = ikcp_decode32u(data, &sn); + data = ikcp_decode32u(data, &una); + data = ikcp_decode32u(data, &len); + + size -= IKCP_OVERHEAD; + + if ((long)size < (long)len || (int)len < 0) return -2; + + if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK && + cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS) + return -3; + + kcp->rmt_wnd = wnd; + ikcp_parse_una(kcp, una); + ikcp_shrink_buf(kcp); + + if (cmd == IKCP_CMD_ACK) + { + if (_itimediff(kcp->current, ts) >= 0) + { + ikcp_update_ack(kcp, (int)_itimediff(kcp->current, ts)); + } + + ikcp_parse_ack(kcp, sn); + ikcp_shrink_buf(kcp); + if (flag == 0) + { + flag = 1; + maxack = sn; + latest_ts = ts; + } + else + { + if (_itimediff(sn, maxack) > 0) + { +#if !IKCP_FASTACK_CONSERVE + maxack = sn; + latest_ts = ts; +#else + if (_itimediff(ts, latest_ts) > 0) + { + maxack = sn; + latest_ts = ts; + } +#endif + } + } + } + else if (cmd == IKCP_CMD_PUSH) + { + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) + { + ikcp_ack_push(kcp, sn, ts); + if (_itimediff(sn, kcp->rcv_nxt) >= 0) + { + seg = ikcp_segment_new(kcp, (int)len); + seg->conv = conv; + seg->cmd = cmd; + seg->frg = frg; + seg->wnd = wnd; + seg->ts = ts; + seg->sn = sn; + seg->una = una; + seg->len = len; + + if (len > 0) + { + memcpy(seg->data, data, (nuint)len); + } + + ikcp_parse_data(kcp, seg); + } + } + } + else if (cmd == IKCP_CMD_WASK) + { + // ready to send back IKCP_CMD_WINS in ikcp_flush + // tell remote my window size + kcp->probe |= IKCP_ASK_TELL; + } + else if (cmd == IKCP_CMD_WINS) + { + // do nothing + } + else + { + return -3; + } + + data += len; + size -= len; + } + + if (flag != 0) + { + ikcp_parse_fastack(kcp, maxack, latest_ts); + } + + if (_itimediff(kcp->snd_una, prev_una) > 0) + { + if (kcp->cwnd < kcp->rmt_wnd) + { + uint mss = kcp->mss; + if (kcp->cwnd < kcp->ssthresh) + { + kcp->cwnd++; + kcp->incr += mss; + } + else + { + if (kcp->incr < mss) kcp->incr = mss; + kcp->incr += (mss * mss) / kcp->incr + (mss / 16); + if ((kcp->cwnd + 1) * mss <= kcp->incr) + { + kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0) ? mss : 1); + } + } + + if (kcp->cwnd > kcp->rmt_wnd) + { + kcp->cwnd = kcp->rmt_wnd; + kcp->incr = kcp->rmt_wnd * mss; + } + } + } + + return 0; + } + + //--------------------------------------------------------------------- + // ikcp_encode_seg + //--------------------------------------------------------------------- + public static byte* ikcp_encode_seg(byte* ptr, IKCPSEG* seg) + { + ptr = ikcp_encode32u(ptr, seg->conv); + ptr = ikcp_encode8u(ptr, (byte)seg->cmd); + ptr = ikcp_encode8u(ptr, (byte)seg->frg); + ptr = ikcp_encode16u(ptr, (ushort)seg->wnd); + ptr = ikcp_encode32u(ptr, seg->ts); + ptr = ikcp_encode32u(ptr, seg->sn); + ptr = ikcp_encode32u(ptr, seg->una); + ptr = ikcp_encode32u(ptr, seg->len); + return ptr; + } + + public static int ikcp_wnd_unused(IKCPCB* kcp) + { + if (kcp->nrcv_que < kcp->rcv_wnd) + { + return (int)(kcp->rcv_wnd - kcp->nrcv_que); + } + + return 0; + } + + //--------------------------------------------------------------------- + // ikcp_flush + //--------------------------------------------------------------------- + public static void ikcp_flush(IKCPCB* kcp, byte* buffer, byte[] destination, KcpCallback output) + { + uint current = kcp->current; + byte* ptr = buffer; + int count, size, i; + uint resent, cwnd; + uint rtomin; + IQUEUEHEAD* p; + int change = 0; + int lost = 0; + IKCPSEG seg; + + // 'ikcp_update' haven't been called. + if (kcp->updated == 0) return; + + seg.conv = kcp->conv; + seg.cmd = IKCP_CMD_ACK; + seg.frg = 0; + seg.wnd = (uint)ikcp_wnd_unused(kcp); + seg.una = kcp->rcv_nxt; + seg.len = 0; + seg.sn = 0; + seg.ts = 0; + + // flush acknowledges + count = (int)kcp->ackcount; + for (i = 0; i < count; i++) + { + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) + { + ikcp_output(kcp, size, destination, output); + ptr = buffer; + } + + ikcp_ack_get(kcp, i, &seg.sn, &seg.ts); + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->ackcount = 0; + + // probe window size (if remote window size equals zero) + if (kcp->rmt_wnd == 0) + { + if (kcp->probe_wait == 0) + { + kcp->probe_wait = IKCP_PROBE_INIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + } + else + { + if (_itimediff(kcp->current, kcp->ts_probe) >= 0) + { + if (kcp->probe_wait < IKCP_PROBE_INIT) + kcp->probe_wait = IKCP_PROBE_INIT; + kcp->probe_wait += kcp->probe_wait / 2; + if (kcp->probe_wait > IKCP_PROBE_LIMIT) + kcp->probe_wait = IKCP_PROBE_LIMIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + kcp->probe |= IKCP_ASK_SEND; + } + } + } + else + { + kcp->ts_probe = 0; + kcp->probe_wait = 0; + } + + // flush window probing commands + if ((kcp->probe & IKCP_ASK_SEND) != 0) + { + seg.cmd = IKCP_CMD_WASK; + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) + { + ikcp_output(kcp, size, destination, output); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, &seg); + } + + // flush window probing commands + if ((kcp->probe & IKCP_ASK_TELL) != 0) + { + seg.cmd = IKCP_CMD_WINS; + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) + { + ikcp_output(kcp, size, destination, output); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->probe = 0; + + // calculate window size + cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd); + if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd); + + // move data from snd_queue to snd_buf + while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) + { + IKCPSEG* newseg; + if (iqueue_is_empty(&kcp->snd_queue)) break; + + newseg = iqueue_entry(kcp->snd_queue.next); + + iqueue_del(&newseg->node); + iqueue_add_tail(&newseg->node, &kcp->snd_buf); + kcp->nsnd_que--; + kcp->nsnd_buf++; + + newseg->conv = kcp->conv; + newseg->cmd = IKCP_CMD_PUSH; + newseg->wnd = seg.wnd; + newseg->ts = current; + newseg->sn = kcp->snd_nxt++; + newseg->una = kcp->rcv_nxt; + newseg->resendts = current; + newseg->rto = (uint)kcp->rx_rto; + newseg->fastack = 0; + newseg->xmit = 0; + } + + // calculate resent + resent = (kcp->fastresend > 0) ? (uint)kcp->fastresend : 0xffffffff; + rtomin = (uint)((kcp->nodelay == 0) ? (kcp->rx_rto >> 3) : 0); + + // flush data segments + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + IKCPSEG* segment = iqueue_entry(p); + int needsend = 0; + if (segment->xmit == 0) + { + needsend = 1; + segment->xmit++; + segment->rto = (uint)kcp->rx_rto; + segment->resendts = current + segment->rto + rtomin; + } + else if (_itimediff(current, segment->resendts) >= 0) + { + needsend = 1; + segment->xmit++; + kcp->xmit++; + if (kcp->nodelay == 0) + { + segment->rto += _imax_(segment->rto, (uint)kcp->rx_rto); + } + else + { + int step = (kcp->nodelay < 2) ? ((int)(segment->rto)) : kcp->rx_rto; + segment->rto += (uint)(step / 2); + } + + segment->resendts = current + segment->rto; + lost = 1; + } + else if (segment->fastack >= resent) + { + if ((int)segment->xmit <= kcp->fastlimit || + kcp->fastlimit <= 0) + { + needsend = 1; + segment->xmit++; + segment->fastack = 0; + segment->resendts = current + segment->rto; + change++; + } + } + + if (needsend != 0) + { + int need; + segment->ts = current; + segment->wnd = seg.wnd; + segment->una = kcp->rcv_nxt; + + size = (int)(ptr - buffer); + need = (int)(IKCP_OVERHEAD + segment->len); + + if (size + need > (int)kcp->mtu) + { + ikcp_output(kcp, size, destination, output); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, segment); + + if (segment->len > 0) + { + memcpy(ptr, segment->data, (nuint)segment->len); + ptr += segment->len; + } + + if (segment->xmit >= kcp->dead_link) + { + kcp->state = unchecked((uint)(-1)); + } + } + } + + // flash remain segments + size = (int)(ptr - buffer); + if (size > 0) + { + ikcp_output(kcp, size, destination, output); + } + + // update ssthresh + if (change != 0) + { + uint inflight = kcp->snd_nxt - kcp->snd_una; + kcp->ssthresh = inflight / 2; + if (kcp->ssthresh < IKCP_THRESH_MIN) + kcp->ssthresh = IKCP_THRESH_MIN; + kcp->cwnd = kcp->ssthresh + resent; + kcp->incr = kcp->cwnd * kcp->mss; + } + + if (lost != 0) + { + kcp->ssthresh = cwnd / 2; + if (kcp->ssthresh < IKCP_THRESH_MIN) + kcp->ssthresh = IKCP_THRESH_MIN; + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } + + if (kcp->cwnd < 1) + { + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } + } + + public static void ikcp_update(IKCPCB* kcp, uint current, byte* buffer, byte[] destination, KcpCallback output) + { + int slap; + + kcp->current = current; + + if (kcp->updated == 0) + { + kcp->updated = 1; + kcp->ts_flush = kcp->current; + } + + slap = (int)_itimediff(kcp->current, kcp->ts_flush); + + if (slap >= 10000 || slap < -10000) + { + kcp->ts_flush = kcp->current; + slap = 0; + } + + if (slap >= 0) + { + kcp->ts_flush += kcp->interval; + if (_itimediff(kcp->current, kcp->ts_flush) >= 0) + { + kcp->ts_flush = kcp->current + kcp->interval; + } + + ikcp_flush(kcp, buffer, destination, output); + } + } + + //--------------------------------------------------------------------- + // Determine when should you invoke ikcp_update: + // returns when you should invoke ikcp_update in millisec, if there + // is no ikcp_input/_send calling. you can call ikcp_update in that + // time, instead of call update repeatly. + // Important to reduce unnacessary ikcp_update invoking. use it to + // schedule ikcp_update (eg. implementing an epoll-like mechanism, + // or optimize ikcp_update when handling massive kcp connections) + //--------------------------------------------------------------------- + public static uint ikcp_check(IKCPCB* kcp, uint current) + { + uint ts_flush = kcp->ts_flush; + int tm_flush = 0x7fffffff; + int tm_packet = 0x7fffffff; + uint minimal = 0; + IQUEUEHEAD* p; + + if (kcp->updated == 0) + { + return current; + } + + if (_itimediff(current, ts_flush) >= 10000 || + _itimediff(current, ts_flush) < -10000) + { + ts_flush = current; + } + + if (_itimediff(current, ts_flush) >= 0) + { + return current; + } + + tm_flush = (int)_itimediff(ts_flush, current); + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + IKCPSEG* seg = iqueue_entry(p); + int diff = (int)_itimediff(seg->resendts, current); + if (diff <= 0) + { + return current; + } + + if (diff < tm_packet) tm_packet = diff; + } + + minimal = (uint)(tm_packet < tm_flush ? tm_packet : tm_flush); + if (minimal >= kcp->interval) minimal = kcp->interval; + + return current + minimal; + } + + public static int ikcp_setmtu(IKCPCB* kcp, int mtu, int reserved, ref byte[] buffer) + { + if (mtu < 50 || mtu < (int)IKCP_OVERHEAD) + return -1; + buffer = new byte[(reserved + mtu + IKCP_OVERHEAD) * 3]; + if (buffer == null) + return -2; + kcp->mtu = (uint)mtu; + kcp->mss = kcp->mtu - IKCP_OVERHEAD; + return 0; + } + + public static int ikcp_interval(IKCPCB* kcp, int interval) + { + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + kcp->interval = (uint)interval; + return 0; + } + + public static int ikcp_nodelay(IKCPCB* kcp, int nodelay, int interval, int resend, int nc) + { + if (nodelay >= 0) + { + kcp->nodelay = (uint)nodelay; + if (nodelay != 0) + { + kcp->rx_minrto = (int)IKCP_RTO_NDL; + } + else + { + kcp->rx_minrto = (int)IKCP_RTO_MIN; + } + } + + if (interval >= 0) + { + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + kcp->interval = (uint)interval; + } + + if (resend >= 0) + { + kcp->fastresend = resend; + } + + if (nc >= 0) + { + kcp->nocwnd = nc; + } + + return 0; + } + + public static int ikcp_wndsize(IKCPCB* kcp, int sndwnd, int rcvwnd) + { + if (kcp != null) + { + if (sndwnd > 0) + { + kcp->snd_wnd = (uint)sndwnd; + } + + if (rcvwnd > 0) + { + // must >= max fragment size + kcp->rcv_wnd = _imax_((uint)rcvwnd, IKCP_WND_RCV); + } + } + + return 0; + } + + public static int ikcp_waitsnd(IKCPCB* kcp) + { + return (int)(kcp->nsnd_buf + kcp->nsnd_que); + } + + // read conv + public static uint ikcp_getconv(void* ptr) + { + uint conv; + ikcp_decode32u((byte*)ptr, &conv); + return conv; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs.meta new file mode 100644 index 0000000..2051166 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/c/kcp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ec1687787304abc46b28c13da20cac7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define.meta new file mode 100644 index 0000000..460c59d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 898c342658e10654499dc2f6eab1588e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs new file mode 100644 index 0000000..fec2d37 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs @@ -0,0 +1,41 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +#pragma warning disable CS1591 + +// ReSharper disable ALL + +namespace kcp +{ + internal static unsafe partial class KCP + { + private static void* malloc(nuint size) + { +#if NET6_0_OR_GREATER + return NativeMemory.Alloc((nuint)size); +#else + return (void*)Marshal.AllocHGlobal((nint)size); +#endif + } + + private static void free(void* memory) + { +#if NET6_0_OR_GREATER + NativeMemory.Free(memory); +#else + Marshal.FreeHGlobal((nint)memory); +#endif + } + + private static void memcpy(void* dst, void* src, nuint size) => Unsafe.CopyBlockUnaligned(dst, src, (uint)size); + + private static void memset(void* dst, byte val, nuint size) => Unsafe.InitBlockUnaligned(dst, val, (uint)size); + + [Conditional("DEBUG")] + private static void assert(bool condition) => Debug.Assert(condition); + + private static void abort() => Environment.Exit(-1); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs.meta new file mode 100644 index 0000000..4ce1649 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/define/system.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b41dff3d194ce05439e691a580d97787 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include.meta new file mode 100644 index 0000000..4b07143 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6bdc2b6cbc41a82498232e24500bf423 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs new file mode 100644 index 0000000..838cc09 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs @@ -0,0 +1,127 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +#pragma warning disable CS1591 + +// ReSharper disable ALL + +namespace kcp +{ + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IQUEUEHEAD + { + public IQUEUEHEAD* next; + public IQUEUEHEAD* prev; + } + + internal static unsafe partial class KCP + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_init(IQUEUEHEAD* head) + { + head->next = head; + head->prev = head; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T* iqueue_entry(IQUEUEHEAD* ptr) where T : unmanaged => ((T*)(((byte*)((T*)ptr)))); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_add(IQUEUEHEAD* node, IQUEUEHEAD* head) + { + node->prev = head; + node->next = head->next; + head->next->prev = node; + head->next = node; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_add_tail(IQUEUEHEAD* node, IQUEUEHEAD* head) + { + node->prev = head->prev; + node->next = head; + head->prev->next = node; + head->prev = node; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_del(IQUEUEHEAD* entry) + { + entry->next->prev = entry->prev; + entry->prev->next = entry->next; + entry->next = (IQUEUEHEAD*)0; + entry->prev = (IQUEUEHEAD*)0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_del_init(IQUEUEHEAD* entry) + { + iqueue_del(entry); + iqueue_init(entry); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool iqueue_is_empty(IQUEUEHEAD* entry) => entry == entry->next; + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IKCPSEG + { + public IQUEUEHEAD node; + public uint conv; + public uint cmd; + public uint frg; + public uint wnd; + public uint ts; + public uint sn; + public uint una; + public uint len; + public uint resendts; + public uint rto; + public uint fastack; + public uint xmit; + public fixed byte data[1]; + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IKCPCB + { + public uint conv, mtu, mss, state; + public uint snd_una, snd_nxt, rcv_nxt; + public uint ts_recent, ts_lastack, ssthresh; + public int rx_rttval, rx_srtt, rx_rto, rx_minrto; + public uint snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe; + public uint current, interval, ts_flush, xmit; + public uint nrcv_buf, nsnd_buf; + public uint nrcv_que, nsnd_que; + public uint nodelay, updated; + public uint ts_probe, probe_wait; + public uint dead_link, incr; + public IQUEUEHEAD snd_queue; + public IQUEUEHEAD rcv_queue; + public IQUEUEHEAD snd_buf; + public IQUEUEHEAD rcv_buf; + public uint* acklist; + public uint ackcount; + public uint ackblock; + public int fastresend; + public int fastlimit; + public int nocwnd, stream; + } + + internal static partial class KCP + { + public const uint IKCP_LOG_OUTPUT = 1; + public const uint IKCP_LOG_INPUT = 2; + public const uint IKCP_LOG_SEND = 4; + public const uint IKCP_LOG_RECV = 8; + public const uint IKCP_LOG_IN_DATA = 16; + public const uint IKCP_LOG_IN_ACK = 32; + public const uint IKCP_LOG_IN_PROBE = 64; + public const uint IKCP_LOG_IN_WINS = 128; + public const uint IKCP_LOG_OUT_DATA = 256; + public const uint IKCP_LOG_OUT_ACK = 512; + public const uint IKCP_LOG_OUT_PROBE = 1024; + public const uint IKCP_LOG_OUT_WINS = 2048; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs.meta new file mode 100644 index 0000000..94bacf0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Base/include/kcp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f7e3418aad4857642a7b031532f8337c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client.meta new file mode 100644 index 0000000..e2e264f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 59d6f259f9af9f04eb8173f565bb5f6a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs new file mode 100644 index 0000000..835938a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs @@ -0,0 +1,697 @@ +#if !FANTASY_WEBGL +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Threading; +using Fantasy.Async; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using KCP; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable PossibleNullReferenceException +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +namespace Fantasy.Network.KCP +{ + internal sealed class KCPClientNetworkUpdateSystem : UpdateSystem + { + protected override void Update(KCPClientNetwork self) + { + self.CheckUpdate(); + } + } + internal sealed class KCPClientNetwork : AClientNetwork + { + private Kcp _kcp; + private Socket _socket; + private int _maxSndWnd; + private long _startTime; + private bool _isConnected; + private bool _isDisconnect; + private uint _updateMinTime; + private bool _isInnerDispose; + private long _connectTimeoutId; + private bool _allowWraparound = true; + private IPEndPoint _remoteAddress; + private BufferPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly byte[] _sendBuff = new byte[5]; + private readonly byte[] _receiveBuffer = new byte[Packet.PacketBodyMaxLength + 20]; + private readonly List _updateTimeOutTime = new List(); + private readonly SortedSet _updateTimer = new SortedSet(); + private readonly SocketAsyncEventArgs _connectEventArgs = new SocketAsyncEventArgs(); + private readonly Queue _messageCache = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); +#if FANTASY_UNITY + private readonly EndPoint _ipEndPoint = new IPEndPoint(IPAddress.Any, 0); +#endif + private event Action OnConnectFail; + private event Action OnConnectComplete; + private event Action OnConnectDisconnect; + public uint ChannelId { get; private set; } + private uint TimeNow => (uint) (TimeHelper.Now - _startTime); + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.KCP, networkTarget); + _packetParser = PacketParserFactory.CreateClientBufferPacket(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + try + { + _isInnerDispose = true; + + if (!_isDisconnect) + { + SendDisconnect(); + } + + ClearConnectTimeout(); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + OnConnectDisconnect?.Invoke(); + _kcp.Dispose(); + + if (_socket.Connected) + { + _socket.Close(); + } + + _packetParser.Dispose(); + ChannelId = 0; + _isConnected = false; + _messageCache.Clear(); + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + #region Connect + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + if (IsInit) + { + throw new NotSupportedException($"KCPClientNetwork Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _startTime = TimeHelper.Now; + ChannelId = CreateChannelId(); + _remoteAddress = NetworkHelper.GetIPEndPoint(remoteAddress); + OnConnectFail = onConnectFail; + OnConnectComplete = onConnectComplete; + OnConnectDisconnect = onConnectDisconnect; + _connectEventArgs.Completed += OnConnectSocketCompleted; + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + OnConnectFail?.Invoke(); + Dispose(); + }); + _connectEventArgs.RemoteEndPoint = _remoteAddress; + _socket = new Socket(_remoteAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + _socket.Blocking = false; + _socket.SetSocketBufferToOsLimit(); + _socket.SetSioUdpConnReset(); + _socket.Bind(new IPEndPoint(IPAddress.Any, 0)); + _kcp = KCPFactory.Create(NetworkTarget, ChannelId, KcpSpanCallback, out var kcpSettings); + _maxSndWnd = kcpSettings.MaxSendWindowSize; + + if (!_socket.ConnectAsync(_connectEventArgs)) + { + try + { + OnReceiveSocketComplete(); + } + catch (Exception e) + { + Log.Error(e); + OnConnectFail?.Invoke(); + } + } + + Session = Session.Create(this, _remoteAddress); + return Session; + } + + private void OnConnectSocketCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + if (asyncEventArgs.LastOperation == SocketAsyncOperation.Connect) + { + if (asyncEventArgs.SocketError == SocketError.Success) + { + Scene.ThreadSynchronizationContext.Post(OnReceiveSocketComplete); + } + else + { + Scene.ThreadSynchronizationContext.Post(() => + { + OnConnectFail?.Invoke(); + Dispose(); + }); + } + } + } + + private void OnReceiveSocketComplete() + { + SendRequestConnection(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + #endregion + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); +#if FANTASY_UNITY + MemoryMarshal.TryGetArray(memory, out ArraySegment arraySegment); + var result = await _socket.ReceiveFromAsync(arraySegment, SocketFlags.None, _ipEndPoint); + _pipe.Writer.Advance(result.ReceivedBytes); + await _pipe.Writer.FlushAsync(); +#else + var result = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + _pipe.Writer.Advance(result); + await _pipe.Writer.FlushAsync(); +#endif + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var header, out var channelId, out var message)) + { + ReceiveData(ref header, ref channelId, ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + } + + private unsafe bool TryReadMessage(ref ReadOnlySequence buffer, out KcpHeader header, out uint channelId, out ReadOnlyMemory message) + { + if (buffer.Length < 5) + { + channelId = 0; + message = default; + header = KcpHeader.None; + if (buffer.Length > 0) + { + buffer = buffer.Slice(buffer.Length); + } + return false; + } + + var readOnlyMemory = buffer.First; + + if (MemoryMarshal.TryGetArray(readOnlyMemory, out var arraySegment)) + { + fixed (byte* bytePointer = &arraySegment.Array[arraySegment.Offset]) + { + header = (KcpHeader)bytePointer[0]; + channelId = Unsafe.ReadUnaligned(ref bytePointer[1]); + } + } + else + { + // 如果无法获取数组段,回退到安全代码来执行。这种情况几乎不会发生、为了保险还是写一下了。 + var firstSpan = readOnlyMemory.Span; + header = (KcpHeader)firstSpan[0]; + channelId = MemoryMarshal.Read(firstSpan.Slice(1, 4)); + + } + + message = readOnlyMemory.Slice(5); + buffer = buffer.Slice(readOnlyMemory.Length); + return true; + } + + private void ReceiveData(ref KcpHeader header, ref uint channelId, ref ReadOnlyMemory buffer) + { + switch (header) + { + // 发送握手给服务器 + case KcpHeader.RepeatChannelId: + { + // 到这里是客户端的channelId再服务器上已经存在、需要重新生成一个再次尝试连接 + ChannelId = CreateChannelId(); + SendRequestConnection(); + break; + } + // 收到服务器发送会来的确认握手 + case KcpHeader.WaitConfirmConnection: + { + if (channelId != ChannelId) + { + break; + } + + ClearConnectTimeout(); + SendConfirmConnection(); + OnConnectComplete?.Invoke(); + _isConnected = true; + while (_messageCache.TryDequeue(out var memoryStream)) + { + SendMemoryStream(memoryStream); + } + break; + } + // 收到服务器发送的消息 + case KcpHeader.ReceiveData: + { + if (buffer.Length == 5) + { + Log.Warning($"KCP Server KcpHeader.Data buffer.Length == 5"); + break; + } + + if (channelId != ChannelId) + { + break; + } + + Input(buffer); + break; + } + // 接收到服务器的断开连接消息 + case KcpHeader.Disconnect: + { + if (channelId != ChannelId) + { + break; + } + + _isDisconnect = true; + Dispose(); + break; + } + } + } + + private void Input(ReadOnlyMemory buffer) + { + _kcp.Input(buffer.Span); + AddToUpdate(0); + + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var peekSize = _kcp.PeekSize(); + + if (peekSize < 0) + { + return; + } + + var receiveCount = _kcp.Receive(_receiveBuffer.AsSpan(0, peekSize)); + + if (receiveCount != peekSize) + { + return; + } + + if (!_packetParser.UnPack(_receiveBuffer, ref receiveCount, out var packInfo)) + { + continue; + } + + Session.Receive(packInfo); + } + catch (ScanException e) + { + Log.Debug($"RemoteAddress:{_remoteAddress} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + #endregion + + #region Update + + public void CheckUpdate() + { + var nowTime = TimeNow; + _allowWraparound = nowTime < _updateMinTime; + + if (IsTimeGreaterThan(nowTime, _updateMinTime) && _updateTimer.Count > 0) + { + foreach (var timeId in _updateTimer) + { + if (IsTimeGreaterThan(timeId, nowTime)) + { + _updateMinTime = timeId; + break; + } + + _updateTimeOutTime.Add(timeId); + } + + foreach (var timeId in _updateTimeOutTime) + { + _updateTimer.Remove(timeId); + KcpUpdate(); + } + + _updateTimeOutTime.Clear(); + } + + _allowWraparound = true; + } + + private void AddToUpdate(uint tillTime) + { + if (tillTime == 0) + { + KcpUpdate(); + return; + } + + if (IsTimeGreaterThan(_updateMinTime, tillTime) || _updateMinTime == 0) + { + _updateMinTime = tillTime; + } + + _updateTimer.Add(tillTime); + } + + private void KcpUpdate() + { + var nowTime = TimeNow; + + try + { + _kcp.Update(nowTime); + } + catch (Exception e) + { + Log.Error(e); + } + + AddToUpdate(_kcp.Check(nowTime)); + } + + private const uint HalfMaxUint = uint.MaxValue / 2; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool IsTimeGreaterThan(uint timeId, uint nowTime) + { + if (!_allowWraparound) + { + return timeId > nowTime; + } + var diff = timeId - nowTime; + // 如果 diff 的值在 [0, HalfMaxUint] 范围内,说明 timeId 是在 nowTime 之后或相等。 + // 如果 diff 的值在 (HalfMaxUint, uint.MaxValue] 范围内,说明 timeId 是在 nowTime 之前(时间回绕的情况)。 + return diff < HalfMaxUint || diff == HalfMaxUint; + } + + #endregion + + #region Send + + private const byte KcpHeaderDisconnect = (byte)KcpHeader.Disconnect; + private const byte KcpHeaderReceiveData = (byte)KcpHeader.ReceiveData; + private const byte KcpHeaderRequestConnection = (byte)KcpHeader.RequestConnection; + private const byte KcpHeaderConfirmConnection = (byte)KcpHeader.ConfirmConnection; + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + + if (!_isConnected) + { + _messageCache.Enqueue(buffer); + return; + } + + SendMemoryStream(buffer); + } + + private void SendMemoryStream(MemoryStreamBuffer memoryStream) + { + if (_kcp.WaitSendCount > _maxSndWnd) + { + // 检查等待发送的消息,如果超出两倍窗口大小,KCP作者给的建议是要断开连接 + Log.Warning($"ERR_KcpWaitSendSizeTooLarge {_kcp.WaitSendCount} > {_maxSndWnd}"); + Dispose(); + return; + } + + try + { + _kcp.Send(memoryStream.GetBuffer().AsSpan(0, (int)memoryStream.Position)); + AddToUpdate(0); + } + finally + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + private unsafe void SendRequestConnection() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderRequestConnection; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private unsafe void SendConfirmConnection() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderConfirmConnection; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private unsafe void SendDisconnect() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderDisconnect; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SendAsync(byte[] buffer, int offset, int count) + { + try + { + _socket.Send(new ArraySegment(buffer, offset, count), SocketFlags.None); + } + catch (ArgumentException ex) + { + Log.Error($"ArgumentException: {ex.Message}"); // 处理参数错误 + } + catch (SocketException) + { + //Log.Error($"SocketException: {ex.Message}"); // 处理网络错误 + Dispose(); + } + catch (ObjectDisposedException ex) + { + Log.Error($"ObjectDisposedException: {ex.Message}"); // 处理套接字已关闭的情况 + Dispose(); + } + catch (InvalidOperationException ex) + { + Log.Error($"InvalidOperationException: {ex.Message}"); // 处理无效操作 + } + catch (Exception ex) + { + Log.Error($"Exception: {ex.Message}"); // 捕获其他异常 + } + } + + private unsafe void KcpSpanCallback(byte[] buffer, int count) + { + if (IsDisposed) + { + return; + } + + if (count == 0) + { + throw new Exception("KcpOutput count 0"); + } + + fixed (byte* p = buffer) + { + p[0] = KcpHeaderReceiveData; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(buffer, 0, count + 5); + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net.Remove(ref _connectTimeoutId); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static unsafe uint CreateChannelId() + { + uint value; + RandomNumberGenerator.Fill(MemoryMarshal.CreateSpan(ref *(byte*)&value, 4)); + return 0xC0000000 | (value & int.MaxValue); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta new file mode 100644 index 0000000..21a9a47 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29e6fbf8eff739646b2363fd776a79f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs new file mode 100644 index 0000000..d7ca536 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs @@ -0,0 +1,91 @@ +#if !FANTASY_WEBGL +using System; +using KCP; + +#pragma warning disable CS1591 +namespace Fantasy.Network.KCP +{ + public class KCPSettings + { + public int Mtu { get; private set; } + public int SendWindowSize { get; private set; } + public int ReceiveWindowSize { get; private set; } + public int MaxSendWindowSize { get; private set; } + + public static KCPSettings Create(NetworkTarget networkTarget) + { + var settings = new KCPSettings(); + + switch (networkTarget) + { + case NetworkTarget.Outer: + { + // 外网设置470的原因: + // 1、mtu设置过大有可能路由器过滤掉 + // 2、降低 mtu 到 470,同样数据虽然会发更多的包,但是小包在路由层优先级更高 + settings.Mtu = 470; +#if FANTASY_NET + settings.SendWindowSize = 8192; + settings.ReceiveWindowSize = 8192; + settings.MaxSendWindowSize = 8192 * 8192 * 7; +#endif +#if FANTASY_UNITY || FANTASY_CONSOLE + settings.SendWindowSize = 512; + settings.ReceiveWindowSize = 512; + settings.MaxSendWindowSize = 512 * 512 * 7; +#endif + + break; + } +#if FANTASY_NET + case NetworkTarget.Inner: + { + // 内网设置1400的原因 + // 1、一般都是同一台服务器来运行多个进程来处理 + // 2、内网每个进程跟其他进程只有一个通道进行发送、所以发送的数量会比较大 + // 3、如果不把窗口设置大点、会出现消息滞后。 + // 4、因为内网发送的可不只是外网转发数据、还有可能是其他进程的通讯 + settings.Mtu = 1200; + settings.SendWindowSize = 8192; + settings.ReceiveWindowSize = 8192; + settings.MaxSendWindowSize = 8192 * 8192 * 7; + break; + } +#endif + default: + { + throw new NotSupportedException($"KCPServerNetwork NotSupported NetworkType:{networkTarget}"); + } + } + + return settings; + } + } + + internal static class KCPFactory + { + public const int FANTASY_KCP_RESERVED_HEAD = 5; + + public static Kcp Create(NetworkTarget networkTarget, uint conv, KcpCallback output, out KCPSettings kcpSettings) + { + var kcp = new Kcp(conv, output, FANTASY_KCP_RESERVED_HEAD); + kcpSettings = KCPSettings.Create(networkTarget); + kcp.SetNoDelay(1, 5, 2, 1); + kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize); + kcp.SetMtu(kcpSettings.Mtu); + kcp.SetMinrto(30); + return kcp; + } + + public static Kcp Create(KCPSettings kcpSettings, uint conv, KcpCallback output) + { + var kcp = new Kcp(conv, output, FANTASY_KCP_RESERVED_HEAD); + kcp.SetNoDelay(1, 5, 2, 1); + kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize); + kcp.SetMtu(kcpSettings.Mtu); + kcp.SetMinrto(30); + return kcp; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs.meta new file mode 100644 index 0000000..01a2360 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KCPSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15cc4c409b867d44aa02cfe3ec5e810f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs new file mode 100644 index 0000000..5ad606e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs @@ -0,0 +1,14 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.KCP +{ + internal enum KcpHeader : byte + { + None = 0x00, + RequestConnection = 0x01, + WaitConfirmConnection = 0x02, + ConfirmConnection = 0x03, + RepeatChannelId = 0x04, + ReceiveData = 0x06, + Disconnect = 0x07 + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs.meta new file mode 100644 index 0000000..95c4651 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/KcpHeader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35241d1404dc3ba49b7fc16bbd0dadf1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server.meta new file mode 100644 index 0000000..5ff3e66 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 27dafcf4519821349a8672ec5a7f22fb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs new file mode 100644 index 0000000..0fb4e29 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs @@ -0,0 +1,575 @@ +// #if FANTASY_NET +// using System.Buffers; +// using System.Net; +// using System.Net.Sockets; +// using System.Runtime.CompilerServices; +// using System.Runtime.InteropServices; +// using Fantasy.Async; +// using Fantasy.DataStructure.Collection; +// using Fantasy.Entitas.Interface; +// using Fantasy.Helper; +// using Fantasy.Network.Interface; +// #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// +// // ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// #pragma warning disable CS8604 // Possible null reference argument. +// #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +// #pragma warning disable CS8602 // Dereference of a possibly null reference. +// +// #pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). +// +// namespace Fantasy.Network.KCP +// { +// public sealed class KCPServerNetworkUpdateSystem : UpdateSystem +// { +// protected override void Update(KCPServerNetwork self) +// { +// self.Update(); +// } +// } +// +// public struct PendingConnection +// { +// public readonly uint ChannelId; +// public readonly uint TimeOutId; +// public readonly IPEndPoint RemoteEndPoint; +// +// public PendingConnection(uint channelId, IPEndPoint remoteEndPoint, uint time) +// { +// ChannelId = channelId; +// RemoteEndPoint = remoteEndPoint; +// TimeOutId = time + 10 * 1000; // 设置10秒超时,如果10秒内没有确认连接则删除。 +// } +// } +// +// public sealed class KCPServerNetwork : ANetwork +// { +// private Socket _socket; +// private Thread _thread; +// private long _startTime; +// private uint _updateMinTime; +// private uint _pendingMinTime; +// private bool _allowWraparound = true; +// +// private readonly byte[] _sendBuff = new byte[5]; +// private readonly List _pendingTimeOutTime = new List(); +// private readonly HashSet _updateChannels = new HashSet(); +// private readonly List _updateTimeOutTime = new List(); +// private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); +// private readonly SortedOneToManyList _updateTimer = new SortedOneToManyList(); +// +// private readonly Dictionary _pendingConnection = new Dictionary(); +// private readonly SortedOneToManyList _pendingConnectionTimeOut = new SortedOneToManyList(); +// private readonly Dictionary _connectionChannel = new Dictionary(); +// +// public KCPSettings Settings { get; private set; } +// +// private uint TimeNow => (uint)(TimeHelper.Now - _startTime); +// +// public void Initialize(NetworkTarget networkTarget, IPEndPoint address) +// { +// _startTime = TimeHelper.Now; +// Settings = KCPSettings.Create(networkTarget); +// base.Initialize(NetworkType.Server, NetworkProtocolType.KCP, networkTarget); +// _socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); +// _socket.Blocking = false; +// _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); +// if (address.AddressFamily == AddressFamily.InterNetworkV6) +// { +// _socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); +// } +// +// _socket.Blocking = false; +// _socket.Bind(address); +// _socket.SetSocketBufferToOsLimit(); +// _socket.SetSioUdpConnReset(); +// _thread = new Thread(() => +// { +// ReceiveSocketAsync().Coroutine(); +// }); +// _thread.Start(); +// Log.Info($"SceneConfigId = {Scene.SceneConfigId} networkTarget = {networkTarget.ToString()} KCPServer Listen {address}"); +// } +// +// public override void Dispose() +// { +// if (IsDisposed) +// { +// return; +// } +// +// try +// { +// if (!_cancellationTokenSource.IsCancellationRequested) +// { +// try +// { +// _cancellationTokenSource.Cancel(); +// } +// catch (OperationCanceledException) +// { +// // 通常情况下,此处的异常可以忽略 +// } +// } +// +// foreach (var (_, channel) in _connectionChannel.ToArray()) +// { +// channel.Dispose(); +// } +// +// _connectionChannel.Clear(); +// _pendingConnection.Clear(); +// +// if (_socket != null) +// { +// _socket.Dispose(); +// _socket = null; +// } +// } +// catch (Exception e) +// { +// Log.Error(e); +// } +// finally +// { +// base.Dispose(); +// } +// } +// +// #region ReceiveSocket +// +// private const int BufferSize = 8192; +// private static readonly ArrayPool BufferPool = ArrayPool.Shared; +// private async FTask ReceiveSocketAsync() +// { +// var sceneThreadSynchronizationContext = Scene.ThreadSynchronizationContext; +// var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); +// +// while (!_cancellationTokenSource.IsCancellationRequested) +// { +// try +// { +// IPEndPoint receiveRemoteEndPoint = null; +// var buffer = BufferPool.Rent(BufferSize); +// var socketReceiveFromResult = await _socket.ReceiveFromAsync(buffer, SocketFlags.None, remoteEndPoint, _cancellationTokenSource.Token); +// var receivedBytes = socketReceiveFromResult.ReceivedBytes; +// +// switch (receivedBytes) +// { +// case 5: +// { +// switch ((KcpHeader)buffer[0]) +// { +// case KcpHeader.RequestConnection: +// case KcpHeader.ConfirmConnection: +// { +// receiveRemoteEndPoint = socketReceiveFromResult.RemoteEndPoint.Clone(); +// break; +// } +// } +// +// break; +// } +// case < 5: +// { +// continue; +// } +// } +// +// sceneThreadSynchronizationContext.Post(() => +// { +// ReceiveDataAsync(buffer, receivedBytes, receiveRemoteEndPoint); +// }); +// } +// catch (SocketException ex) +// { +// Log.Error($"Socket exception: {ex.Message}"); +// Dispose(); +// break; +// } +// catch (OperationCanceledException) +// { +// break; +// } +// catch (ObjectDisposedException) +// { +// Dispose(); +// break; +// } +// catch (Exception ex) +// { +// Log.Error($"Unexpected exception: {ex.Message}"); +// } +// } +// } +// +// #endregion +// +// #region ReceivePipeData +// +// private void ReceiveDataAsync(byte[] buffer, int receivedBytes, IPEndPoint remoteEndPoint) +// { +// try +// { +// var header = (KcpHeader)buffer[0]; +// var channelId = BitConverter.ToUInt32(buffer, 1); +// +// switch (header) +// { +// // 客户端请求建立KCP连接 +// case KcpHeader.RequestConnection: +// { +// if (_pendingConnection.TryGetValue(channelId, out var pendingConnection)) +// { +// if (!remoteEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) +// { +// // 重复通道ID,向客户端发送重复通道ID消息 +// SendRepeatChannelId(ref channelId, remoteEndPoint); +// } +// +// break; +// } +// +// if (_connectionChannel.ContainsKey(channelId)) +// { +// // 已存在的通道ID,向客户端发送重复通道ID消息 +// SendRepeatChannelId(ref channelId, remoteEndPoint); +// break; +// } +// +// AddPendingConnection(ref channelId, remoteEndPoint); +// break; +// } +// // 客户端确认建立KCP连接 +// case KcpHeader.ConfirmConnection: +// { +// if (!ConfirmPendingConnection(ref channelId, remoteEndPoint)) +// { +// break; +// } +// +// AddConnection(ref channelId, remoteEndPoint); +// break; +// } +// // 接收KCP的数据 +// case KcpHeader.ReceiveData: +// { +// if (buffer.Length == 5) +// { +// Log.Warning($"KCP Server KcpHeader.Data buffer.Length == 5"); +// break; +// } +// +// if (_connectionChannel.TryGetValue(channelId, out var channel)) +// { +// channel.Input(buffer.AsMemory().Slice(5, receivedBytes - 5)); +// } +// +// break; +// } +// // 断开KCP连接 +// case KcpHeader.Disconnect: +// { +// // 断开不需要清楚PendingConnection让ClearPendingConnection自动清楚就可以了,并且不一定有Pending。 +// RemoveChannel(channelId); +// break; +// } +// } +// } +// finally +// { +// BufferPool.Return(buffer); +// } +// } +// +// #endregion +// +// #region Update +// +// public void Update() +// { +// var timeNow = TimeNow; +// _allowWraparound = timeNow < _updateMinTime; +// CheckUpdateTimerOut(ref timeNow); +// UpdateChannel(ref timeNow); +// PendingTimerOut(ref timeNow); +// _allowWraparound = true; +// } +// +// private void CheckUpdateTimerOut(ref uint nowTime) +// { +// if (_updateTimer.Count == 0) +// { +// return; +// } +// +// if (IsTimeGreaterThan(_updateMinTime, nowTime)) +// { +// return; +// } +// +// _updateTimeOutTime.Clear(); +// +// foreach (var kv in _updateTimer) +// { +// var timeId = kv.Key; +// +// if (IsTimeGreaterThan(timeId, nowTime)) +// { +// _updateMinTime = timeId; +// break; +// } +// +// _updateTimeOutTime.Add(timeId); +// } +// +// foreach (var timeId in _updateTimeOutTime) +// { +// foreach (var channelId in _updateTimer[timeId]) +// { +// _updateChannels.Add(channelId); +// } +// +// _updateTimer.RemoveKey(timeId); +// } +// } +// +// private void UpdateChannel(ref uint timeNow) +// { +// foreach (var channelId in _updateChannels) +// { +// if (!_connectionChannel.TryGetValue(channelId, out var channel)) +// { +// continue; +// } +// +// if (channel.IsDisposed) +// { +// _connectionChannel.Remove(channelId); +// continue; +// } +// +// channel.Kcp.Update(timeNow); +// AddUpdateChannel(channelId, channel.Kcp.Check(timeNow)); +// } +// +// _updateChannels.Clear(); +// } +// +// private void PendingTimerOut(ref uint timeNow) +// { +// if (_pendingConnectionTimeOut.Count == 0) +// { +// return; +// } +// +// if (IsTimeGreaterThan(_pendingMinTime, timeNow)) +// { +// return; +// } +// +// _pendingTimeOutTime.Clear(); +// +// foreach (var kv in _pendingConnectionTimeOut) +// { +// var timeId = kv.Key; +// +// if (IsTimeGreaterThan(timeId, timeNow)) +// { +// _pendingMinTime = timeId; +// break; +// } +// +// _pendingTimeOutTime.Add(timeId); +// } +// +// foreach (var timeId in _pendingTimeOutTime) +// { +// foreach (var channelId in _pendingConnectionTimeOut[timeId]) +// { +// _pendingConnection.Remove(channelId); +// } +// +// _pendingConnectionTimeOut.RemoveKey(timeId); +// } +// } +// +// public void AddUpdateChannel(uint channelId, uint tillTime) +// { +// if (tillTime == 0) +// { +// _updateChannels.Add(channelId); +// return; +// } +// +// if (IsTimeGreaterThan(_updateMinTime, tillTime)) +// { +// _updateMinTime = tillTime; +// } +// +// _updateTimer.Add(tillTime, channelId); +// } +// +// private const uint HalfMaxUint = uint.MaxValue / 2; +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private bool IsTimeGreaterThan(uint timeId, uint nowTime) +// { +// if (!_allowWraparound) +// { +// return timeId > nowTime; +// } +// +// var diff = timeId - nowTime; +// // 如果 diff 的值在 [0, HalfMaxUint] 范围内,说明 timeId 是在 nowTime 之后或相等。 +// // 如果 diff 的值在 (HalfMaxUint, uint.MaxValue] 范围内,说明 timeId 是在 nowTime 之前(时间回绕的情况)。 +// return diff < HalfMaxUint || diff == HalfMaxUint; +// } +// +// #endregion +// +// #region Pending +// +// private void AddPendingConnection(ref uint channelId, IPEndPoint ipEndPoint) +// { +// var now = TimeNow; +// var pendingConnection = new PendingConnection(channelId, ipEndPoint, now); +// +// if (IsTimeGreaterThan(_pendingMinTime, pendingConnection.TimeOutId) || _pendingMinTime == 0) +// { +// _pendingMinTime = pendingConnection.TimeOutId; +// } +// +// _pendingConnection.Add(channelId, pendingConnection); +// _pendingConnectionTimeOut.Add(pendingConnection.TimeOutId, channelId); +// SendWaitConfirmConnection(ref channelId, ipEndPoint); +// } +// +// private bool ConfirmPendingConnection(ref uint channelId, EndPoint ipEndPoint) +// { +// if (!_pendingConnection.TryGetValue(channelId, out var pendingConnection)) +// { +// return false; +// } +// +// if (!ipEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) +// { +// Log.Error($"KCPSocket syn address diff: {channelId} {pendingConnection.RemoteEndPoint} {ipEndPoint}"); +// return false; +// } +// +// _pendingConnection.Remove(channelId); +// _pendingConnectionTimeOut.RemoveValue(pendingConnection.TimeOutId, pendingConnection.ChannelId); +// #if FANTASY_DEVELOP +// Log.Debug($"KCPSocket _pendingConnection:{_pendingConnection.Count} _pendingConnectionTimer:{_pendingConnectionTimeOut.Count}"); +// #endif +// return true; +// } +// +// #endregion +// +// #region Connection +// +// private void AddConnection(ref uint channelId, IPEndPoint ipEndPoint) +// { +// var eventArgs = new KCPServerNetworkChannel(this, channelId, ipEndPoint); +// _connectionChannel.Add(channelId, eventArgs); +// #if FANTASY_DEVELOP +// Log.Debug($"AddConnection _connectionChannel:{_connectionChannel.Count()}"); +// #endif +// } +// +// public override void RemoveChannel(uint channelId) +// { +// if (!_connectionChannel.Remove(channelId, out var channel)) +// { +// return; +// } +// +// if (!channel.IsDisposed) +// { +// SendDisconnect(ref channelId, channel.RemoteEndPoint); +// channel.Dispose(); +// } +// #if FANTASY_DEVELOP +// Log.Debug($"RemoveChannel _connectionChannel:{_connectionChannel.Count()}"); +// #endif +// } +// +// #endregion +// +// #region Send +// +// private const byte KcpHeaderDisconnect = (byte)KcpHeader.Disconnect; +// private const byte KcpHeaderRepeatChannelId = (byte)KcpHeader.RepeatChannelId; +// private const byte KcpHeaderWaitConfirmConnection = (byte)KcpHeader.WaitConfirmConnection; +// +// private unsafe void SendDisconnect(ref uint channelId, EndPoint clientEndPoint) +// { +// fixed (byte* p = _sendBuff) +// { +// p[0] = KcpHeaderDisconnect; +// *(uint*)(p + 1) = channelId; +// } +// +// SendAsync(_sendBuff, 0, 5, clientEndPoint); +// } +// +// private unsafe void SendRepeatChannelId(ref uint channelId, EndPoint clientEndPoint) +// { +// fixed (byte* p = _sendBuff) +// { +// p[0] = KcpHeaderRepeatChannelId; +// *(uint*)(p + 1) = channelId; +// } +// +// SendAsync(_sendBuff, 0, 5, clientEndPoint); +// } +// +// private unsafe void SendWaitConfirmConnection(ref uint channelId, EndPoint clientEndPoint) +// { +// fixed (byte* p = _sendBuff) +// { +// p[0] = KcpHeaderWaitConfirmConnection; +// *(uint*)(p + 1) = channelId; +// } +// +// SendAsync(_sendBuff, 0, 5, clientEndPoint); +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// public void SendAsync(byte[] buffer, int offset, int count, EndPoint endPoint) +// { +// try +// { +// _socket.SendTo(new ArraySegment(buffer, offset, count), SocketFlags.None, endPoint); +// } +// catch (ArgumentException ex) +// { +// Log.Error($"ArgumentException: {ex.Message}"); // 处理参数错误 +// } +// catch (SocketException) +// { +// //Log.Error($"SocketException: {ex.Message}"); // 处理网络错误 +// } +// catch (ObjectDisposedException) +// { +// // 处理套接字已关闭的情况 +// } +// catch (InvalidOperationException ex) +// { +// Log.Error($"InvalidOperationException: {ex.Message}"); // 处理无效操作 +// } +// catch (Exception ex) +// { +// Log.Error($"Exception: {ex.Message}"); // 捕获其他异常 +// } +// } +// +// #endregion +// } +// } +// +// #endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs.meta new file mode 100644 index 0000000..e5389dc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByArrayPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 039dc040fe04142f99a246629d6c2e0d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs new file mode 100644 index 0000000..8acbf99 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs @@ -0,0 +1,619 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.KCP +{ + internal sealed class KCPServerNetworkUpdateSystem : UpdateSystem + { + protected override void Update(KCPServerNetwork self) + { + self.Update(); + } + } + + internal struct PendingConnection + { + public readonly uint ChannelId; + public readonly uint TimeOutId; + public readonly IPEndPoint RemoteEndPoint; + + public PendingConnection(uint channelId, IPEndPoint remoteEndPoint, uint time) + { + ChannelId = channelId; + RemoteEndPoint = remoteEndPoint; + TimeOutId = time + 10 * 1000; // 设置10秒超时,如果10秒内没有确认连接则删除。 + } + } + + public sealed class KCPServerNetwork : ANetwork + { + private Socket _socket; + private long _startTime; + private uint _updateMinTime; + private uint _pendingMinTime; + private bool _allowWraparound = true; + private readonly Pipe _pipe = new Pipe(); + private readonly byte[] _sendBuff = new byte[5]; + private readonly List _pendingTimeOutTime = new List(); + private readonly HashSet _updateChannels = new HashSet(); + private readonly List _updateTimeOutTime = new List(); + private readonly Queue _endPoint = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private readonly SortedOneToManyList _updateTimer = new SortedOneToManyList(); + + private readonly Dictionary _pendingConnection = new Dictionary(); + private readonly SortedOneToManyList _pendingConnectionTimeOut = new SortedOneToManyList(); + private readonly Dictionary _connectionChannel = new Dictionary(); + + public KCPSettings Settings { get; private set; } + + private uint TimeNow => (uint)(TimeHelper.Now - _startTime); + + public void Initialize(NetworkTarget networkTarget, IPEndPoint address) + { + _startTime = TimeHelper.Now; + Settings = KCPSettings.Create(networkTarget); + base.Initialize(NetworkType.Server, NetworkProtocolType.KCP, networkTarget); + _socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + _socket.Blocking = false; + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); + } + + _socket.Blocking = false; + _socket.Bind(address); + _socket.SetSocketBufferToOsLimit(); + _socket.SetSioUdpConnReset(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} networkTarget = {networkTarget.ToString()} KCPServer Listen {address}"); + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + foreach (var (_, channel) in _connectionChannel.ToArray()) + { + channel.Dispose(); + } + + _connectionChannel.Clear(); + _pendingConnection.Clear(); + + if (_socket != null) + { + _socket.Dispose(); + _socket = null; + } + + base.Dispose(); + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); + + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + var socketReceiveFromResult = await _socket.ReceiveFromAsync(memory, SocketFlags.None, remoteEndPoint, _cancellationTokenSource.Token); + var receivedBytes = socketReceiveFromResult.ReceivedBytes; + + if (receivedBytes == 5) + { + switch ((KcpHeader)memory.Span[0]) + { + case KcpHeader.RequestConnection: + case KcpHeader.ConfirmConnection: + { + _endPoint.Enqueue(socketReceiveFromResult.RemoteEndPoint.Clone()); + break; + } + } + } + + _pipe.Writer.Advance(receivedBytes); + await _pipe.Writer.FlushAsync(); + } + catch (SocketException ex) + { + Log.Error($"Socket exception: {ex.Message}"); + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var header, out var channelId, out var message)) + { + ReceiveData(ref header, ref channelId, ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private unsafe bool TryReadMessage(ref ReadOnlySequence buffer, out KcpHeader header, out uint channelId, out ReadOnlyMemory message) + { + if (buffer.Length < 5) + { + channelId = 0; + message = default; + header = KcpHeader.None; + if (buffer.Length > 0) + { + buffer = buffer.Slice(buffer.Length); + } + return false; + } + + var readOnlyMemory = buffer.First; + + if (MemoryMarshal.TryGetArray(readOnlyMemory, out var arraySegment)) + { + fixed (byte* bytePointer = &arraySegment.Array[arraySegment.Offset]) + { + header = (KcpHeader)bytePointer[0]; + channelId = Unsafe.ReadUnaligned(ref bytePointer[1]); + } + } + else + { + // 如果无法获取数组段,回退到安全代码来执行。这种情况几乎不会发生、为了保险还是写一下了。 + var firstSpan = readOnlyMemory.Span; + header = (KcpHeader)firstSpan[0]; + channelId = MemoryMarshal.Read(firstSpan.Slice(1, 4)); + } + + message = readOnlyMemory.Slice(5); + buffer = buffer.Slice(readOnlyMemory.Length); + return true; + } + + private void ReceiveData(ref KcpHeader header, ref uint channelId, ref ReadOnlyMemory buffer) + { + switch (header) + { + // 客户端请求建立KCP连接 + case KcpHeader.RequestConnection: + { + _endPoint.TryDequeue(out var ipEndPoint); + + if (_pendingConnection.TryGetValue(channelId, out var pendingConnection)) + { + if (!ipEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) + { + // 重复通道ID,向客户端发送重复通道ID消息 + SendRepeatChannelId(ref channelId, ipEndPoint); + } + + break; + } + + if (_connectionChannel.ContainsKey(channelId)) + { + // 已存在的通道ID,向客户端发送重复通道ID消息 + SendRepeatChannelId(ref channelId, ipEndPoint); + break; + } + + AddPendingConnection(ref channelId, ipEndPoint); + break; + } + // 客户端确认建立KCP连接 + case KcpHeader.ConfirmConnection: + { + _endPoint.TryDequeue(out var ipEndPoint); + if (!ConfirmPendingConnection(ref channelId, ipEndPoint)) + { + break; + } + + AddConnection(ref channelId, ipEndPoint.Clone()); + break; + } + // 接收KCP的数据 + case KcpHeader.ReceiveData: + { + if (buffer.Length == 5) + { + Log.Warning($"KCP Server KcpHeader.Data buffer.Length == 5"); + break; + } + + if (_connectionChannel.TryGetValue(channelId, out var channel)) + { + channel.Input(buffer); + } + + break; + } + // 断开KCP连接 + case KcpHeader.Disconnect: + { + // 断开不需要清楚PendingConnection让ClearPendingConnection自动清楚就可以了,并且不一定有Pending。 + RemoveChannel(channelId); + break; + } + } + } + + #endregion + + #region Update + + public void Update() + { + var timeNow = TimeNow; + _allowWraparound = timeNow < _updateMinTime; + CheckUpdateTimerOut(ref timeNow); + UpdateChannel(ref timeNow); + PendingTimerOut(ref timeNow); + _allowWraparound = true; + } + + private void CheckUpdateTimerOut(ref uint nowTime) + { + if (_updateTimer.Count == 0) + { + return; + } + + if (IsTimeGreaterThan(_updateMinTime, nowTime)) + { + return; + } + + _updateTimeOutTime.Clear(); + + foreach (var kv in _updateTimer) + { + var timeId = kv.Key; + + if (IsTimeGreaterThan(timeId, nowTime)) + { + _updateMinTime = timeId; + break; + } + + _updateTimeOutTime.Add(timeId); + } + + foreach (var timeId in _updateTimeOutTime) + { + foreach (var channelId in _updateTimer[timeId]) + { + _updateChannels.Add(channelId); + } + + _updateTimer.RemoveKey(timeId); + } + } + + private void UpdateChannel(ref uint timeNow) + { + foreach (var channelId in _updateChannels) + { + if (!_connectionChannel.TryGetValue(channelId, out var channel)) + { + continue; + } + + if (channel.IsDisposed) + { + _connectionChannel.Remove(channelId); + continue; + } + + channel.Kcp.Update(timeNow); + AddUpdateChannel(channelId, channel.Kcp.Check(timeNow)); + } + + _updateChannels.Clear(); + } + + private void PendingTimerOut(ref uint timeNow) + { + if (_pendingConnectionTimeOut.Count == 0) + { + return; + } + + if (IsTimeGreaterThan(_pendingMinTime, timeNow)) + { + return; + } + + _pendingTimeOutTime.Clear(); + + foreach (var kv in _pendingConnectionTimeOut) + { + var timeId = kv.Key; + + if (IsTimeGreaterThan(timeId, timeNow)) + { + _pendingMinTime = timeId; + break; + } + + _pendingTimeOutTime.Add(timeId); + } + + foreach (var timeId in _pendingTimeOutTime) + { + foreach (var channelId in _pendingConnectionTimeOut[timeId]) + { + _pendingConnection.Remove(channelId); + } + + _pendingConnectionTimeOut.RemoveKey(timeId); + } + } + + public void AddUpdateChannel(uint channelId, uint tillTime) + { + if (tillTime == 0) + { + _updateChannels.Add(channelId); + return; + } + + if (IsTimeGreaterThan(_updateMinTime, tillTime)) + { + _updateMinTime = tillTime; + } + + _updateTimer.Add(tillTime, channelId); + } + + private const uint HalfMaxUint = uint.MaxValue / 2; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool IsTimeGreaterThan(uint timeId, uint nowTime) + { + if (!_allowWraparound) + { + return timeId > nowTime; + } + + var diff = timeId - nowTime; + // 如果 diff 的值在 [0, HalfMaxUint] 范围内,说明 timeId 是在 nowTime 之后或相等。 + // 如果 diff 的值在 (HalfMaxUint, uint.MaxValue] 范围内,说明 timeId 是在 nowTime 之前(时间回绕的情况)。 + return diff < HalfMaxUint || diff == HalfMaxUint; + } + + #endregion + + #region Pending + + private void AddPendingConnection(ref uint channelId, IPEndPoint ipEndPoint) + { + var now = TimeNow; + var pendingConnection = new PendingConnection(channelId, ipEndPoint, now); + + if (IsTimeGreaterThan(_pendingMinTime, pendingConnection.TimeOutId) || _pendingMinTime == 0) + { + _pendingMinTime = pendingConnection.TimeOutId; + } + + _pendingConnection.Add(channelId, pendingConnection); + _pendingConnectionTimeOut.Add(pendingConnection.TimeOutId, channelId); + SendWaitConfirmConnection(ref channelId, ipEndPoint); + } + + private bool ConfirmPendingConnection(ref uint channelId, EndPoint ipEndPoint) + { + if (!_pendingConnection.TryGetValue(channelId, out var pendingConnection)) + { + return false; + } + + if (!ipEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) + { + Log.Error($"KCPSocket syn address diff: {channelId} {pendingConnection.RemoteEndPoint} {ipEndPoint}"); + return false; + } + + _pendingConnection.Remove(channelId); + _pendingConnectionTimeOut.RemoveValue(pendingConnection.TimeOutId, pendingConnection.ChannelId); +#if FANTASY_DEVELOP + Log.Debug($"KCPSocket _pendingConnection:{_pendingConnection.Count} _pendingConnectionTimer:{_pendingConnectionTimeOut.Count}"); +#endif + return true; + } + + #endregion + + #region Connection + + private void AddConnection(ref uint channelId, IPEndPoint ipEndPoint) + { + var eventArgs = new KCPServerNetworkChannel(this, channelId, ipEndPoint); + _connectionChannel.Add(channelId, eventArgs); +#if FANTASY_DEVELOP + Log.Debug($"AddConnection _connectionChannel:{_connectionChannel.Count()}"); +#endif + } + + public override void RemoveChannel(uint channelId) + { + if (!_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (!channel.IsDisposed) + { + SendDisconnect(ref channelId, channel.RemoteEndPoint); + channel.Dispose(); + } +#if FANTASY_DEVELOP + Log.Debug($"RemoveChannel _connectionChannel:{_connectionChannel.Count()}"); +#endif + } + + #endregion + + #region Send + + private const byte KcpHeaderDisconnect = (byte)KcpHeader.Disconnect; + private const byte KcpHeaderRepeatChannelId = (byte)KcpHeader.RepeatChannelId; + private const byte KcpHeaderWaitConfirmConnection = (byte)KcpHeader.WaitConfirmConnection; + + private unsafe void SendDisconnect(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderDisconnect; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + private unsafe void SendRepeatChannelId(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderRepeatChannelId; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + private unsafe void SendWaitConfirmConnection(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderWaitConfirmConnection; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SendAsync(byte[] buffer, int offset, int count, EndPoint endPoint) + { + try + { + _socket.SendTo(new ArraySegment(buffer, offset, count), SocketFlags.None, endPoint); + } + catch (ArgumentException ex) + { + Log.Error($"ArgumentException: {ex.Message}"); // 处理参数错误 + } + catch (SocketException) + { + //Log.Error($"SocketException: {ex.Message}"); // 处理网络错误 + } + catch (ObjectDisposedException) + { + // 处理套接字已关闭的情况 + } + catch (InvalidOperationException ex) + { + Log.Error($"InvalidOperationException: {ex.Message}"); // 处理无效操作 + } + catch (Exception ex) + { + Log.Error($"Exception: {ex.Message}"); // 捕获其他异常 + } + } + + #endregion + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs.meta new file mode 100644 index 0000000..e8d5283 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkByPipe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6649471da39384f85b3ade8aca364fb1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs new file mode 100644 index 0000000..dfcbd18 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs @@ -0,0 +1,165 @@ +#if FANTASY_NET +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using KCP; +// ReSharper disable ParameterHidesMember +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.KCP +{ + /// + /// KCP 服务器网络通道,用于处理服务器与客户端之间的数据通信。 + /// + internal class KCPServerNetworkChannel : ANetworkServerChannel + { + private bool _isInnerDispose; + private readonly int _maxSndWnd; + private KCPServerNetwork _kcpServerNetwork; + private readonly BufferPacketParser _packetParser; + private readonly byte[] _receiveBuffer = new byte[Packet.PacketBodyMaxLength + 20]; + public Kcp Kcp { get; private set; } + public uint ChannelId { get; private set; } + + public KCPServerNetworkChannel(KCPServerNetwork network, uint channelId, IPEndPoint ipEndPoint) : base(network, channelId, ipEndPoint) + { + _kcpServerNetwork = network; + ChannelId = channelId; + _maxSndWnd = network.Settings.MaxSendWindowSize; + Kcp = KCPFactory.Create(network.Settings, ChannelId, KcpSpanCallback); + _packetParser = PacketParserFactory.CreateServerBufferPacket(network); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + try + { + _isInnerDispose = true; + _kcpServerNetwork.RemoveChannel(Id); + IsDisposed = true; + Kcp.Dispose(); + Kcp = null; + ChannelId = 0; + _kcpServerNetwork = null; + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + public void Input(ReadOnlyMemory buffer) + { + Kcp.Input(buffer.Span); + _kcpServerNetwork.AddUpdateChannel(ChannelId, 0); + + while (!IsDisposed) + { + try + { + var peekSize = Kcp.PeekSize(); + + if (peekSize < 0) + { + return; + } + + var receiveCount = Kcp.Receive(_receiveBuffer.AsSpan(0, peekSize)); + + if (receiveCount != peekSize) + { + return; + } + + if (!_packetParser.UnPack(_receiveBuffer, ref receiveCount, out var packInfo)) + { + continue; + } + + Session.Receive(packInfo); + } + catch (ScanException e) + { + Log.Debug($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (IsDisposed) + { + return; + } + + if (Kcp.WaitSendCount > _maxSndWnd) + { + // 检查等待发送的消息,如果超出两倍窗口大小,KCP作者给的建议是要断开连接 + Log.Warning($"ERR_KcpWaitSendSizeTooLarge {Kcp.WaitSendCount} > {_maxSndWnd}"); + Dispose(); + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + Kcp.Send(buffer.GetBuffer().AsSpan(0, (int)buffer.Position)); + + if (buffer.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _kcpServerNetwork.MemoryStreamBufferPool.ReturnMemoryStream(buffer); + } + + _kcpServerNetwork.AddUpdateChannel(ChannelId, 0); + } + + private const byte KcpHeaderReceiveData = (byte)KcpHeader.ReceiveData; + + private unsafe void KcpSpanCallback(byte[] buffer, int count) + { + if (IsDisposed) + { + return; + } + + try + { + if (count == 0) + { + throw new Exception("KcpOutput count 0"); + } + + fixed (byte* p = buffer) + { + p[0] = KcpHeaderReceiveData; + *(uint*)(p + 1) = ChannelId; + } + + _kcpServerNetwork.SendAsync(buffer, 0, count + 5, RemoteEndPoint); + } + catch (Exception e) + { + Log.Error(e); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta new file mode 100644 index 0000000..0c0f645 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3877e0b5a4b5c24d81b306598bc4119 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs new file mode 100644 index 0000000..c7b6ecc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs @@ -0,0 +1,95 @@ +using System; +using System.Net; +using Fantasy.Entitas; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#if !FANTASY_WEBGL +using Fantasy.Network.TCP; +using Fantasy.Network.KCP; +#endif +#if FANTASY_NET +using Fantasy.Network.HTTP; +#endif +using Fantasy.Network.WebSocket; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network +{ + internal static class NetworkProtocolFactory + { +#if FANTASY_NET + public static ANetwork CreateServer(Scene scene, NetworkProtocolType protocolType, NetworkTarget networkTarget, string bindIp, int port) + { + switch (protocolType) + { + case NetworkProtocolType.TCP: + { + var network = Entity.Create(scene, false, false); + var address = NetworkHelper.ToIPEndPoint(bindIp, port); + network.Initialize(networkTarget, address); + return network; + } + case NetworkProtocolType.KCP: + { + var network = Entity.Create(scene, false, true); + var address = NetworkHelper.ToIPEndPoint(bindIp, port); + network.Initialize(networkTarget, address); + return network; + } + case NetworkProtocolType.WebSocket: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget, bindIp, port); + return network; + } + case NetworkProtocolType.HTTP: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget, bindIp, port); + return network; + } + default: + { + throw new NotSupportedException($"Unsupported NetworkProtocolType:{protocolType}"); + } + } + } +#endif + public static AClientNetwork CreateClient(Scene scene, NetworkProtocolType protocolType, NetworkTarget networkTarget) + { +#if !FANTASY_WEBGL + switch (protocolType) + { + case NetworkProtocolType.TCP: + { + var network = Entity.Create(scene, false, false); + network.Initialize(networkTarget); + return network; + } + case NetworkProtocolType.KCP: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; + } + case NetworkProtocolType.WebSocket: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; + } + default: + { + throw new NotSupportedException($"Unsupported NetworkProtocolType:{protocolType}"); + } + } +#else + // Webgl平台只能用这个协议。 + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; +#endif + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta new file mode 100644 index 0000000..3fcce62 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e189df40e145ed940a39a37df31b101f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs new file mode 100644 index 0000000..55a04c9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs @@ -0,0 +1,69 @@ +namespace Fantasy.Network +{ + /// + /// 网络服务器类型 + /// + public enum NetworkType + { + /// + /// 默认 + /// + None = 0, + /// + /// 客户端网络 + /// + Client = 1, +#if FANTASY_NET + /// + /// 服务器网络 + /// + Server = 2 +#endif + } + /// + /// 网络服务的目标 + /// + public enum NetworkTarget + { + /// + /// 默认 + /// + None = 0, + /// + /// 对外 + /// + Outer = 1, +#if FANTASY_NET + /// + /// 对内 + /// + Inner = 2 +#endif + } + /// + /// 支持的网络协议 + /// + public enum NetworkProtocolType + { + /// + /// 默认 + /// + None = 0, + /// + /// KCP + /// + KCP = 1, + /// + /// TCP + /// + TCP = 2, + /// + /// WebSocket + /// + WebSocket = 3, + /// + /// HTTP + /// + HTTP = 4, + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs.meta new file mode 100644 index 0000000..3137d0f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkProtocolType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e107bcbc8d8dee443a1025dd7a46b4ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs new file mode 100644 index 0000000..c0c166b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs @@ -0,0 +1,100 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Threading; +using Fantasy.Entitas; +// ReSharper disable ForCanBeConvertedToForeach +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network +{ + internal interface INetworkThreadUpdate + { + void Update(); + } + + /// + /// 网络线程组件 + /// + internal sealed class NetworkThreadComponent : Entity + { + private Thread _netWorkThread; + internal ThreadSynchronizationContext SynchronizationContext { get; private set; } + private readonly List _updates = new List(); + + internal NetworkThreadComponent Initialize() + { + SynchronizationContext = new ThreadSynchronizationContext(); + _netWorkThread = new Thread(Update) + { + IsBackground = true + }; + _netWorkThread.Start(); + return this; + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + SynchronizationContext.Post(() => + { + _updates.Clear(); + _netWorkThread.Join(); + _netWorkThread = null; + SynchronizationContext = null; + }); + + base.Dispose(); + } + + private void Update() + { + // 将同步上下文设置为网络线程的上下文,以确保操作在正确的线程上下文中执行。 + System.Threading.SynchronizationContext.SetSynchronizationContext(SynchronizationContext); + // 循环执行 + while (!IsDisposed) + { + for (var i = 0; i < _updates.Count; i++) + { + try + { + _updates[i].Update(); + } + catch (Exception e) + { + Log.Error(e); + } + } + SynchronizationContext.Update(); + Thread.Sleep(1); + } + } + + internal void AddNetworkThreadUpdate(INetworkThreadUpdate update) + { + SynchronizationContext.Post(() => + { + if (_updates.Contains(update)) + { + Log.Warning($"{update.GetType().FullName} Network thread update is already running"); + return; + } + _updates.Add(update); + }); + } + + internal void RemoveNetworkThreadUpdate(INetworkThreadUpdate update) + { + SynchronizationContext.Post(() => + { + _updates.Remove(update); + }); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs.meta new file mode 100644 index 0000000..85cc407 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/NetworkThreadComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8fa747144a600ef40afb26fa48139688 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP.meta new file mode 100644 index 0000000..79dc962 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8bbc3e3ece3f5e0469fd7c5edff02bbc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client.meta new file mode 100644 index 0000000..2a39d7d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 963796da7ae29094291aed71407e1eee +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs new file mode 100644 index 0000000..233fb7b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs @@ -0,0 +1,413 @@ +#if !FANTASY_WEBGL +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Threading; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.TCP +{ + public sealed class TCPClientNetwork : AClientNetwork + { + private bool _isSending; + private bool _isInnerDispose; + private long _connectTimeoutId; + private Socket _socket; + private IPEndPoint _remoteEndPoint; + private SocketAsyncEventArgs _sendArgs; + private ReadOnlyMemoryPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public uint ChannelId { get; private set; } + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.TCP, networkTarget); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + try + { + _isSending = false; + _isInnerDispose = true; + ClearConnectTimeout(); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + _onConnectDisconnect?.Invoke(); + + if (_socket.Connected) + { + _socket.Close(); + _socket = null; + } + + _sendBuffers.Clear(); + _packetParser?.Dispose(); + ChannelId = 0; + _sendArgs = null; + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + /// + /// 连接到远程服务器。 + /// + /// 远程服务器的终端点。 + /// 连接成功时的回调。 + /// 连接失败时的回调。 + /// 连接断开时的回调。 + /// + /// 连接超时时间,单位:毫秒。 + /// 连接的会话。 + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + // 如果已经初始化过一次,抛出异常,要求重新实例化 + + if (IsInit) + { + throw new NotSupportedException("TCPClientNetwork Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _isSending = false; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + // 设置连接超时定时器 + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + _packetParser = PacketParserFactory.CreateClientReadOnlyMemoryPacket(this); + _remoteEndPoint = NetworkHelper.GetIPEndPoint(remoteAddress); + _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket.NoDelay = true; + _socket.SetSocketBufferToOsLimit(); + _sendArgs = new SocketAsyncEventArgs(); + _sendArgs.Completed += OnSendCompleted; + var outArgs = new SocketAsyncEventArgs + { + RemoteEndPoint = _remoteEndPoint + }; + outArgs.Completed += OnConnectSocketCompleted; + + if (!_socket.ConnectAsync(outArgs)) + { + OnReceiveSocketComplete(); + } + + Session = Session.Create(this, _remoteEndPoint); + return Session; + } + + private void OnConnectSocketCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + if (asyncEventArgs.LastOperation == SocketAsyncOperation.Connect) + { + if (asyncEventArgs.SocketError == SocketError.Success) + { + Scene.ThreadSynchronizationContext.Post(OnReceiveSocketComplete); + } + else + { + Scene.ThreadSynchronizationContext.Post(() => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + } + } + } + + private void OnReceiveSocketComplete() + { + ClearConnectTimeout(); + _onConnectComplete?.Invoke(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); +#if UNITY_2021 + // Unity2021.3.14f有个恶心的问题,使用ReceiveAsync会导致memory不能正确写入 + // 所有只能使用ReceiveFromAsync来接收消息,但ReceiveFromAsync只有一个接受ArraySegment的接口。 + MemoryMarshal.TryGetArray(memory, out ArraySegment arraySegment); + var result = await _socket.ReceiveFromAsync(arraySegment, SocketFlags.None, _remoteEndPoint); + _pipe.Writer.Advance(result.ReceivedBytes); +#else + var count = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + _pipe.Writer.Advance(count); +#endif + await _pipe.Writer.FlushAsync(); + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning(e.Message); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send(); + } + } + + private void Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_sendBuffers.Count > 0) + { + var memoryStreamBuffer = _sendBuffers.Dequeue(); + _sendArgs.UserToken = memoryStreamBuffer; + _sendArgs.SetBuffer(new ArraySegment(memoryStreamBuffer.GetBuffer(), 0, (int)memoryStreamBuffer.Position)); + + try + { + if (_socket.SendAsync(_sendArgs)) + { + break; + } + + ReturnMemoryStream(memoryStreamBuffer); + } + catch + { + _isSending = false; + return; + } + } + + _isSending = false; + } + + private void ReturnMemoryStream(MemoryStreamBuffer memoryStream) + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + + private void OnSendCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.SocketError != SocketError.Success || asyncEventArgs.BytesTransferred == 0) + { + _isSending = false; + return; + } + + var memoryStreamBuffer = (MemoryStreamBuffer)asyncEventArgs.UserToken; + Scene.ThreadSynchronizationContext.Post(() => + { + ReturnMemoryStream(memoryStreamBuffer); + + if (_sendBuffers.Count > 0) + { + Send(); + } + else + { + _isSending = false; + } + }); + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net?.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta new file mode 100644 index 0000000..ae0e67e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c3d888bae391e0498f5cdaebbf34531 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server.meta new file mode 100644 index 0000000..0a0fc70 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d42a7567caa9ff6499f97c14d76f1f08 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs new file mode 100644 index 0000000..3e8efb4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs @@ -0,0 +1,161 @@ +#if FANTASY_NET +using System.Net; +using System.Net.Sockets; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable GCSuppressFinalizeForTypeWithoutDestructor +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network.TCP +{ + public sealed class TCPServerNetwork : ANetwork + { + private Random _random; + private Socket _socket; + private SocketAsyncEventArgs _acceptAsync; + private readonly Dictionary _connectionChannel = new Dictionary(); + + public void Initialize(NetworkTarget networkTarget, IPEndPoint address) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.TCP, networkTarget); + _random = new Random(); + _acceptAsync = new SocketAsyncEventArgs(); + _socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); + + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); + } + + _socket.Bind(address); + _socket.Listen(int.MaxValue); + _socket.SetSocketBufferToOsLimit(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} networkTarget = {networkTarget.ToString()} TCPServer Listen {address}"); + _acceptAsync.Completed += OnCompleted; + AcceptAsync(); + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + try + { + foreach (var networkChannel in _connectionChannel.Values.ToArray()) + { + networkChannel.Dispose(); + } + + _connectionChannel.Clear(); + _random = null; + _socket.Dispose(); + _socket = null; + _acceptAsync.Dispose(); + _acceptAsync = null; + GC.SuppressFinalize(this); + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + private void AcceptAsync() + { + _acceptAsync.AcceptSocket = null; + + if (_socket.AcceptAsync(_acceptAsync)) + { + return; + } + + OnAcceptComplete(_acceptAsync); + } + + private void OnAcceptComplete(SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.AcceptSocket == null) + { + return; + } + + if (asyncEventArgs.SocketError != SocketError.Success) + { + Log.Error($"Socket Accept Error: {_acceptAsync.SocketError}"); + return; + } + + try + { + uint channelId; + do + { + channelId = 0xC0000000 | (uint)_random.Next(); + } while (_connectionChannel.ContainsKey(channelId)); + + _connectionChannel.Add(channelId, new TCPServerNetworkChannel(this, asyncEventArgs.AcceptSocket, channelId)); + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + AcceptAsync(); + } + } + + public override void RemoveChannel(uint channelId) + { + if (IsDisposed || !_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (channel.IsDisposed) + { + return; + } + + channel.Dispose(); + } + + #region 网络线程(由Socket底层产生的线程) + + private void OnCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + switch (asyncEventArgs.LastOperation) + { + case SocketAsyncOperation.Accept: + { + Scene.ThreadSynchronizationContext.Post(() => + { + OnAcceptComplete(asyncEventArgs); + }); + break; + } + default: + { + throw new Exception($"Socket Accept Error: {asyncEventArgs.LastOperation}"); + } + } + } + + #endregion + } +} +#endif + + diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta new file mode 100644 index 0000000..ee16d19 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c798e74bff3b84245b957ce9bbeff9f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs new file mode 100644 index 0000000..15f3f66 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs @@ -0,0 +1,294 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net.Sockets; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.TCP +{ + public sealed class TCPServerNetworkChannel : ANetworkServerChannel + { + private bool _isSending; + private bool _isInnerDispose; + private readonly Socket _socket; + private readonly ANetwork _network; + private readonly Pipe _pipe = new Pipe(); + private readonly SocketAsyncEventArgs _sendArgs; + private readonly ReadOnlyMemoryPacketParser _packetParser; + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public TCPServerNetworkChannel(ANetwork network, Socket socket, uint id) : base(network, id, socket.RemoteEndPoint) + { + _socket = socket; + _network = network; + _socket.NoDelay = true; + _sendArgs = new SocketAsyncEventArgs(); + _sendArgs.Completed += OnSendCompletedHandler; + _packetParser = PacketParserFactory.CreateServerReadOnlyMemoryPacket(network); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + _network.RemoveChannel(Id); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + if (_socket != null) + { + _socket.Shutdown(SocketShutdown.Both); + _socket.Close(); + } + + _sendBuffers.Clear(); + _packetParser.Dispose(); + _isSending = false; + base.Dispose(); + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + var count = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + + if (count == 0) + { + Dispose(); + return; + } + + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send(); + } + } + + private void Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_sendBuffers.Count > 0) + { + var memoryStreamBuffer = _sendBuffers.Dequeue(); + _sendArgs.UserToken = memoryStreamBuffer; + _sendArgs.SetBuffer(new ArraySegment(memoryStreamBuffer.GetBuffer(), 0, (int)memoryStreamBuffer.Position)); + + try + { + if (_socket.SendAsync(_sendArgs)) + { + break; + } + + ReturnMemoryStream(memoryStreamBuffer); + } + catch + { + _isSending = false; + return; + } + } + + _isSending = false; + } + + private void ReturnMemoryStream(MemoryStreamBuffer memoryStream) + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _network.MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + + private void OnSendCompletedHandler(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.SocketError != SocketError.Success || asyncEventArgs.BytesTransferred == 0) + { + _isSending = false; + return; + } + + var memoryStreamBuffer = (MemoryStreamBuffer)asyncEventArgs.UserToken; + + Scene.ThreadSynchronizationContext.Post(() => + { + ReturnMemoryStream(memoryStreamBuffer); + + if (_sendBuffers.Count > 0) + { + Send(); + } + else + { + _isSending = false; + } + }); + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta new file mode 100644 index 0000000..59f2cfb --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a6e71caa8544bf04f8a9faefda9ec16a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket.meta new file mode 100644 index 0000000..b03efb7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d8b56697f07773e4b81c4afe610a4d83 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client.meta new file mode 100644 index 0000000..c145187 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 81c0dca986b7d084c9bf661bc5868e32 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs new file mode 100644 index 0000000..45e69e8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs @@ -0,0 +1,345 @@ +#if FANTASY_NET || FANTASY_CONSOLE +using System.Buffers; +using System.IO.Pipelines; +using System.Net.WebSockets; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Network.WebSocket +{ + public sealed class WebSocketClientNetwork : AClientNetwork + { + private bool _isSending; + private bool _isInnerDispose; + private long _connectTimeoutId; + private ClientWebSocket _clientWebSocket; + private ReadOnlyMemoryPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.WebSocket, networkTarget); + _packetParser = PacketParserFactory.CreateClientReadOnlyMemoryPacket(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + try + { + _isInnerDispose = true; + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + ClearConnectTimeout(); + WebSocketClientDisposeAsync().Coroutine(); + _onConnectDisconnect?.Invoke(); + _packetParser.Dispose(); + _packetParser = null; + _isSending = false; + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + private async FTask WebSocketClientDisposeAsync() + { + if (_clientWebSocket == null) + { + return; + } + + await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None); + _clientWebSocket.Dispose(); + _clientWebSocket = null; + } + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + if (IsInit) + { + throw new NotSupportedException( + $"WebSocketClientNetwork Id:{Id} Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + // 设置连接超时定时器 + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + + _clientWebSocket = new ClientWebSocket(); + var webSocketAddress = WebSocketHelper.GetWebSocketAddress(remoteAddress, isHttps); + + try + { + _clientWebSocket.ConnectAsync(new Uri(webSocketAddress), _cancellationTokenSource.Token).Wait(); + + if (_cancellationTokenSource.IsCancellationRequested) + { + return null; + } + } + catch (WebSocketException wse) + { + Log.Error($"WebSocket error: {wse.Message}"); + Dispose(); + return null; + } + catch (Exception e) + { + Log.Error($"An error occurred: {e.Message}"); + Dispose(); + return null; + } + + ClearConnectTimeout(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + _onConnectComplete?.Invoke(); + Session = Session.Create(this, null); + return Session; + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + // 这里接收的数据不一定是一个完整的包。如果大于8192就会分成多个包。 + var receiveResult = await _clientWebSocket.ReceiveAsync(memory, _cancellationTokenSource.Token); + + if (receiveResult.MessageType == WebSocketMessageType.Close) + { + break; + } + + var count = receiveResult.Count; + + if (count > 0) + { + await PipeWriterFlushAsync(count); + } + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + // 这个先暂时注释掉,因为有些时候会出现WebSocketException + // 因为会出现这个挥手的错误,下个版本处理一下。 + // The remote party closed the WebSocket connection without completing the close handshake. + // catch (WebSocketException wse) + // { + // Log.Error($"WebSocket error: {wse.Message}"); + // Dispose(); + // break; + // } + catch (Exception e) + { + Log.Error(e); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + private async FTask PipeWriterFlushAsync(int count) + { + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning(e.Message); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send().Coroutine(); + } + } + + private async FTask Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_isSending) + { + if (!_sendBuffers.TryDequeue(out var memoryStream)) + { + _isSending = false; + return; + } + + await _clientWebSocket.SendAsync(new ArraySegment(memoryStream.GetBuffer(), 0, (int)memoryStream.Position), WebSocketMessageType.Binary, true, _cancellationTokenSource.Token); + + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net?.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta new file mode 100644 index 0000000..e09c1bc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 04007ff05bd91cb4d826c14bacb40e93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs new file mode 100644 index 0000000..36ef84d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs @@ -0,0 +1,190 @@ +#if !FANTASY_NET && !FANTASY_CONSOLE +using System; +using System.Collections.Generic; +using System.IO; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using UnityWebSocket; + +namespace Fantasy.Network.WebSocket +{ + // 因为webgl的限制、注定这个要是在游戏主线程里。所以这个库不会再其他线程执行的。 + // WebGL:在WebGL环境下运行 + // 另外不是运行在WebGL环境下,也没必要使用WebSocket协议了。完全可以使用TCP或KCP运行。同样也不会有那个队列产生的GC。 + public class WebSocketClientNetwork : AClientNetwork + { + private UnityWebSocket.WebSocket _webSocket; + private bool _isInnerDispose; + private bool _isConnected; + private long _connectTimeoutId; + private BufferPacketParser _packetParser; + private readonly Queue _messageCache = new Queue(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.WebSocket, networkTarget); + _packetParser = PacketParserFactory.CreateClient(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + try + { + _isInnerDispose = true; + ClearConnectTimeout(); + + if (_webSocket != null && _webSocket.ReadyState != WebSocketState.Closed) + { + _onConnectDisconnect?.Invoke(); + _webSocket.CloseAsync(); + } + + _packetParser.Dispose(); + _messageCache.Clear(); + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + base.Dispose(); + } + } + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + // 如果已经初始化过一次,抛出异常,要求重新实例化 + + if (IsInit) + { + throw new NotSupportedException($"WebSocketClientNetwork Id:{Id} Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + var webSocketAddress = WebSocketHelper.GetWebSocketAddress(remoteAddress, isHttps); + _webSocket = new UnityWebSocket.WebSocket(webSocketAddress); + _webSocket.OnOpen += OnNetworkConnectComplete; + _webSocket.OnMessage += OnReceiveComplete; + _webSocket.OnClose += (sender, args) => + { + _onConnectDisconnect?.Invoke(); + Dispose(); + }; + _webSocket.ConnectAsync(); + Session = Session.Create(this, null); + return Session; + } + + private void OnNetworkConnectComplete(object sender, OpenEventArgs e) + { + if (IsDisposed) + { + return; + } + + _isConnected = true; + ClearConnectTimeout(); + _onConnectComplete?.Invoke(); + + while (_messageCache.TryDequeue(out var memoryStream)) + { + Send(memoryStream); + } + } + + #region Receive + + private void OnReceiveComplete(object sender, MessageEventArgs e) + { + try + { + // WebSocket 协议已经在协议层面处理了消息的边界问题,因此不需要额外的粘包处理逻辑。 + // 所以如果解包的时候出现任何错误只能是恶意攻击造成的。 + var rawDataLength = e.RawData.Length; + _packetParser.UnPack(e.RawData, ref rawDataLength, out var packInfo); + Session.Receive(packInfo); + } + catch (ScanException ex) + { + Log.Warning($"{ex}"); + Dispose(); + } + catch (Exception ex) + { + Log.Error($"{ex}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (IsDisposed) + { + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + + if (!_isConnected) + { + _messageCache.Enqueue(buffer); + return; + } + + Send(buffer); + } + + private void Send(MemoryStreamBuffer memoryStream) + { + _webSocket.SendAsync(memoryStream.GetBuffer(), 0, (int)memoryStream.Position); +#if !UNITY_EDITOR && UNITY_WEBGL + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } +#endif + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net?.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta new file mode 100644 index 0000000..08ad9b0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 414afd2468dbd8b4a894f323de33f23b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server.meta new file mode 100644 index 0000000..f0df159 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 063f12d180a250b4296e1e09cf7378e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs new file mode 100644 index 0000000..09feb2b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs @@ -0,0 +1,112 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +using System.Net; +using System.Security.Cryptography.X509Certificates; +using Fantasy.Async; +using Fantasy.Network.Interface; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable PossibleMultipleEnumeration +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Network.WebSocket; + +public class WebSocketServerNetwork : ANetwork +{ + private Random _random; + private HttpListener _httpListener; + private readonly Dictionary _connectionChannel = new Dictionary(); + + public void Initialize(NetworkTarget networkTarget, string bindIp, int port) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.WebSocket, networkTarget); + + try + { + _random = new Random(); + _httpListener = new HttpListener(); + StartAcceptAsync(bindIp, port).Coroutine(); + } + catch (HttpListenerException e) + { + if (e.ErrorCode == 5) + { + throw new Exception($"CMD管理员中输入: netsh http add urlacl url=http://*:8080/ user=Everyone", e); + } + + Log.Error(e); + } + catch (Exception e) + { + Log.Error(e); + } + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + if (_httpListener != null) + { + _httpListener.Close(); + _httpListener = null; + } + + foreach (var channel in _connectionChannel.Values.ToArray()) + { + channel.Dispose(); + } + + _connectionChannel.Clear(); + base.Dispose(); + } + + private async FTask StartAcceptAsync(string bindIp, int port) + { + var listenUrl = ""; + var certificatePath = Path.Combine(AppContext.BaseDirectory, $"certificate{bindIp}{port}"); + listenUrl = Directory.Exists(certificatePath) ? $"https://{bindIp}:{port}/" : $"http://{bindIp}:{port}/"; + _httpListener.Prefixes.Add(listenUrl); + _httpListener.Start(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} WebSocketServer Listen {listenUrl}"); + while (!IsDisposed) + { + try + { + var httpListenerContext = await _httpListener.GetContextAsync(); + var webSocketContext = await httpListenerContext.AcceptWebSocketAsync(null); + var channelId = 0xC0000000 | (uint) _random.Next(); + + while (_connectionChannel.ContainsKey(channelId)) + { + channelId = 0xC0000000 | (uint) _random.Next(); + } + + _connectionChannel.Add(channelId, new WebSocketServerNetworkChannel(this, channelId, webSocketContext, httpListenerContext.Request.RemoteEndPoint)); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void RemoveChannel(uint channelId) + { + if (IsDisposed || !_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (channel.IsDisposed) + { + return; + } + + channel.Dispose(); + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta new file mode 100644 index 0000000..be7734b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a76d22f75cf277346bd6efcb1e24c18c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs new file mode 100644 index 0000000..3b8ee90 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs @@ -0,0 +1,253 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.WebSocket; + +public sealed class WebSocketServerNetworkChannel : ANetworkServerChannel +{ + private bool _isSending; + private bool _isInnerDispose; + private readonly Pipe _pipe = new Pipe(); + private readonly System.Net.WebSockets.WebSocket _webSocket; + private readonly WebSocketServerNetwork _network; + private readonly ReadOnlyMemoryPacketParser _packetParser; + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public WebSocketServerNetworkChannel(ANetwork network, uint id, HttpListenerWebSocketContext httpListenerWebSocketContext, IPEndPoint remoteEndPoint) : base(network, id, remoteEndPoint) + { + _network = (WebSocketServerNetwork)network; + _webSocket = httpListenerWebSocketContext.WebSocket; + _packetParser = PacketParserFactory.CreateServerReadOnlyMemoryPacket(network); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + _sendBuffers.Clear(); + _network.RemoveChannel(Id); + if (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.CloseReceived) + { + _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", + _cancellationTokenSource.Token).GetAwaiter().GetResult(); + } + _webSocket.Dispose(); + _isSending = false; + base.Dispose(); + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + // 这里接收的数据不一定是一个完整的包。如果大于8192就会分成多个包。 + var receiveResult = await _webSocket.ReceiveAsync(memory, _cancellationTokenSource.Token); + + if (receiveResult.MessageType == WebSocketMessageType.Close) + { + Dispose(); + break; + } + + var count = receiveResult.Count; + + if (count > 0) + { + await PipeWriterFlushAsync(count); + } + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (WebSocketException) + { + // Log.Error($"WebSocket error: {wse.Message}"); + Dispose(); + break; + } + catch (Exception e) + { + Log.Error(e); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + private async FTask PipeWriterFlushAsync(int count) + { + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send().Coroutine(); + } + } + + private async FTask Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_isSending) + { + if (!_sendBuffers.TryDequeue(out var memoryStream)) + { + _isSending = false; + return; + } + + await _webSocket.SendAsync(new ArraySegment(memoryStream.GetBuffer(), 0, (int)memoryStream.Position), WebSocketMessageType.Binary, true, _cancellationTokenSource.Token); + + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _network.MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + #endregion +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta new file mode 100644 index 0000000..f6e9599 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b3101ddd3ce5e749b3e7e61938d0245 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming.meta b/Runtime/CoreRuntime/Core/Network/Roaming.meta new file mode 100644 index 0000000..2c9faad --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bdef21f877441bf47b4ec51e4cdf2397 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Component.meta new file mode 100644 index 0000000..17b0156 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b1b068344c9a03f4489e06b830bc3f51 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs new file mode 100644 index 0000000..a42d582 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs @@ -0,0 +1,254 @@ +#if FANTASY_NET +using System.Runtime.CompilerServices; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Timer; +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Network.Roaming; + +/// +/// 漫游组件,用来管理当然Scene下的所有漫游消息。 +/// 大多数是在Gate这样的转发服务器上创建的。 +/// +public sealed class RoamingComponent : Entity +{ + private TimerSchedulerNet _timerSchedulerNet; + private readonly Dictionary _sessionRoamingComponents = new(); + private readonly Dictionary _delayRemoveTaskId = new(); + + internal RoamingComponent Initialize() + { + _timerSchedulerNet = Scene.TimerComponent.Net; + return this; + } + + /// + /// 销毁方法。 + /// + public override void Dispose() + { + DisposeAsync().Coroutine(); + } + + private async FTask DisposeAsync() + { + foreach (var (_,taskId) in _delayRemoveTaskId) + { + _timerSchedulerNet.Remove(taskId); + } + + _delayRemoveTaskId.Clear(); + + foreach (var (_, sessionRoamingComponent) in _sessionRoamingComponents) + { + await sessionRoamingComponent.UnLink(); + } + + _sessionRoamingComponents.Clear(); + _timerSchedulerNet = null; + base.Dispose(); + } + + /// + /// 给Session会话增加漫游功能 + /// 如果指定的roamingId已经存在漫游,会把这个漫游功能和当前Session会话关联起来。 + /// + /// + /// 自定义roamingId,这个Id在漫游中并没有实际作用,但用户可以用这个id来进行标记。。 + /// 是否在Session断开的时候自动断开漫游功能。 + /// 如果开启了自定断开漫游功能需要设置一个延迟多久执行断开。 + /// 创建成功会返回SessionRoamingComponent组件,这个组件提供漫游的所有功能。 + public SessionRoamingComponent Create(Session session, long roamingId, bool isAutoDispose, int delayRemove) + { + if (session.SessionRoamingComponent != null) + { + if (session.SessionRoamingComponent.Id != roamingId) + { + Log.Error("The current session has created a SessionRoamingComponent."); + return null; + } + } + else + { + if (!_sessionRoamingComponents.TryGetValue(roamingId, out var sessionRoamingComponent)) + { + sessionRoamingComponent = Entity.Create(Scene, roamingId, true, true); + sessionRoamingComponent.Initialize(session); + _sessionRoamingComponents.Add(roamingId, sessionRoamingComponent); + } + } + + if (isAutoDispose) + { + session.AddComponent(roamingId).DelayRemove = delayRemove; + } + + return session.SessionRoamingComponent; + } + + /// + /// 获取当前Session会话的漫游组件 + /// + /// + /// + public SessionRoamingComponent Get(Session session) + { + var sessionRoamingFlgComponent = session.GetComponent(); + + if (sessionRoamingFlgComponent != null) + { + if (_sessionRoamingComponents.TryGetValue(sessionRoamingFlgComponent.Id, out var sessionRoamingComponent)) + { + return sessionRoamingComponent; + } + + Log.Error($"There is no SessionRoamingComponent with roamingId: {sessionRoamingFlgComponent.Id}."); + } + else + { + Log.Error("The current session has not created a roaming session yet, so you need to create one first."); + } + + return null; + } + + /// + /// 获取当前Session会话的漫游组件 + /// + /// + /// + /// + public bool TryGet(Session session, out SessionRoamingComponent sessionRoamingComponent) + { + var sessionRoamingFlgComponent = session.GetComponent(); + + if (sessionRoamingFlgComponent != null) + { + return _sessionRoamingComponents.TryGetValue(sessionRoamingFlgComponent.Id, out sessionRoamingComponent); + } + + sessionRoamingComponent = null; + return false; + } + + /// + /// 移除一个漫游 + /// + /// + /// 要移除的RoamingType,默认不设置是移除所有漫游。 + /// 当设置了延迟移除时间后,会在设置的时间后再进行移除。 + public async FTask Remove(long roamingId, int roamingType, int delayRemove = 0) + { + if (_delayRemoveTaskId.Remove(roamingId, out var taskId)) + { + _timerSchedulerNet.Remove(taskId); + } + + if (delayRemove <= 0) + { + await InnerRemove(roamingId, roamingType); + return; + } + + taskId = _timerSchedulerNet.OnceTimer(delayRemove, () => + { InnerRemove(roamingId, roamingType).Coroutine(); }); + _delayRemoveTaskId.Add(roamingId, taskId); + } + + private async FTask InnerRemove(long roamingId, int roamingType) + { + if (!_sessionRoamingComponents.Remove(roamingId, out var sessionRoamingComponent)) + { + return; + } + + await sessionRoamingComponent.UnLink(roamingType); + sessionRoamingComponent.Dispose(); + _delayRemoveTaskId.Remove(roamingId); + } +} + +/// +/// 漫游Roaming帮助类 +/// +public static class RoamingHelper +{ + /// + /// 给Session会话增加漫游功能 + /// 如果指定的roamingId已经存在漫游,会把这个漫游功能和当前Session会话关联起来。 + /// + /// + /// 自定义roamingId,这个Id在漫游中并没有实际作用,但用户可以用这个id来进行标记。 + /// 是否在Session断开的时候自动断开漫游功能。 + /// 如果开启了自定断开漫游功能需要设置一个延迟多久执行断开。 + /// 创建成功会返回SessionRoamingComponent组件,这个组件提供漫游的所有功能。 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static SessionRoamingComponent CreateRoaming(this Session session, long roamingId, bool isAutoDispose = true, int delayRemove = 1000 * 60 * 3) + { + return session.Scene.RoamingComponent.Create(session, roamingId, isAutoDispose, delayRemove); + } + + /// + /// 获取当前Session会话的漫游组件 + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static SessionRoamingComponent GetRoaming(this Session session) + { + return session.Scene.RoamingComponent.Get(session); + } + + /// + /// 获取当前Session会话的漫游组件 + /// + /// + /// + /// 如果返回为false表示没有获取到漫游组件。 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetRoaming(this Session session, out SessionRoamingComponent sessionRoamingComponent) + { + return session.Scene.RoamingComponent.TryGet(session, out sessionRoamingComponent); + } + + /// + /// 移除一个漫游 + /// + /// + /// 要移除的RoamingType,默认不设置是移除所有漫游。 + /// 当设置了延迟移除时间后,会在设置的时间后再进行移除。 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async FTask RemoveRoaming(this Session session, int roamingType = 0, int delayRemove = 0) + { + if (session.SessionRoamingComponent == null || session.SessionRoamingComponent.Id == 0) + { + return; + } + + await session.Scene.RoamingComponent.Remove(session.SessionRoamingComponent.Id, roamingType, delayRemove); + } + + /// + /// 移除一个漫游 + /// + /// + /// + /// 要移除的RoamingType,默认不设置是移除所有漫游。 + /// 当设置了延迟移除时间后,会在设置的时间后再进行移除。 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async FTask RemoveRoaming(Scene scene, long roamingId, int roamingType = 0, int delayRemove = 0) + { + if (roamingId == 0) + { + return; + } + + await scene.RoamingComponent.Remove(roamingId, roamingType, delayRemove); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs.meta new file mode 100644 index 0000000..6e847e1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/RoamingComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc7b9ff65ac69954a944e6a8cb9333dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs new file mode 100644 index 0000000..6834834 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs @@ -0,0 +1,390 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Platform.Net; +using Fantasy.Scheduler; +using Fantasy.Timer; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.Network.Roaming; + +internal sealed class SessionRoamingComponentDestroySystem : DestroySystem +{ + protected override void Destroy(SessionRoamingComponent self) + { + self.RoamingLock.Dispose(); + self.RoamingMessageLock.Dispose(); + + self.RoamingLock = null; + self.RoamingMessageLock = null; + self.TimerComponent = null; + self.NetworkMessagingComponent = null; + self.MessageDispatcherComponent = null; + } +} + +/// +/// Session的漫游组件。 +/// 用于关联对应的Session的功能。 +/// 但这个组件并不会挂载到这个Session下。 +/// +public sealed class SessionRoamingComponent : Entity +{ + internal CoroutineLock RoamingLock; + internal CoroutineLock RoamingMessageLock; + internal TimerComponent TimerComponent; + internal NetworkMessagingComponent NetworkMessagingComponent; + internal MessageDispatcherComponent MessageDispatcherComponent; + /// + /// 漫游的列表。 + /// + private readonly Dictionary _roaming = new Dictionary(); + + internal void Initialize(Session session) + { + session.SessionRoamingComponent = this; + + var scene = session.Scene; + TimerComponent = scene.TimerComponent; + NetworkMessagingComponent = scene.NetworkMessagingComponent; + MessageDispatcherComponent = scene.MessageDispatcherComponent; + RoamingLock = scene.CoroutineLockComponent.Create(this.GetType().TypeHandle.Value.ToInt64()); + RoamingMessageLock = scene.CoroutineLockComponent.Create(this.GetType().TypeHandle.Value.ToInt64()); + } + + #region Get + + /// + /// 尝试获取一个漫游。 + /// + /// + /// + /// + public bool TryGetRoaming(int roamingType, out Roaming roaming) + { + return _roaming.TryGetValue(roamingType, out roaming); + } + + #endregion + + #region Link + + /// + /// 建立漫游关系。 + /// + /// 要建立漫游协议的目标Scene的SceneConfig。 + /// 需要转发的Session + /// 要创建的漫游协议类型。 + /// 如果建立完成会返回为0,其余不为0的都是发生错误了。可以通过InnerErrorCode.cs来查看错误。 + public async FTask Link(Session session, SceneConfig targetSceneConfig, int roamingTyp) + { + return await Link(targetSceneConfig.RouteId, session.RuntimeId, roamingTyp); + } + + /// + /// 建立漫游关系。 + /// + /// 要建立漫游协议的目标Scene的RouteId。 + /// 需要转发的Session的RouteId。 + /// 要创建的漫游协议类型。 + /// 如果建立完成会返回为0,其余不为0的都是发生错误了。可以通过InnerErrorCode.cs来查看错误。 + public async FTask Link(long targetSceneRouteId, long forwardSessionRouteId, int roamingType) + { + if (_roaming.ContainsKey(roamingType)) + { + return InnerErrorCode.ErrLinkRoamingAlreadyExists; + } + + var response = (I_LinkRoamingResponse)await Scene.NetworkMessagingComponent.CallInnerRoute(targetSceneRouteId, + new I_LinkRoamingRequest() + { + RoamingId = Id, + RoamingType = roamingType, + ForwardSessionRouteId = forwardSessionRouteId, + SceneRouteId = Scene.RuntimeId + }); + + if (response.ErrorCode != 0) + { + return response.ErrorCode; + } + + var roaming = Entity.Create(Scene, true, true); + roaming.TerminusId = response.TerminusId; + roaming.TargetSceneRouteId = targetSceneRouteId; + roaming.ForwardSessionRouteId = forwardSessionRouteId; + roaming.SessionRoamingComponent = this; + roaming.RoamingType = roamingType; + roaming.RoamingLock = RoamingLock; + _roaming.Add(roamingType, roaming); + return 0; + } + + #endregion + + #region UnLink + + /// + /// 断开当前的所有漫游关系。 + /// 要移除的RoamingType,默认不设置是移除所有漫游。 + /// + public async FTask UnLink(int removeRoamingType = 0) + { + switch (removeRoamingType) + { + case 0: + { + foreach (var (roamingType,roaming) in _roaming) + { + try + { + var errorCode = await roaming.Disconnect(); + + if (errorCode != 0) + { + Log.Warning($"roaming roamingId:{Id} roamingType:{roamingType} disconnect errorCode:{errorCode}"); + } + } + finally + { + roaming.Dispose(); + } + } + + _roaming.Clear(); + return; + } + default: + { + if (!_roaming.Remove(removeRoamingType, out var roaming)) + { + return; + } + + var errorCode = await roaming.Disconnect(); + + if (errorCode != 0) + { + Log.Warning($"roaming roamingId:{Id} roamingType:{removeRoamingType} disconnect errorCode:{errorCode}"); + } + + roaming.Dispose(); + return; + } + } + } + + #endregion + + #region OuterMessage + + /// + /// 发送一个消息给漫游终 + /// + /// + public void Send(IRoamingMessage message) + { + Call(message.RouteType, message).Coroutine(); + } + + /// + /// 发送一个消息给漫游终端 + /// + /// + /// + public void Send(int roamingType, IRouteMessage message) + { + Call(roamingType, message).Coroutine(); + } + + /// + /// 发送一个RPC消息给漫游终端 + /// + /// + /// + public async FTask Call(IRoamingMessage message) + { + return await Call(message.RouteType, message); + } + + /// + /// 发送一个RPC消息给漫游终端 + /// + /// + /// + /// + public async FTask Call(int roamingType, IRouteMessage message) + { + if (!_roaming.TryGetValue(roamingType, out var roaming)) + { + return MessageDispatcherComponent.CreateResponse(message.GetType(), InnerErrorCode.ErrNotFoundRoaming); + } + + var failCount = 0; + var runtimeId = RuntimeId; + var routeId = roaming.TerminusId; + var requestType = message.GetType(); + + IResponse iRouteResponse = null; + + using (await RoamingMessageLock.Wait(roaming.RoamingType, "RoamingComponent Call MemoryStream")) + { + while (!IsDisposed) + { + if (routeId == 0) + { + routeId = await roaming.GetTerminusId(); + } + + if (routeId == 0) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoaming); + } + + iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(routeId, message); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRoamingTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrRouteTimeout: + case InnerErrorCode.ErrRoamingTimeout: + { + return iRouteResponse; + } + case InnerErrorCode.ErrNotFoundRoute: + case InnerErrorCode.ErrNotFoundRoaming: + { + if (++failCount > 20) + { + Log.Error($"RoamingComponent.Call failCount > 20 route send message fail, LinkRoamingId: {routeId}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(100); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrNotFoundRoaming; + } + + routeId = 0; + continue; + } + default: + { + return iRouteResponse; // 对于其他情况,直接返回响应,无需额外处理 + } + } + } + } + + return iRouteResponse; + } + + #endregion + + #region InnerMessage + + internal async FTask Send(int roamingType, Type requestType, APackInfo packInfo) + { + await Call(roamingType, requestType, packInfo); + } + + internal async FTask Call(int roamingType, Type requestType, APackInfo packInfo) + { + if (IsDisposed) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoaming); + } + + packInfo.IsDisposed = true; + + if (!_roaming.TryGetValue(roamingType, out var roaming)) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoaming); + } + + var failCount = 0; + var runtimeId = RuntimeId; + var routeId = roaming.TerminusId; + IResponse iRouteResponse = null; + + try + { + using (await RoamingMessageLock.Wait(roamingType, "RoamingComponent Call MemoryStream")) + { + while (!IsDisposed) + { + if (routeId == 0) + { + routeId = await roaming.GetTerminusId(); + } + + if (routeId == 0) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoaming); + } + + iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(routeId, requestType, packInfo); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRoamingTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrRouteTimeout: + case InnerErrorCode.ErrRoamingTimeout: + { + return iRouteResponse; + } + case InnerErrorCode.ErrNotFoundRoute: + case InnerErrorCode.ErrNotFoundRoaming: + { + if (++failCount > 20) + { + Log.Error($"RoamingComponent.Call failCount > 20 route send message fail, LinkRoamingId: {routeId}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(100); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrNotFoundRoaming; + } + routeId = 0; + continue; + } + default: + { + return iRouteResponse; // 对于其他情况,直接返回响应,无需额外处理 + } + } + } + } + } + finally + { + packInfo.Dispose(); + } + + return iRouteResponse; + } + + #endregion +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs.meta new file mode 100644 index 0000000..7e08dd2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86ef91e743d245046b5ba1d4b015c5cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs new file mode 100644 index 0000000..23f4c33 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs @@ -0,0 +1,23 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.Entitas; +namespace Fantasy.Network.Roaming; + +internal sealed class SessionRoamingFlgComponent : Entity +{ + public int DelayRemove; + + public override void Dispose() + { + DisposeAsync().Coroutine(); + } + + private async FTask DisposeAsync() + { + var roamingId = Id; + await Scene.RoamingComponent.Remove(roamingId, 0, DelayRemove); + DelayRemove = 0; + base.Dispose(); + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs.meta new file mode 100644 index 0000000..3db1c84 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/SessionRoamingFlgComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed11dc83d25ee714eb442fac63522501 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs new file mode 100644 index 0000000..0185261 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs @@ -0,0 +1,138 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.DataStructure.Dictionary; +using Fantasy.Entitas; +using Fantasy.Network; +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Network.Roaming; + +/// +/// 当Terminus创建完成后发送的事件参数 +/// +public struct OnCreateTerminus +{ + /// + /// 获取与事件关联的场景实体。 + /// + public readonly Scene Scene; + /// + /// 获取与事件关联的Terminus。 + /// + public readonly Terminus Terminus; + /// + /// 初始化一个新的 OnCreateTerminus 实例。 + /// + /// + /// + public OnCreateTerminus(Scene scene, Terminus terminus) + { + Scene = scene; + Terminus = terminus; + } +} + +/// +/// 漫游终端管理组件。 +/// 这个组件不需要手动挂载,会在Scene启动的时候自动挂载这个组件。 +/// +public sealed class TerminusComponent : Entity +{ + /// + /// 漫游终端的实体集合。 + /// + private readonly Dictionary _terminals = new(); + + /// + /// Dispose + /// + public override void Dispose() + { + foreach (var (_, terminus) in _terminals) + { + terminus.Dispose(); + } + + _terminals.Clear(); + base.Dispose(); + } + + /// + /// 创建一个新的漫游终端。 + /// + /// + /// + /// + /// + /// + public async FTask<(uint, Terminus)> Create(long roamingId, int roamingType, long forwardSessionRouteId, long forwardSceneRouteId) + { + if (_terminals.ContainsKey(roamingId)) + { + return (InnerErrorCode.ErrAddRoamingTerminalAlreadyExists, null); + } + + var terminus = roamingId == 0 + ? Entity.Create(Scene, false, true) + : Entity.Create(Scene, roamingId, false, true); + terminus.RoamingType = roamingType; + terminus.TerminusId = terminus.RuntimeId; + terminus.ForwardSceneRouteId = forwardSceneRouteId; + terminus.ForwardSessionRouteId = forwardSessionRouteId; + terminus.RoamingMessageLock = Scene.CoroutineLockComponent.Create(terminus.Type.TypeHandle.Value.ToInt64()); + await Scene.EventComponent.PublishAsync(new OnCreateTerminus(Scene, terminus)); + _terminals.Add(terminus.Id, terminus); + return (0U, terminus); + } + + /// + /// 添加一个漫游终端。 + /// + /// + public void AddTerminus(Terminus terminus) + { + _terminals.Add(terminus.Id, terminus); + } + + /// + /// 根据roamingId获取一个漫游终端。 + /// + /// + /// + /// + public bool TryGetTerminus(long roamingId, out Terminus terminus) + { + return _terminals.TryGetValue(roamingId, out terminus); + } + + /// + /// 根据roamingId获取一个漫游终端。 + /// + /// + /// + public Terminus GetTerminus(long roamingId) + { + return _terminals[roamingId]; + } + + /// + /// 根据roamingId移除一个漫游终端。 + /// + /// + /// + public void RemoveTerminus(long roamingId, bool isDispose = true) + { + if (!_terminals.Remove(roamingId, out var terminus)) + { + return; + } + + if (isDispose) + { + terminus.Dispose(); + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs.meta new file mode 100644 index 0000000..976b66b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Component/TerminusComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42c461e17646ec54bb64320a91d8003b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Entity.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Entity.meta new file mode 100644 index 0000000..d768eda --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Entity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 600fa6f48ca422d419c52dea2c49e325 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs new file mode 100644 index 0000000..33a5355 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs @@ -0,0 +1,132 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.InnerMessage; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +namespace Fantasy.Network.Roaming; + +/// +/// 漫游实体 +/// +public sealed class Roaming : Entity +{ + /// + /// 连接到漫游TerminusId。 + /// 也可以理解为目标实体的RouteId。 + /// + internal long TerminusId; + /// + /// 漫游目标Scene的RouteId。 + /// + public long TargetSceneRouteId { get; internal set; } + /// + /// 漫游转发Session的RouteId。 + /// + public long ForwardSessionRouteId { get; internal set; } + /// + /// 当前漫游类型。 + /// + public int RoamingType { get; internal set; } + /// + /// 协程锁。 + /// + internal CoroutineLock RoamingLock; + /// + /// 当前正在执行的协程锁。 + /// + private WaitCoroutineLock? _waitCoroutineLock; + /// + /// 关联Session的漫游组件。 + /// + internal SessionRoamingComponent SessionRoamingComponent; + /// + /// 获得当前漫游对应终端的TerminusId。 + /// + /// + internal async FTask GetTerminusId() + { + using (await RoamingLock.Wait(RoamingType,"Roaming.cs GetTerminusId")) + { + return TerminusId; + } + } + /// + /// 设置当前漫游对应的终端的TerminusId。 + /// + /// + internal async FTask SetTerminusId(long terminusId) + { + using (await RoamingLock.Wait(RoamingType,"Roaming.cs SetTerminusId")) + { + TerminusId = terminusId; + } + } + /// + /// 锁定TerminusId。 + /// + internal async FTask LockTerminusId() + { + _waitCoroutineLock = await RoamingLock.Wait(RoamingType,"Roaming.cs LockTerminusId"); + } + + /// + /// 解锁TerminusId。 + /// + /// + /// + internal void UnLockTerminusId(long terminusId, long targetSceneRouteId) + { + if (_waitCoroutineLock == null) + { + Log.Error("terminusId unlock waitCoroutineLock is null"); + return; + } + + TerminusId = terminusId; + TargetSceneRouteId = targetSceneRouteId; + _waitCoroutineLock.Dispose(); + _waitCoroutineLock = null; + } + + /// + /// 断开当前漫游的连接。 + /// + /// + public async FTask Disconnect() + { + var response = + await Scene.NetworkMessagingComponent.CallInnerRoute(TargetSceneRouteId, new I_UnLinkRoamingRequest() + { + RoamingId = SessionRoamingComponent.Id + }); + return response.ErrorCode; + } + /// + /// 销毁方法 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + if (_waitCoroutineLock != null) + { + _waitCoroutineLock.Dispose(); + _waitCoroutineLock = null; + } + + TerminusId = 0; + TargetSceneRouteId = 0; + ForwardSessionRouteId = 0; + + RoamingLock = null; + SessionRoamingComponent = null; + base.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs.meta new file mode 100644 index 0000000..275d7da --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Roaming.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4e7145491812ad40b2fdb39b18da912 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs new file mode 100644 index 0000000..8d4448b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs @@ -0,0 +1,338 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Scheduler; +using MongoDB.Bson.Serialization.Attributes; +// ReSharper disable UnassignedField.Global +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.Network.Roaming; + +/// +/// 漫游终端实体 +/// +public sealed class Terminus : Entity +{ + /// + /// 当前漫游终端的TerminusId。 + /// 可以通过 TerminusId 发送消息给这个漫游终端。 + /// 也可以理解为实体的RuntimeId。 + /// + internal long TerminusId; + /// + /// 当前漫游终端的类型。 + /// + [BsonElement("r")] + internal int RoamingType; + /// + /// 漫游转发Session所在的Scene的RouteId。 + /// + [BsonElement("s")] + internal long ForwardSceneRouteId; + /// + /// 漫游转发Session的RouteId。 + /// 不知道原理千万不要手动赋值这个。 + /// + [BsonElement("f")] + internal long ForwardSessionRouteId; + /// + /// 关联的玩家实体 + /// + [BsonElement("e")] + public Entity TerminusEntity; + /// + /// 漫游消息锁。 + /// + [BsonIgnore] + internal CoroutineLock RoamingMessageLock; + /// + /// 获得转发的SessionRouteId,可以通过这个Id来发送消息来自动转发到客户端。 + /// + public long SessionRouteId => ForwardSessionRouteId; + /// + /// 存放其他漫游终端的Id。 + /// 通过这个Id可以发送消息给它。 + /// + [BsonIgnore] + private readonly Dictionary _roamingTerminusId = new Dictionary(); + /// + /// 创建关联的终端实体。 + /// 创建完成后,接收消息都是由关联的终端实体来处理。 + /// 注意,当你销毁这个实体的时候,并不能直接销毁Terminus,会导致无法接收到漫游消息。 + /// + /// + /// + public T LinkTerminusEntity() where T : Entity, new() + { + if (TerminusEntity != null) + { + Log.Error($"TerminusEntity:{TerminusEntity.Type.FullName} Already exists!"); + return null; + } + + var t = Entity.Create(Scene, true, true); + TerminusEntity = t; + TerminusId = TerminusEntity.RuntimeId; + return t; + } + + /// + /// 关联的终端实体。 + /// 注意,当你销毁这个实体的时候,并不能直接销毁Terminus,会导致无法接收到漫游消息 + /// + /// + public void LinkTerminusEntity(Entity entity) + { + if (entity == null) + { + Log.Error("Entity cannot be empty"); + return; + } + + if (TerminusEntity != null) + { + Log.Error($"TerminusEntity:{TerminusEntity.Type.FullName} Already exists!"); + return; + } + + TerminusEntity = entity; + TerminusId = TerminusEntity.RuntimeId; + } + + #region Transfer + + /// + /// 传送漫游终端 + /// 传送完成后,漫游终端和关联的玩家实体都会被销毁。 + /// 所以如果有其他组件关联这个实体,要提前记录好Id,方便传送后清理。 + /// + /// + public async FTask StartTransfer(long targetSceneRouteId) + { + var currentSceneRouteId = Scene.SceneConfig.RouteId; + if (targetSceneRouteId == currentSceneRouteId) + { + Log.Warning($"Unable to teleport to your own scene targetSceneRouteId:{targetSceneRouteId} == currentSceneRouteId:{currentSceneRouteId}"); + return 0; + } + + try + { + // 传送目标服务器之前要先锁定,防止再传送过程中还有其他消息发送过来。 + var lockErrorCode = await Lock(); + if (lockErrorCode != 0) + { + return lockErrorCode; + } + // 开始执行传送请求。 + var response = (I_TransferTerminusResponse)await Scene.NetworkMessagingComponent.CallInnerRoute( + targetSceneRouteId, + new I_TransferTerminusRequest() + { + Terminus = this + }); + if (response.ErrorCode != 0) + { + // 如果传送出现异常,需要先解锁,不然会出现一直卡死的问题。 + await UnLock(); + return response.ErrorCode; + } + // 在当前Scene下移除漫游终端。 + Scene.TerminusComponent.RemoveTerminus(Id); + } + catch (Exception e) + { + Log.Error(e); + // 如果代码执行出现任何异常,要先去解锁,避免会出现卡死的问题。 + await UnLock(); + return InnerErrorCode.ErrTerminusStartTransfer; + } + + return 0; + } + + /// + /// 传送完成。 + /// 当传送完成后,需要清理漫游终端。 + /// + /// + public async FTask TransferComplete(Scene scene) + { + // 首先恢复漫游终端的序列化数据。并且注册到框架中。 + Deserialize(scene); + TerminusId = RuntimeId; + if (TerminusEntity != null) + { + TerminusEntity.Deserialize(scene); + TerminusId = TerminusEntity.RuntimeId; + } + // 然后要解锁下漫游 + return await UnLock(); + } + + /// + /// 锁定漫游当执行锁定了后,所有消息都会被暂时放入队列中不会发送。 + /// 必须要解锁后才能继续发送消息。 + /// + /// + public async FTask Lock() + { + var response = await Scene.NetworkMessagingComponent.CallInnerRoute(ForwardSceneRouteId, + new I_LockTerminusIdRequest() + { + SessionRuntimeId = ForwardSessionRouteId, + RoamingType = RoamingType + }); + return response.ErrorCode; + } + + /// + /// 锁定漫游 + /// + /// + public async FTask UnLock() + { + var response = await Scene.NetworkMessagingComponent.CallInnerRoute(ForwardSceneRouteId, + new I_UnLockTerminusIdRequest() + { + SessionRuntimeId = ForwardSessionRouteId, + RoamingType = RoamingType, + TerminusId = TerminusId, + TargetSceneRouteId = Scene.RouteId + }); + return response.ErrorCode; + } + + #endregion + + #region Message + + private async FTask GetTerminusId(int roamingType) + { + if (IsDisposed) + { + return 0; + } + + var response = (I_GetTerminusIdResponse)await Scene.NetworkMessagingComponent.CallInnerRoute( + ForwardSceneRouteId, + new I_GetTerminusIdRequest() + { + SessionRuntimeId = ForwardSessionRouteId, + RoamingType = roamingType + }); + return response.TerminusId; + } + + /// + /// 发送一个消息给客户端 + /// + /// + public void Send(IRouteMessage message) + { + Scene.NetworkMessagingComponent.SendInnerRoute(ForwardSessionRouteId, message); + } + /// + /// 发送一个漫游消息 + /// + /// + /// + public void Send(int roamingType, IRoamingMessage message) + { + Call(roamingType, message).Coroutine(); + } + + /// + /// 发送一个漫游RPC消息。 + /// + /// + /// + /// + public async FTask Call(int roamingType, IRoamingMessage request) + { + if (IsDisposed) + { + return Scene.MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoaming); + } + + if (roamingType == RoamingType) + { + Log.Warning($"Does not support sending messages to the same scene as roamingType currentRoamingType:{RoamingType} roamingType:{roamingType}"); + return Scene.MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoaming); + } + + var failCount = 0; + var runtimeId = RuntimeId; + IResponse iRouteResponse = null; + _roamingTerminusId.TryGetValue(roamingType, out var routeId); + + using (await RoamingMessageLock.Wait(roamingType, "Terminus Call request")) + { + while (!IsDisposed) + { + if (routeId == 0) + { + routeId = await GetTerminusId(roamingType); + + if (routeId != 0) + { + _roamingTerminusId[roamingType] = routeId; + } + else + { + return Scene.MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoaming); + } + } + + iRouteResponse = await Scene.NetworkMessagingComponent.CallInnerRoute(routeId, request); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRoamingTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrRouteTimeout: + case InnerErrorCode.ErrRoamingTimeout: + { + return iRouteResponse; + } + case InnerErrorCode.ErrNotFoundRoute: + case InnerErrorCode.ErrNotFoundRoaming: + { + if (++failCount > 20) + { + Log.Error($"Terminus.Call failCount > 20 route send message fail, TerminusId: {routeId}"); + return iRouteResponse; + } + + await Scene.TimerComponent.Net.WaitAsync(100); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrNotFoundRoaming; + } + + routeId = 0; + continue; + } + default: + { + return iRouteResponse; // 对于其他情况,直接返回响应,无需额外处理 + } + } + } + } + + return iRouteResponse; + } + + #endregion +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs.meta new file mode 100644 index 0000000..2395f82 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Entity/Terminus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb23a76ca94f75944b2d947577322a13 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler.meta new file mode 100644 index 0000000..31196a1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: afd2120283a7c6a4a80be71d8377886f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs new file mode 100644 index 0000000..90f7ab9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs @@ -0,0 +1,32 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Network.Roaming; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.Roaming.Handler; + +internal sealed class I_GetTerminusIdRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_GetTerminusIdRequest request, I_GetTerminusIdResponse response, Action reply) + { + if (!scene.TryGetEntity(request.SessionRuntimeId, out var sessionEntity)) + { + response.ErrorCode = InnerErrorCode.ErrLockTerminusIdNotFoundSession; + return; + } + + var session = (Session)sessionEntity; + + if (!scene.RoamingComponent.TryGet(session, out var sessionRoamingComponent) || !sessionRoamingComponent.TryGetRoaming(request.RoamingType, out var sessionRoaming)) + { + response.ErrorCode = InnerErrorCode.ErrLockTerminusIdNotFoundRoamingType; + return; + } + + response.TerminusId = await sessionRoaming.GetTerminusId(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs.meta new file mode 100644 index 0000000..6893643 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_GetTerminusIdRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c668e09741af41498fd8315198013ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs new file mode 100644 index 0000000..6efb58c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs @@ -0,0 +1,26 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Roaming.Handler; + +public sealed class I_LinkRoamingRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_LinkRoamingRequest request, I_LinkRoamingResponse response, Action reply) + { + var (errorCode, roamingTerminal) = await scene.TerminusComponent.Create( + request.RoamingId, request.RoamingType, + request.ForwardSessionRouteId, request.SceneRouteId); + + if (errorCode != 0) + { + response.ErrorCode = errorCode; + return; + } + + response.TerminusId = roamingTerminal.TerminusId; + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs.meta new file mode 100644 index 0000000..75c6c76 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LinkRoamingRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fe2e60c6d58efb4d9b360ed50d7ea9d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs new file mode 100644 index 0000000..c530a1e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs @@ -0,0 +1,35 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Network.Interface; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Roaming.Handler; + +/// +/// 内部网络漫游锁定的请求处理。 +/// +internal sealed class I_LockTerminusIdRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_LockTerminusIdRequest request, I_LockTerminusIdResponse response, Action reply) + { + if (!scene.TryGetEntity(request.SessionRuntimeId, out var sessionEntity)) + { + response.ErrorCode = InnerErrorCode.ErrLockTerminusIdNotFoundSession; + return; + } + + var session = (Session)sessionEntity; + + if (!scene.RoamingComponent.TryGet(session, out var sessionRoamingComponent) || !sessionRoamingComponent.TryGetRoaming(request.RoamingType, out var sessionRoaming)) + { + response.ErrorCode = InnerErrorCode.ErrLockTerminusIdNotFoundRoamingType; + return; + } + + await sessionRoaming.LockTerminusId(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs.meta new file mode 100644 index 0000000..0b16418 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_LockTerminusIdRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42c67413a4a338749839e0d65d681034 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs new file mode 100644 index 0000000..162171f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs @@ -0,0 +1,22 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Roaming.Handler; + +/// +/// 传送漫游Terminus的请求处理 +/// +internal sealed class I_TransferTerminusRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_TransferTerminusRequest request, I_TransferTerminusResponse response, Action reply) + { + // 添加Terminus到当前Scene下。 + scene.TerminusComponent.AddTerminus(request.Terminus); + // 执行Terminus的传送完成逻辑。 + await request.Terminus.TransferComplete(scene); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs.meta new file mode 100644 index 0000000..19e532c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_TransferTerminusRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e5a5974ef626ce0489d844c2bda00045 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs new file mode 100644 index 0000000..5849b11 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs @@ -0,0 +1,16 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +namespace Fantasy.Roaming.Handler; + +internal sealed class I_UnLinkRoamingRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_UnLinkRoamingRequest request, I_UnLinkRoamingResponse response, Action reply) + { + scene.TerminusComponent.RemoveTerminus(request.RoamingId, request.DisposeRoaming); + await FTask.CompletedTask; + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs.meta new file mode 100644 index 0000000..a673283 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLinkRoamingRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc06e04239929c147886d67e878b3b28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs new file mode 100644 index 0000000..8a04079 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs @@ -0,0 +1,36 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Network.Interface; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Roaming.Handler; + +/// +/// 内部网络漫游解锁的请求处理。 +/// +internal sealed class I_UnLockTerminusIdRequestHandler : RouteRPC +{ + protected override async FTask Run(Scene scene, I_UnLockTerminusIdRequest request, I_UnLockTerminusIdResponse response, Action reply) + { + if (!scene.TryGetEntity(request.SessionRuntimeId, out var sessionEntity)) + { + response.ErrorCode = InnerErrorCode.ErrUnLockTerminusIdNotFoundSession; + return; + } + + var session = (Session)sessionEntity; + + if (!scene.RoamingComponent.TryGet(session, out var sessionRoamingComponent) || !sessionRoamingComponent.TryGetRoaming(request.RoamingType, out var sessionRoaming)) + { + response.ErrorCode = InnerErrorCode.ErrLockTerminusIdNotFoundRoamingType; + return; + } + + sessionRoaming.UnLockTerminusId(request.TerminusId, request.TargetSceneRouteId); + await FTask.CompletedTask; + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs.meta b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs.meta new file mode 100644 index 0000000..363ef50 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Roaming/Handler/I_UnLockTerminusIdRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e544bcf93c7ced44a9f4fbea7f4a19ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Route.meta b/Runtime/CoreRuntime/Core/Network/Route.meta new file mode 100644 index 0000000..4dbfdfd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Route.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6058750e614f61241b1ee2b48c7a9816 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs b/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs new file mode 100644 index 0000000..1ce1fe8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs @@ -0,0 +1,82 @@ +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#if FANTASY_NET +namespace Fantasy.Network; + +/// +/// RouteComponent的AwakeSystem +/// +public sealed class RouteComponentAwakeSystem : AwakeSystem +{ + /// + /// Awake + /// + /// + /// + protected override void Awake(RouteComponent self) + { + ((Session)self.Parent).RouteComponent = self; + } +} + +/// +/// 自定义Route组件、如果要自定义Route协议必须使用这个组件 +/// +public sealed class RouteComponent : Entity +{ + /// + /// 存储路由类型和路由ID的映射关系。 + /// + public readonly Dictionary RouteAddress = new Dictionary(); + + /// + /// 添加路由类型和路由ID的映射关系。 + /// + /// 路由类型。 + /// 路由ID。 + public void AddAddress(long routeType, long routeId) + { + RouteAddress.Add(routeType, routeId); + } + + /// + /// 移除指定路由类型的映射关系。 + /// + /// 路由类型。 + public void RemoveAddress(long routeType) + { + RouteAddress.Remove(routeType); + } + + /// + /// 获取指定路由类型的路由ID。 + /// + /// 路由类型。 + /// 路由ID。 + public long GetRouteId(long routeType) + { + return RouteAddress.GetValueOrDefault(routeType, 0); + } + + /// + /// 尝试获取指定路由类型的路由ID。 + /// + /// 路由类型。 + /// 输出的路由ID。 + /// 如果获取成功返回true,否则返回false。 + public bool TryGetRouteId(long routeType, out long routeId) + { + return RouteAddress.TryGetValue(routeType, out routeId); + } + + /// + /// 释放组件资源,清空映射关系。 + /// + public override void Dispose() + { + RouteAddress.Clear(); + base.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs.meta new file mode 100644 index 0000000..ea223b9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Route/RouteComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 01dbfcd5ea1d37a4380936ea672e6f6b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session.meta b/Runtime/CoreRuntime/Core/Network/Session.meta new file mode 100644 index 0000000..1346249 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e558fcdc7cbb4fc42a3be6ca48af4570 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component.meta b/Runtime/CoreRuntime/Core/Network/Session/Component.meta new file mode 100644 index 0000000..d6962f1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 847bcccfb838eb14aba0faed9a8fa279 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs b/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs new file mode 100644 index 0000000..dc4677e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs @@ -0,0 +1,156 @@ +// ReSharper disable MemberCanBePrivate.Global + +#if FANTASY_CONSOLE + +using System; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.InnerMessage; +using Fantasy.Timer; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network +{ + public class SessionHeartbeatComponentAwakeSystem : AwakeSystem + { + protected override void Awake(SessionHeartbeatComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } + } + + /// + /// 负责管理会话心跳的组件。 + /// + public class SessionHeartbeatComponent : Entity + { + public int TimeOut; + public long TimerId; + public long LastTime; + public long SelfRunTimeId; + public long TimeOutTimerId; + public long SessionRunTimeId; + public TimerComponent TimerComponent; + public EntityReference Session; + private readonly PingRequest _pingRequest = new PingRequest(); + + public int Ping { get; private set; } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + Stop(); + Ping = 0; + Session = null; + TimeOut = 0; + SelfRunTimeId = 0; + base.Dispose(); + } + + /// + /// 使用指定的间隔启动心跳功能。 + /// + /// 以毫秒为单位的心跳请求发送间隔。 + /// 设置与服务器的通信超时时间,如果超过这个时间限制,将自动断开会话(Session)。 + /// 用于检测与服务器连接超时频率。 + public void Start(int interval, int timeOut = 2000, int timeOutInterval = 3000) + { + TimeOut = timeOut + interval; + Session = (Session)Parent; + SelfRunTimeId = RuntimeId; + LastTime = TimeHelper.Now; + + if (TimerComponent == null) + { + Log.Error("请在Unity的菜单执行Fantasy->Generate link.xml再重新打包"); + return; + } + + TimerId = TimerComponent.Net.RepeatedTimer(interval, () => RepeatedSend().Coroutine()); + TimeOutTimerId = TimerComponent.Net.RepeatedTimer(timeOutInterval, CheckTimeOut); + } + + private void CheckTimeOut() + { + if (TimeHelper.Now - LastTime < TimeOut) + { + return; + } + + Session entityReference = Session; + + if (entityReference == null) + { + return; + } + + entityReference.Dispose(); + } + + /// + /// 停止心跳功能。 + /// + public void Stop() + { + if (TimerId != 0) + { + TimerComponent?.Net.Remove(ref TimerId); + } + + if (TimeOutTimerId != 0) + { + TimerComponent?.Net.Remove(ref TimeOutTimerId); + } + } + + /// + /// 异步发送心跳请求并处理响应。 + /// + /// 表示进行中操作的异步任务。 + private async FTask RepeatedSend() + { + if (SelfRunTimeId != RuntimeId) + { + Stop(); + return; + } + + Session session = Session; + + if (session == null) + { + Dispose(); + return; + } + + try + { + var requestTime = TimeHelper.Now; + + var pingResponse = (PingResponse)await session.Call(_pingRequest); + + if (pingResponse.ErrorCode != 0) + { + return; + } + + var responseTime = TimeHelper.Now; + LastTime = responseTime; + Ping = (int)(responseTime - requestTime) / 2; + TimeHelper.TimeDiff = pingResponse.Now + Ping - responseTime; + } + catch (Exception) + { + Dispose(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta new file mode 100644 index 0000000..66a7240 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c25e88340834bfd4f9fee81ebc395076 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs b/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs new file mode 100644 index 0000000..4a8845d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs @@ -0,0 +1,116 @@ +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Timer; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network; + +public class SessionIdleCheckerComponentAwakeSystem : AwakeSystem +{ + protected override void Awake(SessionIdleCheckerComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } +} + +/// +/// 负责检查会话空闲超时的组件。 +/// +public class SessionIdleCheckerComponent : Entity +{ + /// + /// 空闲超时时间(毫秒) + /// + private long _timeOut; + /// + /// 检查计时器的 ID + /// + private long _timerId; + /// + /// 用于确保组件完整性的自身运行时 ID + /// + private long _selfRuntimeId; + /// + /// 对会话对象的引用 + /// + private Session _session; + public TimerComponent TimerComponent; + + /// + /// 重写 Dispose 方法以释放资源。 + /// + public override void Dispose() + { + Stop(); // 停止检查计时器 + _timeOut = 0; // 重置空闲超时时间 + _selfRuntimeId = 0; // 重置自身运行时 ID + _session = null; // 清除会话引用 + base.Dispose(); + } + + /// + /// 使用指定的间隔和空闲超时时间启动空闲检查功能。 + /// + /// 以毫秒为单位的检查间隔。 + /// 以毫秒为单位的空闲超时时间。 + internal void Start(int interval, int timeOut) + { + _timeOut = timeOut; + _session = (Session)Parent; + _selfRuntimeId = RuntimeId; + // 安排重复计时器,在指定的间隔内执行 Check 方法 + _timerId = TimerComponent.Net.RepeatedTimer(interval, Check); + } + + /// + /// 重新开始心跳检查 + /// + /// 以毫秒为单位的检查间隔。 + /// 以毫秒为单位的空闲超时时间。 + public void Restart(int interval, int timeOut) + { + Stop(); + Start(interval, timeOut); + } + + /// + /// 停止空闲检查功能。 + /// + private void Stop() + { + if (_timerId == 0) + { + return; + } + + TimerComponent.Net.Remove(ref _timerId); + } + + /// + /// 执行空闲检查操作。 + /// + private void Check() + { + if (_selfRuntimeId != RuntimeId || IsDisposed || _session == null) + { + Stop(); + return; + } + + var timeNow = TimeHelper.Now; + Log.Debug($"timeNow:{timeNow} _session.LastReceiveTime:{_session.LastReceiveTime} {timeNow - _session.LastReceiveTime}"); + if (timeNow - _session.LastReceiveTime < _timeOut) + { + return; + } +#if FANTASY_DEBUG + Log.Warning($"session timeout id:{Id} timeNow:{timeNow} _session.LastReceiveTime:{_session.LastReceiveTime} _timeOut:{_timeOut}"); +#endif + _session.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta new file mode 100644 index 0000000..befb46f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 342372726a6897342af7f0e94b44c821 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs b/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs new file mode 100644 index 0000000..fa981ce --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs @@ -0,0 +1,188 @@ +// ReSharper disable MemberCanBePrivate.Global + +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.InnerMessage; +using Fantasy.Timer; + +#if FANTASY_UNITY + +namespace Fantasy.Network +{ + public class SessionHeartbeatComponentAwakeSystem : AwakeSystem + { + protected override void Awake(SessionHeartbeatComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } + } + + /// + /// 负责管理会话心跳的组件。 + /// + public class SessionHeartbeatComponent : Entity + { + public int TimeOut; + public long TimerId; + public long LastTime; + public long SelfRunTimeId; + public long TimeOutTimerId; + public TimerComponent TimerComponent; + public EntityReference Session; + private readonly PingRequest _pingRequest = new PingRequest(); + + // Ping滑动窗口及其累加和 + private int _pingSum; + private int _maxPingSamples; + private readonly Queue _pingSamples = new Queue(); + /// + /// 当前Ping延迟(毫秒,滑动均值) + /// + public int PingMilliseconds { get; private set; } + /// + /// 当前Ping延迟(秒,浮点数,通常用于调试) + /// + public float PingSeconds => PingMilliseconds / 1000f; + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + Stop(); + Session = null; + TimeOut = 0; + LastTime = 0; + SelfRunTimeId = 0; + base.Dispose(); + } + + /// + /// 使用指定的间隔启动心跳功能。 + /// + /// 以毫秒为单位的心跳请求发送间隔。 + /// 设置与服务器的通信超时时间,如果超过这个时间限制,将自动断开会话(Session)。 + /// 用于检测与服务器连接超时频率。 + /// Ping包的采样数量 + public void Start(int interval, int timeOut = 5000, int timeOutInterval = 3000, int maxPingSamples = 8) + { + TimeOut = timeOut + interval; + Session = (Session)Parent; + SelfRunTimeId = RuntimeId; + LastTime = TimeHelper.Now; + _maxPingSamples = maxPingSamples; + + if (TimerComponent == null) + { + Log.Error("请在Unity的菜单执行Fantasy->Generate link.xml再重新打包"); + return; + } + + TimerId = TimerComponent.Unity.RepeatedTimer(interval, () => + { + RepeatedSend().Coroutine(); + }); + TimeOutTimerId = TimerComponent.Unity.RepeatedTimer(timeOutInterval, CheckTimeOut); + } + + private void CheckTimeOut() + { + if (TimeHelper.Now - LastTime < TimeOut) + { + return; + } + + Session entityReference = Session; + + if (entityReference == null) + { + return; + } + + entityReference.Dispose(); + } + + /// + /// 停止心跳功能。 + /// + public void Stop() + { + if (TimerId != 0) + { + TimerComponent?.Unity.Remove(ref TimerId); + } + + if (TimeOutTimerId != 0) + { + TimerComponent?.Unity.Remove(ref TimeOutTimerId); + } + + _pingSum = 0; + PingMilliseconds = 0; + _pingSamples.Clear(); + } + + /// + /// 异步发送心跳请求并处理响应。 + /// + /// 表示进行中操作的异步任务。 + private async FTask RepeatedSend() + { + if (SelfRunTimeId != RuntimeId) + { + Stop(); + return; + } + + Session session = Session; + + if (session == null) + { + Dispose(); + return; + } + + try + { + var requestTime = TimeHelper.Now; + var pingResponse = (PingResponse)await session.Call(_pingRequest); + + if (pingResponse.ErrorCode != 0) + { + return; + } + + var responseTime = TimeHelper.Now; + LastTime = responseTime; + + // 计算Ping(毫秒) + var rtt = (int)(responseTime - requestTime); + var ping = rtt / 2; + + // 平滑滑动均值 + _pingSamples.Enqueue(ping); + _pingSum += ping; + if (_pingSamples.Count > _maxPingSamples) + { + _pingSum -= _pingSamples.Dequeue(); + } + + PingMilliseconds = Math.Max(0, _pingSamples.Count > 0 ? _pingSum / _pingSamples.Count : 0); + + // 校正服务器时间(可选) + TimeHelper.TimeDiff = pingResponse.Now + ping - responseTime; + } + catch (Exception) + { + Dispose(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta new file mode 100644 index 0000000..5978a0d --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b90a3bf1cc225234b8c3baebcfb8882c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession.meta b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession.meta new file mode 100644 index 0000000..0285556 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53b701461cd9de3408958ed5cccc1b30 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs new file mode 100644 index 0000000..ec7c30c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs @@ -0,0 +1,269 @@ +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using Fantasy.IdFactory; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Platform.Net; + +namespace Fantasy.Scheduler; + +internal static class ProcessScheduler +{ + public static void Scheduler(this ProcessSession session, Type messageType, uint rpcId, long routeId, APackInfo packInfo) + { + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.InnerRoamingResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + case OpCodeType.OuterRoamingResponse: + { + using (packInfo) + { + var sessionScene = session.Scene; + var message = packInfo.Deserialize(messageType); + sessionScene.ThreadSynchronizationContext.Post(() => + { + // 因为有可能是其他Scene线程下发送过来的、所以必须放到当前Scene进程下运行。 + sessionScene.NetworkMessagingComponent.ResponseHandler(rpcId, (IResponse)message); + }); + } + + return; + } + case OpCodeType.InnerRouteMessage: + { + using (packInfo) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + + return; + } + case OpCodeType.InnerRouteRequest: + { + using (packInfo) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + sceneMessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + + return; + } + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterRoamingMessage: + case OpCodeType.OuterRoamingRequest: + { + using (packInfo) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new NotSupportedException($"not found scene routeId = {routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + + if (entity == null || entity.IsDisposed) + { + scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + return; + } + default: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + packInfo.Dispose(); + throw new NotSupportedException($"SessionInnerScheduler Received unsupported message protocolCode:{packInfoProtocolCode} messageType:{messageType}"); + } + } + } + + public static void Scheduler(this ProcessSession session, Type messageType, uint rpcId, long routeId, uint protocolCode, object message) + { + OpCodeIdStruct opCodeIdStruct = protocolCode; + + switch (opCodeIdStruct.Protocol) + { + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.InnerRoamingResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + case OpCodeType.OuterRoamingResponse: + { + var sessionScene = session.Scene; + sessionScene.ThreadSynchronizationContext.Post(() => + { + var iResponse = (IResponse)session.Deserialize(messageType, message, ref opCodeIdStruct); + // 因为有可能是其他Scene线程下发送过来的、所以必须放到当前Scene进程下运行。 + sessionScene.NetworkMessagingComponent.ResponseHandler(rpcId, iResponse); + }); + + return; + } + case OpCodeType.InnerRoamingMessage: + case OpCodeType.InnerAddressableMessage: + case OpCodeType.InnerRouteMessage: + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + }); + + return; + } + case OpCodeType.InnerAddressableRequest: + case OpCodeType.InnerRoamingRequest: + case OpCodeType.InnerRouteRequest: + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + sceneMessageDispatcherComponent.FailRouteResponse(session, message.GetType(), InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + }); + + return; + } + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterRoamingMessage: + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + Log.Error($"not found scene routeId:{routeId}"); + return; + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + + switch (entity) + { + case null: + { + // 执行到这里是说明Session已经断开了 + // 因为这里是其他服务器Send到外网的数据、所以不需要给发送端返回就可以 + return; + } + case Session gateSession: + { + // 这里如果是Session只可能是Gate的Session、如果是的话、肯定是转发Address消息 + gateSession.Send((IMessage)messageObject, rpcId); + return; + } + default: + { + scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + return; + } + } + }); + + return; + } + default: + { + throw new NotSupportedException($"SessionInnerScheduler Received unsupported message protocolCode:{protocolCode} messageType:{messageType}"); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta new file mode 100644 index 0000000..2c247f5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2397363566cf0cb44b937803a7274e34 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs new file mode 100644 index 0000000..ecd0bd4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs @@ -0,0 +1,124 @@ +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Scheduler; +using Fantasy.Serialize; +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#if FANTASY_NET +namespace Fantasy.Network; + +/// +/// 网络服务器内部会话。 +/// +public sealed class ProcessSession : Session +{ + private readonly MemoryStreamBufferPool _memoryStreamBufferPool = new MemoryStreamBufferPool(); + private readonly Dictionary> _createInstances = new Dictionary>(); + + /// + /// 发送消息到服务器内部。 + /// + /// 要发送的消息。 + /// RPC 标识符。 + /// 路由标识符。 + public override void Send(IMessage message, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(message.GetType(), rpcId, routeId, message.OpCode(), message); + } + + /// + /// 发送路由消息到服务器内部。 + /// + /// 要发送的路由消息。 + /// RPC 标识符。 + /// 路由标识符。 + public override void Send(IRouteMessage routeMessage, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(routeMessage.GetType(), rpcId, routeId, routeMessage.OpCode(), routeMessage); + } + + public override void Send(uint rpcId, long routeId, Type messageType, APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(messageType, rpcId, routeId, packInfo); + } + + public override void Send(ProcessPackInfo packInfo, uint rpcId = 0, long routeId = 0) + { + this.Scheduler(packInfo.MessageType, rpcId, routeId, packInfo); + } + + public override void Send(MemoryStreamBuffer memoryStream, uint rpcId = 0, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public override FTask Call(IRouteRequest request, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public override FTask Call(IRequest request, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public object Deserialize(Type messageType, object message, ref OpCodeIdStruct opCodeIdStruct) + { + var memoryStream = _memoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.None); + + try + { + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + + if (memoryStream.Position == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.Add(messageType, createInstance); + return createInstance(); + } + + memoryStream.SetLength(memoryStream.Position); + memoryStream.Seek(0, SeekOrigin.Begin); + return serializer.Deserialize(messageType, memoryStream); + } + } + catch (Exception e) + { + Log.Error($"ProcessSession.Deserialize {e}"); + } + finally + { + _memoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + + throw new Exception($"type:{messageType} Does not support processing protocol"); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta new file mode 100644 index 0000000..f2621ef --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93744f4caa0976a4e90c812649408a2a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs new file mode 100644 index 0000000..6e3a534 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs @@ -0,0 +1,17 @@ +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network; + +internal sealed class ProcessSessionInfo(Session session, AClientNetwork aClientNetwork) : IDisposable +{ + public readonly Session Session = session; + public readonly AClientNetwork AClientNetwork = aClientNetwork; + + public void Dispose() + { + Session.Dispose(); + AClientNetwork?.Dispose(); + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta new file mode 100644 index 0000000..f08031c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a48bd7c00774fcd45b487d74ed94575a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Network/Session/Session.cs b/Runtime/CoreRuntime/Core/Network/Session/Session.cs new file mode 100644 index 0000000..fc75dea --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Session.cs @@ -0,0 +1,272 @@ +// ReSharper disable RedundantUsingDirective +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Scheduler; +using Fantasy.Serialize; +#if FANTASY_NET +using Fantasy.Network.Route; +using Fantasy.Platform.Net; +using Fantasy.Network.Roaming; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#endif +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 +#pragma warning disable CS8601 +#pragma warning disable CS8618 + +namespace Fantasy.Network +{ + /// + /// 网络会话的基类,用于管理网络通信。 + /// + public class Session : Entity, ISupportedMultiEntity + { + private uint _rpcId; + internal long LastReceiveTime; + /// + /// 关联的网络连接通道 + /// + internal INetworkChannel Channel { get; private set; } + /// + /// 当前Session的终结点信息 + /// + public IPEndPoint RemoteEndPoint { get; private set; } + private ANetworkMessageScheduler NetworkMessageScheduler { get; set;} + internal readonly Dictionary> RequestCallback = new(); + /// + /// Session的Dispose委托 + /// + internal event Action OnDispose; +#if FANTASY_NET + internal RouteComponent RouteComponent; + internal SessionRoamingComponent SessionRoamingComponent; + internal AddressableRouteComponent AddressableRouteComponent; + internal static Session Create(ANetworkMessageScheduler networkMessageScheduler, ANetworkServerChannel channel, NetworkTarget networkTarget) + { + var session = Entity.Create(channel.Scene, false, true); + session.Channel = channel; + session.NetworkMessageScheduler = networkMessageScheduler; + session.RemoteEndPoint = channel.RemoteEndPoint as IPEndPoint; + session.OnDispose = channel.Dispose; + session.LastReceiveTime = TimeHelper.Now; + // 在外部网络目标下,添加会话空闲检查组件 + if (networkTarget == NetworkTarget.Outer) + { + var interval = ProcessDefine.SessionIdleCheckerInterval; + var timeOut = ProcessDefine.SessionIdleCheckerTimeout; + session.AddComponent().Start(interval, timeOut); + } + return session; + } +#endif + internal static Session Create(AClientNetwork network, IPEndPoint remoteEndPoint) + { + // 创建会话实例 + var session = Entity.Create(network.Scene, false, true); + session.Channel = network; + session.RemoteEndPoint = remoteEndPoint; + session.OnDispose = network.Dispose; + session.NetworkMessageScheduler = network.NetworkMessageScheduler; + session.LastReceiveTime = TimeHelper.Now; + return session; + } +#if FANTASY_NET + internal static ProcessSession CreateInnerSession(Scene scene) + { + var session = Entity.Create(scene, false, false); + session.NetworkMessageScheduler = new InnerMessageScheduler(scene); + return session; + } + + /// + /// 发送一个消息,框架内部使用建议不要用这个方法。 + /// + /// 如果是RPC消息需要传递一个RPCId + /// routeId + /// 消息的类型 + /// packInfo消息包 + public virtual void Send(uint rpcId, long routeId, Type messageType, APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, packInfo.MemoryStream, null); + } + + /// + /// 发送一个消息,框架内部使用建议不要用这个方法。 + /// + /// 一个ProcessPackInfo消息包 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(ProcessPackInfo packInfo, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + using (packInfo) + { + Channel.Send(rpcId, routeId, packInfo.MemoryStream, null); + } + } + + /// + /// 发送一个消息 + /// + /// 需要发送的MemoryStreamBuffer + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(MemoryStreamBuffer memoryStream, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, memoryStream, null); + } +#endif + /// + /// 销毁一个Session,当执行了这个方法会自动断开网络的连接。 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + _rpcId = 0; + LastReceiveTime = 0; + Channel = null; + RemoteEndPoint = null; + NetworkMessageScheduler = null; +#if FANTASY_NET + SessionRoamingComponent = null; + RouteComponent = null; + AddressableRouteComponent = null; +#endif + base.Dispose(); + + // 终止所有等待中的请求回调 + foreach (var requestCallback in RequestCallback.Values.ToArray()) + { + requestCallback.SetException(new Exception($"session is dispose: {Id}")); + } + + RequestCallback.Clear(); + OnDispose?.Invoke(); + } + + /// + /// 发送一个消息 + /// + /// 消息的实例 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(IMessage message, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, null, message); + } + + /// + /// 发送一个消息 + /// + /// 消息的实例,不同的是这个是发送Route消息使用的 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(IRouteMessage routeMessage, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, null, routeMessage); + } + + /// + /// 发送一个RPC消息 + /// + /// 请求Route消息的实例 + /// routeId + /// + public virtual FTask Call(IRouteRequest request, long routeId = 0) + { + if (IsDisposed) + { + return null; + } + + var requestCallback = FTask.Create(); + var rpcId = ++_rpcId; + RequestCallback.Add(rpcId, requestCallback); + Send(request, rpcId, routeId); + return requestCallback; + } + + /// + /// 发送一个RPC消息 + /// + /// 请求消息的实例 + /// routeId + /// + public virtual FTask Call(IRequest request, long routeId = 0) + { + if (IsDisposed) + { + return null; + } + + var requestCallback = FTask.Create(); + var rpcId = ++_rpcId; + RequestCallback.Add(rpcId, requestCallback); + Send(request, rpcId, routeId); + return requestCallback; + } + + internal void Receive(APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + LastReceiveTime = TimeHelper.Now; + + try + { + NetworkMessageScheduler.Scheduler(this, packInfo).Coroutine(); + } + catch (Exception e) + { + // 如果解析失败,只有一种可能,那就是有人恶意发包。 + // 所以这里强制关闭了当前连接。不让对方一直发包。 + Dispose(); + Log.Error(e); + } + } + } +} diff --git a/Runtime/CoreRuntime/Core/Network/Session/Session.cs.meta b/Runtime/CoreRuntime/Core/Network/Session/Session.cs.meta new file mode 100644 index 0000000..038e4b0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Network/Session/Session.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb69fd94eb43ae14395cd9f79c6b6f45 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform.meta b/Runtime/CoreRuntime/Core/Platform.meta new file mode 100644 index 0000000..e64f0a2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 51dda2d70810f8348a9371443ccfadf6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Console.meta b/Runtime/CoreRuntime/Core/Platform/Console.meta new file mode 100644 index 0000000..ac4d3ab --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Console.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6f5312897e2ae6b4e8d698d2b64cbe28 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs b/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs new file mode 100644 index 0000000..c0b3aa6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs @@ -0,0 +1,101 @@ +#if FANTASY_CONSOLE +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Serialize; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Console +{ + public struct OnFantasyInit + { + public Scene Scene; + } + + /// + /// 一般的控制台启动入口,可以适用大部分客户端环境 + /// + public sealed class Entry + { + private static bool _isInit; + private static Thread _updateThread; + public static Scene Scene { get; private set; } + + /// + /// 初始化框架 + /// + /// + public static async FTask Initialize(params System.Reflection.Assembly[] assemblies) + { + if (_isInit) + { + Log.Error("Fantasy has already been initialized and does not need to be initialized again!"); + return; + } + Log.Info($"Fantasy Version:{Define.VERSION}"); + // 初始化程序集管理系统 + await AssemblySystem.InnerInitialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); + _isInit = true; + Log.Debug("Fantasy Initialize Complete!"); + } + + /// + /// 启动框架。 + /// 如果您的平台有每帧更新逻辑的方法,请不要调用这个方法。 + /// 如果没有实现每帧执行方法平台需要调用这个方法,目的是开启一个新的线程来每帧执行Update。 + /// 注意因为开启了一个新的线程来处理更新逻辑,所以要注意多线程的问题。 + /// + public static void StartUpdate() + { + _updateThread = new Thread(() => + { + while (_isInit) + { + ThreadScheduler.Update(); + Thread.Sleep(1); + } + }) + { + IsBackground = true + }; + _updateThread.Start(); + } + + /// + /// 在Entry中创建一个Scene,如果Scene已经被创建过,将先销毁Scene再创建。 + /// + /// + /// + public static async FTask CreateScene(string sceneRuntimeMode = SceneRuntimeMode.MainThread) + { + Scene?.Dispose(); + Scene = await Scene.Create(sceneRuntimeMode); + await Scene.EventComponent.PublishAsync(new OnFantasyInit() + { + Scene = Scene + }); + return Scene; + } + + /// + /// 如果有的话一定要在每帧执行这个方法 + /// + public void Update() + { + ThreadScheduler.Update(); + } + + public static void Dispose() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + Scene?.Dispose(); + Scene = null; + _isInit = false; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs.meta b/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs.meta new file mode 100644 index 0000000..65a245e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Console/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b8ef55e2be7e1414592b471ba12bae0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs b/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs new file mode 100644 index 0000000..29fd54a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs @@ -0,0 +1,38 @@ +#if FANTASY_CONSOLE +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8765 // Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes). +namespace Fantasy +{ + public sealed class ThreadSynchronizationContext : SynchronizationContext + { + private Action _actionHandler; + private readonly Queue _queue = new(); + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta b/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta new file mode 100644 index 0000000..ab5a945 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea6cb106822afc947a3ff7a4ab07c86a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Define.cs b/Runtime/CoreRuntime/Core/Platform/Define.cs new file mode 100644 index 0000000..edd96bc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Define.cs @@ -0,0 +1,7 @@ +namespace Fantasy +{ + internal static class Define + { + public const string VERSION = "Fantasy 2.0 Beta"; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Define.cs.meta b/Runtime/CoreRuntime/Core/Platform/Define.cs.meta new file mode 100644 index 0000000..9be16f0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Define.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6279c2d49dadf40cbbb5d6d1fc031a3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net.meta b/Runtime/CoreRuntime/Core/Platform/Net.meta new file mode 100644 index 0000000..05a2452 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9eeb20f6f5a96b540bab567024a9831c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable.meta b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable.meta new file mode 100644 index 0000000..1337a01 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 45f563c718b2d774396d4234a7ffd7b5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs new file mode 100644 index 0000000..e09b00e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs @@ -0,0 +1,88 @@ +#if FANTASY_NET +// ReSharper disable InconsistentNaming +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 用于记录服务器物理信息 + /// + public sealed class MachineConfigData + { + /// + /// 存放所有MachineConfigInfo信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得MachineConfig的实例 + /// + public static MachineConfigData Instance { get; private set; } + /// + /// 初始化MachineConfig + /// + /// + public static void Initialize(string machineConfigJson) + { + Instance = machineConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取MachineConfig + /// + /// + /// + /// + public MachineConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var machineConfigInfo)) + { + return machineConfigInfo; + } + + throw new FileNotFoundException($"MachineConfig not find {id} Id"); + } + /// + /// 根据Id获取MachineConfig + /// + /// + /// + /// + public bool TryGet(uint id, out MachineConfig config) + { + return _configs.TryGetValue(id, out config); + } + } + /// + /// 表示一个物理服务器的信息 + /// + public sealed class MachineConfig + { + /// + /// Id + /// + public uint Id { get; set; } + /// + /// 外网IP + /// + public string OuterIP { get; set; } + /// + /// 外网绑定IP + /// + public string OuterBindIP { get; set; } + /// + /// 内网绑定IP + /// + public string InnerBindIP { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta new file mode 100644 index 0000000..d0b8f04 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6bf19d9e68325844a0d390b87c3e1d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs new file mode 100644 index 0000000..4a400b0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs @@ -0,0 +1,100 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +// ReSharper disable CollectionNeverUpdated.Global +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Platform.Net +{ + /// + /// 用于管理进程信息 + /// + public sealed class ProcessConfigData + { + /// + /// 存放所有ProcessConfig信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得ProcessConfigData的实例 + /// + public static ProcessConfigData Instance { get; private set; } + /// + /// 初始化MachineConfig + /// + /// + public static void Initialize(string processConfigJson) + { + Instance = processConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取ProcessConfig + /// + /// + /// + /// + public ProcessConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var processConfigInfo)) + { + return processConfigInfo; + } + + throw new FileNotFoundException($"MachineConfig not find {id} Id"); + } + /// + /// 根据Id获取ProcessConfig + /// + /// + /// + /// + public bool TryGet(uint id, out ProcessConfig config) + { + return _configs.TryGetValue(id, out config); + } + /// + /// 按照startupGroup寻找属于startupGroup组的ProcessConfig + /// + /// startupGroup + /// + public IEnumerable ForEachByStartupGroup(uint startupGroup) + { + foreach (var processConfig in List) + { + if (processConfig.StartupGroup == startupGroup) + { + yield return processConfig; + } + } + } + } + /// + /// 表示一个进程配置信息 + /// + public sealed class ProcessConfig + { + /// + /// 进程Id + /// + public uint Id { get; set; } + /// + /// 机器ID + /// + public uint MachineId { get; set; } + /// + /// 启动组 + /// + public uint StartupGroup { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta new file mode 100644 index 0000000..fd6d0bd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5acaa5350b4a15b4cb660ca5a9af16d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs new file mode 100644 index 0000000..e939419 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs @@ -0,0 +1,196 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.DataStructure.Collection; +using Fantasy.DataStructure.Dictionary; +using Fantasy.Helper; +using Fantasy.IdFactory; +using Newtonsoft.Json; +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8601 // Possible null reference assignment. + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 存放所有SceneConfigInfo信息 + /// + public sealed class SceneConfigData + { + /// + /// 存放所有SceneConfig信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + [JsonIgnore] + [IgnoreDataMember] + private readonly OneToManyList _sceneConfigBySceneType = new OneToManyList(); + [JsonIgnore] + [IgnoreDataMember] + private readonly OneToManyList _sceneConfigByProcess = new OneToManyList(); + [JsonIgnore] [IgnoreDataMember] + private readonly Dictionary>> _worldSceneTypes = new Dictionary>>(); + /// + /// 获得SceneConfigData的实例 + /// + public static SceneConfigData Instance { get; private set; } + /// + /// 初始化SceneConfig + /// + /// + public static void Initialize(string sceneConfigJson) + { + Instance = sceneConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + config.Initialize(); + Instance._configs.TryAdd(config.Id, config); + Instance._sceneConfigByProcess.Add(config.ProcessConfigId, config); + Instance._sceneConfigBySceneType.Add(config.SceneType, config); + + var configWorldConfigId = (int)config.WorldConfigId; + + if (!Instance._worldSceneTypes.TryGetValue(configWorldConfigId, out var sceneConfigDic)) + { + sceneConfigDic = new Dictionary>(); + Instance._worldSceneTypes.Add(configWorldConfigId, sceneConfigDic); + } + + if (!sceneConfigDic.TryGetValue(config.SceneType, out var sceneConfigList)) + { + sceneConfigList = new List(); + sceneConfigDic.Add(config.SceneType, sceneConfigList); + } + + sceneConfigList.Add(config); + } + } + + /// + /// 根据Id获取SceneConfig + /// + /// + /// + /// + public SceneConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var sceneConfigInfo)) + { + return sceneConfigInfo; + } + + throw new FileNotFoundException($"WorldConfig not find {id} Id"); + } + + /// + /// 根据Id获取SceneConfig + /// + /// + /// + /// + public bool TryGet(uint id, out SceneConfig config) + { + return _configs.TryGetValue(id, out config); + } + + /// + /// 获得SceneConfig + /// + /// + /// + public List GetByProcess(uint serverConfigId) + { + return _sceneConfigByProcess.TryGetValue(serverConfigId, out var list) ? list : new List(); + } + + /// + /// 获得SceneConfig + /// + /// + /// + public List GetSceneBySceneType(int sceneType) + { + return !_sceneConfigBySceneType.TryGetValue(sceneType, out var list) ? new List() : list; + } + + /// + /// 获得SceneConfig + /// + /// + /// + /// + public List GetSceneBySceneType(int world, int sceneType) + { + if (!_worldSceneTypes.TryGetValue(world, out var sceneConfigDic)) + { + return new List(); + } + + if (!sceneConfigDic.TryGetValue(sceneType, out var list)) + { + return new List(); + } + + return list; + } + } + + /// + /// 表示一个Scene配置信息 + /// + public sealed class SceneConfig + { + /// + /// ID + /// + public uint Id { get; set; } + /// + /// 进程Id + /// + public uint ProcessConfigId { get; set; } + /// + /// 世界Id + /// + public uint WorldConfigId { get; set; } + /// + /// Scene运行类型 + /// + public string SceneRuntimeMode { get; set; } + /// + /// Scene类型 + /// + public string SceneTypeString { get; set; } + /// + /// 协议类型 + /// + public string NetworkProtocol { get; set; } + /// + /// 外网端口 + /// + public int OuterPort { get; set; } + /// + /// 内网端口 + /// + public int InnerPort { get; set; } + /// + /// Scene类型 + /// + public int SceneType { get; set; } + /// + /// RouteId + /// + [JsonIgnore] + [IgnoreDataMember] + public long RouteId { get; private set; } + /// + /// 初始化方法 + /// + public void Initialize() + { + RouteId = IdFactoryHelper.RuntimeId(0, Id, (byte)WorldConfigId, 0); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta new file mode 100644 index 0000000..c7812f5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6d31046187ec7f45a4151a2f2a114c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs new file mode 100644 index 0000000..9b0ede5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs @@ -0,0 +1,93 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +#pragma warning disable CS8601 // Possible null reference assignment. + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 存放所有WorldConfigInfo信息 + /// + public sealed class WorldConfigData + { + /// + /// 存放所有WorldConfigInfo信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得WorldConfig的实例 + /// + public static WorldConfigData Instance { get; private set; } + /// + /// 初始化WorldConfig + /// + /// + public static void Initialize(string worldConfigJson) + { + Instance = worldConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取WorldConfig + /// + /// + /// + /// + public WorldConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var worldConfigInfo)) + { + return worldConfigInfo; + } + + throw new FileNotFoundException($"WorldConfig not find {id} Id"); + } + /// + /// 根据Id获取WorldConfig + /// + /// + /// + /// + public bool TryGet(uint id, out WorldConfig config) + { + return _configs.TryGetValue(id, out config); + } + } + + /// + /// 表示一个世界配置信息 + /// + public sealed class WorldConfig + { + /// + /// Id + /// + public uint Id { get; set; } + /// + /// 名称 + /// + public string WorldName { get; set; } + /// + /// 数据库连接字符串 + /// + public string DbConnection { get; set; } + /// + /// 数据库名称 + /// + public string DbName { get; set; } + /// + /// 数据库类型 + /// + public string DbType { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta new file mode 100644 index 0000000..a822dfe --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b997d0bcb32ca0349bc915df003381d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs b/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs new file mode 100644 index 0000000..2bc3681 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs @@ -0,0 +1,121 @@ +#if FANTASY_NET +using CommandLine; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Serialize; +// ReSharper disable FunctionNeverReturns + +namespace Fantasy.Platform.Net; + +/// +/// Fantasy.Net 应用程序入口 +/// +/// 当命令行格式异常时抛出。 +/// 不支持的 ProcessType 类型异常。 +public static class Entry +{ + /// + /// 框架初始化 + /// + /// 注册的Assembly + public static async FTask Initialize(params System.Reflection.Assembly[] assemblies) + { + // 解析命令行参数 + Parser.Default.ParseArguments(Environment.GetCommandLineArgs()) + .WithNotParsed(error => throw new Exception("Command line format error!")) + .WithParsed(option => + { + ProcessDefine.Options = option; + ProcessDefine.InnerNetwork = Enum.Parse(option.InnerNetwork); + }); + // 初始化Log系统 + Log.Initialize(); + Log.Info($"Fantasy Version:{Define.VERSION}"); + // 检查启动参数,后期可能有机器人等不同的启动参数 + switch (ProcessDefine.Options.ProcessType) + { + case "Game": + { + break; + } + default: + { + throw new NotSupportedException($"ProcessType is {ProcessDefine.Options.ProcessType} Unrecognized!"); + } + } + // 初始化程序集管理系统 + await AssemblySystem.InnerInitialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); + // 精度处理(只针对Windows下有作用、其他系统没有这个问题、一般也不会用Windows来做服务器的) + WinPeriod.Initialize(); + } + + /// + /// 启动Fantasy.Net + /// + public static async FTask Start() + { + // 启动Process + StartProcess().Coroutine(); + await FTask.CompletedTask; + while (true) + { + ThreadScheduler.Update(); + Thread.Sleep(1); + } + } + + /// + /// 初始化并且启动框架 + /// + /// + public static async FTask Start(params System.Reflection.Assembly[] assemblies) + { + await Initialize(assemblies); + await Start(); + } + + private static async FTask StartProcess() + { + if (ProcessDefine.Options.StartupGroup != 0) + { + foreach (var processConfig in ProcessConfigData.Instance.ForEachByStartupGroup((uint)ProcessDefine.Options.StartupGroup)) + { + await Process.Create(processConfig.Id); + } + + return; + } + + switch (ProcessDefine.Options.Mode) + { + case "Develop": + { + foreach (var processConfig in ProcessConfigData.Instance.List) + { + await Process.Create(processConfig.Id); + } + + return; + } + case "Release": + { + await Process.Create(ProcessDefine.Options.ProcessId); + return; + } + } + } + + /// + /// 关闭 Fantasy + /// + public static void Close() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs.meta new file mode 100644 index 0000000..1fd40d7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09a6a4bba47003f42831a429af5348b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/Process.cs b/Runtime/CoreRuntime/Core/Platform/Net/Process.cs new file mode 100644 index 0000000..e3a6cf8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/Process.cs @@ -0,0 +1,156 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using Fantasy.Async; +using Fantasy.IdFactory; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.Platform.Net; + +/// +/// 一个进程的实例 +/// +public sealed class Process : IDisposable +{ + /// + /// 当前进程的Id + /// + public readonly uint Id; + /// + /// 进程关联的MachineId + /// + public readonly uint MachineId; + private readonly ConcurrentDictionary _processScenes = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary Scenes = new ConcurrentDictionary(); + private Process() {} + private Process(uint id, uint machineId) + { + Id = id; + MachineId = machineId; + } + + internal bool IsProcess(ref long routeId) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + return _processScenes.ContainsKey(sceneId); + } + + internal bool IsProcess(ref uint sceneId) + { + return _processScenes.ContainsKey(sceneId); + } + + internal void AddSceneToProcess(Scene scene) + { + _processScenes.TryAdd(scene.SceneConfigId, scene); + } + + internal void RemoveSceneToProcess(Scene scene, bool isDispose) + { + if (!_processScenes.Remove(scene.SceneConfigId, out _)) + { + return; + } + + if (isDispose) + { + scene.Dispose(); + } + } + + internal bool TryGetSceneToProcess(long routeId, out Scene scene) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + return _processScenes.TryGetValue(sceneId, out scene); + } + + internal bool TryGetSceneToProcess(uint sceneId, out Scene scene) + { + return _processScenes.TryGetValue(sceneId, out scene); + } + /// + /// 销毁方法 + /// + public void Dispose() + { + if (_processScenes.IsEmpty) + { + return; + } + + var sceneQueue = new Queue(); + + foreach (var (_, scene) in _processScenes) + { + sceneQueue.Enqueue(scene); + } + + while (sceneQueue.TryDequeue(out var removeScene)) + { + removeScene.Dispose(); + } + + _processScenes.Clear(); + } + + internal static async FTask Create(uint processConfigId) + { + if (!ProcessConfigData.Instance.TryGet(processConfigId, out var processConfig)) + { + Log.Error($"not found processConfig by Id:{processConfigId}"); + return null; + } + + if (!MachineConfigData.Instance.TryGet(processConfig.MachineId, out var machineConfig)) + { + Log.Error($"not found machineConfig by Id:{processConfig.MachineId}"); + return null; + } + + var process = new Process(processConfigId, processConfig.MachineId); + var sceneConfigs = SceneConfigData.Instance.GetByProcess(processConfigId); + + foreach (var sceneConfig in sceneConfigs) + { + await Scene.Create(process, machineConfig, sceneConfig); + } + + Log.Info($"Process:{processConfigId} Startup Complete SceneCount:{sceneConfigs.Count}"); + return process; + } + + internal bool IsInAppliaction(ref uint sceneId) + { + return _processScenes.ContainsKey(sceneId); + } + + internal static void AddScene(Scene scene) + { + Scenes.TryAdd(scene.SceneConfigId, scene); + } + + internal static void RemoveScene(Scene scene, bool isDispose) + { + if (!Scenes.Remove(scene.SceneConfigId, out _)) + { + return; + } + + if (isDispose) + { + scene.Dispose(); + } + } + + internal static bool TryGetScene(long routeId, out Scene scene) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref routeId); + return Scenes.TryGetValue(sceneId, out scene); + } + + internal static bool TryGetScene(uint sceneId, out Scene scene) + { + return Scenes.TryGetValue(sceneId, out scene); + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Platform/Net/Process.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/Process.cs.meta new file mode 100644 index 0000000..fd44eaf --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/Process.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39cc6d3467ecf1e449dad0c2b5ecbb43 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs b/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs new file mode 100644 index 0000000..2bcc4e0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs @@ -0,0 +1,99 @@ +#if FANTASY_NET +using CommandLine; +using Fantasy.Network; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net; + +/// +/// Process运行模式 +/// +public enum ProcessMode +{ + /// + /// 默认 + /// + None =0, + /// + /// 开发模式 + /// + Develop = 1, + /// + /// 发布模式 + /// + Release = 2 +} + +internal sealed class CommandLineOptions +{ + /// + /// 用于启动指定的进程,该进程的 ID 与 ProcessConfig 的 ID 相关联。此参数只能传递单个 ID,不支持传递多个 ID。 + /// + [Option("pid", Required = false, Default = (uint)0, HelpText = "Enter an ProcessIdId such as 1")] + public uint ProcessId { get; set; } + /// + /// Process类型,获取或设置应用程序的类型。 + /// Game - 游戏服务器Process + /// Robot - 机器人(暂未支持该功能) + /// + [Option('a', "ProcessType", Required = false, Default = "Game", HelpText = "Game")] + public string ProcessType { get; set; } + /// + /// 服务器运行模式,获取或设置服务器的运行模式。 + /// Develop - 开发模式(启动Process配置表中的所有Process) + /// Release - 发布模式(根据ProcessId启动Process) + /// + [Option('m', "Mode", Required = true, Default = "Release", HelpText = "Develop:启动Process配置表中的所有Process,\nRelease:根据ProcessId启动Process")] + public string Mode { get; set; } + /// + /// 服务器内部网络协议 + /// TCP - 服务器内部之间通讯使用TCP协议 + /// KCP - 服务器内部之间通讯使用KCP协议 + /// WebSocket - 服务器内部之间通讯使用WebSocket协议(不推荐、TCP或KCP) + /// + [Option('n', "InnerNetwork", Required = false, Default = "TCP", HelpText = "TCP、KCP、WebSocket")] + public string InnerNetwork { get; set; } + /// + /// 会话空闲检查超时时间。 + /// + [Option('t', "SessionIdleCheckerTimeout", Required = false, Default = 8000, HelpText = "Session idle check timeout")] + public int SessionIdleCheckerTimeout { get; set; } + /// + /// 会话空闲检查间隔。 + /// + [Option('i', "SessionIdleCheckerInterval", Required = false, Default = 5000, HelpText = "Session idle check interval")] + public int SessionIdleCheckerInterval { get; set; } + /// + /// 启动组。 + /// + [Option('g', "StartupGroup", Required = false, Default = 0, HelpText = "Used to start a group of Process")] + public int StartupGroup { get; set; } +} + +/// +/// AppDefine +/// +internal static class ProcessDefine +{ + /// + /// 命令行选项 + /// + public static CommandLineOptions Options; + /// + /// App程序Id + /// + public static uint ProcessId => Options.ProcessId; + /// + /// 会话空闲检查超时时间。 + /// + public static int SessionIdleCheckerTimeout => Options.SessionIdleCheckerTimeout; + /// + /// 会话空闲检查间隔。 + /// + public static int SessionIdleCheckerInterval => Options.SessionIdleCheckerInterval; + /// + /// 内部网络通讯协议类型 + /// + public static NetworkProtocolType InnerNetwork; +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs.meta new file mode 100644 index 0000000..c666170 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ProcessDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 888a80409f50faa479db198dc0586840 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs b/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs new file mode 100644 index 0000000..bb2948a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs @@ -0,0 +1,52 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +#pragma warning disable CS8765 +#pragma warning disable CS8601 +#pragma warning disable CS8618 + +namespace Fantasy; + +/// +/// 线程的同步上下文 +/// +public sealed class ThreadSynchronizationContext : SynchronizationContext +{ + private readonly ConcurrentQueue _queue = new(); + /// + /// 执行当前上下文投递过的逻辑 + /// + public void Update() + { + while (_queue.TryDequeue(out var actionHandler)) + { + try + { + actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + /// + /// 投递一个逻辑到当前上下文 + /// + /// + /// + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + /// + /// 投递一个逻辑到当前上下文 + /// + /// + public void Post(Action action) + { + _queue.Enqueue(action); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta b/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta new file mode 100644 index 0000000..0fd3bd8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 839394f31c39d874cb3dba2adec0ca8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity.meta b/Runtime/CoreRuntime/Core/Platform/Unity.meta new file mode 100644 index 0000000..3daa43e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 10822e729bcfffa4cbc52ae6b39e2dfd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs b/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs new file mode 100644 index 0000000..d9d85ae --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs @@ -0,0 +1,19 @@ +#if FANTASY_UNITY +namespace Fantasy.Platform.Unity +{ + public static class AppDefine + { + public static string RemoteUpdatePath; + public static bool EditorModel = true; + public const string VersionName = "version.bytes"; + public const string VersionMD5Name = "version.md5"; + public const string AssetBundleManifestName = "Fantasy"; + public static bool IsEditor => UnityEngine.Application.isEditor && EditorModel; + public static string AssetBundleSaveDirectory => "Assets/AssetBundles"; + public static string LocalAssetBundlePath => UnityEngine.Application.streamingAssetsPath; + public static string RemoteAssetBundlePath => UnityEngine.Application.persistentDataPath; + public static string PersistentDataVersion => $"{UnityEngine.Application.persistentDataPath}/{VersionName}"; + public static string StreamingAssetsVersion => $"{UnityEngine.Application.streamingAssetsPath}/{VersionName}"; + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs.meta new file mode 100644 index 0000000..856bf39 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/AppDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88ed5a2e4f4081e488cec0b79d2e5b7b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes.meta new file mode 100644 index 0000000..d07f8aa --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 87ef44026e43b4841ad6766272ec364b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs new file mode 100644 index 0000000..49914ec --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonDefaultValueAttribute : Attribute + { + public BsonDefaultValueAttribute(object defaultValue) { } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta new file mode 100644 index 0000000..d145f80 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98b83673ce7516e48aab99b614029a4c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs new file mode 100644 index 0000000..3892727 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs @@ -0,0 +1,13 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonElementAttribute : Attribute + { + public BsonElementAttribute() { } + + public BsonElementAttribute(string elementName) { } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta new file mode 100644 index 0000000..61db5c2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6cdf3f4e5ae992f46b95827af5598bb4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs new file mode 100644 index 0000000..48274d0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class BsonIdAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta new file mode 100644 index 0000000..f1e2fb9 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb8e373daeca15849885c1289a9e1cdf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs new file mode 100644 index 0000000..23e55c8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonIgnoreAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta new file mode 100644 index 0000000..eaa9e4c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfcf492f3a3b2be41a5d49f6af1160d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs new file mode 100644 index 0000000..82dddde --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs @@ -0,0 +1,13 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonIgnoreIfDefaultAttribute : Attribute + { + public BsonIgnoreIfDefaultAttribute() { } + + public BsonIgnoreIfDefaultAttribute(bool value) { } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta new file mode 100644 index 0000000..48438c0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 670a795b0bdb8df4db954f0ab2d9958b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs new file mode 100644 index 0000000..f330a8b --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class BsonIgnoreIfNullAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta new file mode 100644 index 0000000..bfe2615 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88600b687f0f5e947999ace2f50c32f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs new file mode 100644 index 0000000..8fb0be8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs @@ -0,0 +1,109 @@ +#if FANTASY_UNITY +using System; +using System.Linq; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Serialize; +using UnityEngine; +using UnityEngine.Scripting; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Platform.Unity +{ + public sealed class FantasyObject : MonoBehaviour + { + public static GameObject FantasyObjectGameObject { get; private set; } + + public static void OnRuntimeMethodLoad() + { + FantasyObjectGameObject = new GameObject("Fantasy.Net"); + DontDestroyOnLoad(FantasyObjectGameObject); + } + private void OnApplicationQuit() + { + Destroy(FantasyObjectGameObject); + } + } + + public struct OnSceneCreate + { + public Scene Scene; + public object Arg; + } + + public class Entry : MonoBehaviour + { + private static bool _isInit; + public static Scene Scene { get; private set; } + + /// + /// 初始化框架 + /// + /// + public static async FTask Initialize(params System.Reflection.Assembly[] assemblies) + { + if (_isInit) + { + Log.Error("Fantasy has already been initialized and does not need to be initialized again!"); + return; + } + FantasyObject.OnRuntimeMethodLoad(); + Log.Register(new UnityLog()); + Log.Info($"Fantasy Version:{Define.VERSION}"); + await AssemblySystem.InnerInitialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); +#if FANTASY_WEBGL + ThreadSynchronizationContext.Initialize(); +#endif + _isInit = true; + FantasyObject.FantasyObjectGameObject.AddComponent(); + Log.Debug("Fantasy Initialize Complete!"); + } + + /// + /// 在Entry中创建一个Scene,如果Scene已经被创建过,将先销毁Scene再创建。 + /// + /// + /// + /// + public static async FTask CreateScene(object arg = null, string sceneRuntimeMode = SceneRuntimeMode.MainThread) + { + Scene?.Dispose(); + Scene = await Scene.Create(sceneRuntimeMode); + await Scene.EventComponent.PublishAsync(new OnSceneCreate() + { + Arg = arg, + Scene = Scene + }); + return Scene; + } + + private void Update() + { + ThreadScheduler.Update(); + } + + private void LateUpdate() + { + ThreadScheduler.LateUpdate(); + } + + private void OnDestroy() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + if (Scene != null) + { + Scene?.Dispose(); + Scene = null; + } + _isInit = false; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs.meta new file mode 100644 index 0000000..ad08a6e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbaefd83a8b3a674d86f4bc0e73f5dc2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs b/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs new file mode 100644 index 0000000..399488f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs @@ -0,0 +1,108 @@ +// using System.Reflection; +// using Fantasy.Assembly; +// using Fantasy.Async; +// // using UnityEngine; +// #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// #pragma warning disable CS8603 // Possible null reference return. +// #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +// +// namespace Fantasy.Platform.Unity +// { +// public class MonoBehaviour +// { +// +// } +// +// public class GameObject +// { +// public GameObject(string name) +// { +// +// } +// } +// +// internal enum RuntimeInitializeLoadType +// { +// BeforeSceneLoad = 1, +// } +// +// internal class RuntimeInitializeOnLoadMethodAttribute : Attribute +// { +// public RuntimeInitializeLoadType RuntimeInitializeLoadType; +// +// public RuntimeInitializeOnLoadMethodAttribute(RuntimeInitializeLoadType loadType) +// { +// +// } +// } +// +// public sealed class FantasyObject : MonoBehaviour +// { +// public static GameObject FantasyObjectGameObject { get; private set; } +// // 这个方法将在游戏启动时自动调用 +// [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] +// static void OnRuntimeMethodLoad() +// { +// FantasyObjectGameObject = new GameObject("Fantasy.Net"); +// // DontDestroyOnLoad(FantasyObjectGameObject); +// } +// private void OnApplicationQuit() +// { +// // Destroy(FantasyObjectGameObject); +// } +// } +// +// public struct OnFantasyInit +// { +// public Scene Scene; +// } +// +// public class Entry : MonoBehaviour +// { +// private static bool _isInit; +// public static Scene Scene { get; private set; } +// /// +// /// 初始化框架 +// /// +// public static async FTask Initialize(params System.Reflection.Assembly[] assemblies) +// { +// Scene?.Dispose(); +// // 初始化程序集管理系统 +// AssemblySystem.Initialize(assemblies); +// if (!_isInit) +// { +// #if FANTASY_WEBGL +// ThreadSynchronizationContext.Initialize(); +// #endif +// _isInit = true; +// // FantasyObject.FantasyObjectGameObject.AddComponent(); +// } +// // Scene = await Scene.Create(SceneRuntimeType.MainThread); +// // await Scene.EventComponent.PublishAsync(new OnFantasyInit() +// // { +// // Scene = Scene +// // }); +// // return Scene; +// await FTask.CompletedTask; +// return null; +// } +// +// private void Update() +// { +// ThreadScheduler.Update(); +// } +// +// private void OnDestroy() +// { +// AssemblySystem.Dispose(); +// if (Scene != null) +// { +// Scene?.Dispose(); +// Scene = null; +// } +// _isInit = false; +// } +// } +// } diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs.meta new file mode 100644 index 0000000..dec85b8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/Temp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 47bcb29d132d2f14986de3ab4ea71e6b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs b/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs new file mode 100644 index 0000000..44b165a --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs @@ -0,0 +1,104 @@ +#if FANTASY_UNITY && !FANTASY_WEBGL +#pragma warning disable CS8765 +#pragma warning disable CS8601 +#pragma warning disable CS8618 +using System; +using System.Collections.Concurrent; +using System.Threading; + +namespace Fantasy +{ + public sealed class ThreadSynchronizationContext : SynchronizationContext + { + private Action _actionHandler; + private readonly ConcurrentQueue _queue = new(); + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } + } +} +#endif +#if FANTASY_UNITY && FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Threading; +using Fantasy; +using UnityEngine; +using Object = UnityEngine.Object; + +public class WebGLSynchronizationContextUpdater : MonoBehaviour +{ + private ThreadSynchronizationContext _context; + + public void Initialize(ThreadSynchronizationContext context) + { + _context = context; + } + + void Update() + { + _context.Update(); + } +} +public sealed class ThreadSynchronizationContext : SynchronizationContext +{ + private Action _actionHandler; + private readonly Queue _queue = new(); + + public static void Initialize() + { + var context = new ThreadSynchronizationContext(); + SetSynchronizationContext(context); + var go = new GameObject("WebGLSynchronizationContextUpdater"); + go.AddComponent().Initialize(context); + Object.DontDestroyOnLoad(go); + } + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta b/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta new file mode 100644 index 0000000..304d19f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b363271d9a7da7143ba12bfeae9ad2ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool.meta b/Runtime/CoreRuntime/Core/Pool.meta new file mode 100644 index 0000000..fa18527 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e90648bb5a13cdd4690142e7b649ff49 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Concurrent.meta b/Runtime/CoreRuntime/Core/Pool/Concurrent.meta new file mode 100644 index 0000000..ef681b3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Concurrent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 87b92340e735e944dbbb3d685e9642d7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs new file mode 100644 index 0000000..4c946d1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs @@ -0,0 +1,37 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 线程安全的静态通用对象池。 + /// + internal static class MultiThreadPool + { + private static readonly ConcurrentDictionary ObjectPools = new ConcurrentDictionary(); + + public static T Rent() where T : IPool, new() + { + return ObjectPools.GetOrAdd(typeof(T), t => new MultiThreadPoolQueue(2000, () => new T())).Rent(); + } + + public static IPool Rent(Type type) + { + return ObjectPools.GetOrAdd(type, t => new MultiThreadPoolQueue(2000, CreateInstance.CreateIPool(type))).Rent(); + } + + public static void Return(T obj) where T : IPool, new() + { + if (!obj.IsPool()) + { + return; + } + + ObjectPools.GetOrAdd(typeof(T), t => new MultiThreadPoolQueue(2000, () => new T())).Return(obj); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs.meta b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs.meta new file mode 100644 index 0000000..0e53f2c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: daa1829b53ad16946bce4b94fed9948c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs new file mode 100644 index 0000000..df15a1c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs @@ -0,0 +1,76 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Threading; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 线程安全的对象池。 + /// + internal class MultiThreadPoolQueue + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Func _createInstance; + private readonly ConcurrentQueue _poolQueue = new ConcurrentQueue(); + private MultiThreadPoolQueue() { } + + public MultiThreadPoolQueue(int maxCapacity, Func createInstance) + { + _maxCapacity = maxCapacity; + _createInstance = createInstance; + } + + public T Rent() where T : IPool, new() + { + if (!_poolQueue.TryDequeue(out var t)) + { + var pool = new T(); + pool.SetIsPool(true); + return pool; + } + + t.SetIsPool(true); + Interlocked.Decrement(ref _poolCount); + return (T)t; + } + + public IPool Rent() + { + if (!_poolQueue.TryDequeue(out var t)) + { + var instance = _createInstance(); + instance.SetIsPool(true); + return instance; + } + + t.SetIsPool(true); + Interlocked.Decrement(ref _poolCount); + return t; + } + + public void Return(IPool obj) + { + if (!obj.IsPool()) + { + return; + } + + obj.SetIsPool(false); + + if (Interlocked.Increment(ref _poolCount) <= _maxCapacity) + { + _poolQueue.Enqueue(obj); + return; + } + + Interlocked.Decrement(ref _poolCount); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta new file mode 100644 index 0000000..500aad3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b2811a12b9eb7748a6da58c9682ff4b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Interface.meta b/Runtime/CoreRuntime/Core/Pool/Interface.meta new file mode 100644 index 0000000..baf577f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b7a4d384c6ea9dc4882d2454f9493243 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs b/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs new file mode 100644 index 0000000..1775f28 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs @@ -0,0 +1,18 @@ +namespace Fantasy.Pool +{ + /// + /// 实现了这个接口代表支持对象池 + /// + public interface IPool + { + /// + /// 是否从池里创建的 + /// + bool IsPool(); + /// + /// 设置是否从池里创建的 + /// + /// + void SetIsPool(bool isPool); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs.meta b/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs.meta new file mode 100644 index 0000000..c35c715 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Interface/IPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f781f39a206e82a4c88286bfc88a9601 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Normal.meta b/Runtime/CoreRuntime/Core/Pool/Normal.meta new file mode 100644 index 0000000..1098fc8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 75d62e36b4e205a49b5e76767b927de3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs b/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs new file mode 100644 index 0000000..88006e1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable CheckNamespace + +namespace Fantasy.Pool +{ + /// + /// 静态的对象池系统,不支持多线程。 + /// + /// + public static class Pool where T : IPool, new() + { + private static readonly Queue PoolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public static int Count => PoolQueue.Count; + + /// + /// 租借 + /// + /// + public static T Rent() + { + return PoolQueue.Count == 0 ? new T() : PoolQueue.Dequeue(); + } + + /// + /// 租借 + /// + /// 如果池子里没有,会先执行这个委托。 + /// + public static T Rent(Func generator) + { + return PoolQueue.Count == 0 ? generator() : PoolQueue.Dequeue(); + } + + /// + /// 返还 + /// + /// + public static void Return(T t) + { + if (t == null) + { + return; + } + + PoolQueue.Enqueue(t); + } + + /// + /// 返还 + /// + /// 返还的东西 + /// 返还后执行的委托 + public static void Return(T t, Action reset) + { + if (t == null) + { + return; + } + + reset(t); + PoolQueue.Enqueue(t); + } + + /// + /// 清空池子 + /// + public static void Clear() + { + PoolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs.meta b/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs.meta new file mode 100644 index 0000000..64bd592 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/Pool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b557573493b4d6247afc32f66a87a758 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs b/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs new file mode 100644 index 0000000..94144f1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Fantasy.DataStructure.Collection; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 对象池抽象接口,用于创建和管理可重复使用的对象实例。 + /// + public abstract class PoolCore : IDisposable + { + private int _poolCount; + private readonly int _maxCapacity; + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + private readonly OneToManyQueue _poolQueue = new OneToManyQueue(); + private readonly Dictionary> _typeCheckCache = new Dictionary>(); + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolCore(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + /// + public T Rent() where T : IPool, new() + { + if (!_poolQueue.TryDequeue(typeof(T), out var queue)) + { + queue = new T(); + } + + queue.SetIsPool(true); + _poolCount--; + return (T)queue; + } + + /// + /// 租借 + /// + /// 租借的类型 + /// + /// + public IPool Rent(Type type) + { + if (!_poolQueue.TryDequeue(type, out var queue)) + { + if (!_typeCheckCache.TryGetValue(type, out var createInstance)) + { + if (!typeof(IPool).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{this.GetType().FullName} Type:{type.FullName} must inherit from IPool"); + } + else + { + createInstance = CreateInstance.CreateIPool(type); + _typeCheckCache[type] = createInstance; + } + } + + var instance = createInstance(); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return queue; + } + + /// + /// 返还 + /// + /// + /// + public void Return(Type type, IPool obj) + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(type, obj); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + _typeCheckCache.Clear(); + } + } + + /// + /// 泛型对象池核心类,用于创建和管理可重复使用的对象实例。 + /// + /// 要池化的对象类型 + public abstract class PoolCore where T : IPool, new() + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Queue _poolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolCore(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + public virtual T Rent() + { + T dequeue; + + if (_poolQueue.Count == 0) + { + dequeue = new T(); + } + else + { + _poolCount--; + dequeue = _poolQueue.Dequeue(); + } + + dequeue.SetIsPool(true); + return dequeue; + } + + /// + /// 返还 + /// + /// + public virtual void Return(T item) + { + if (item == null) + { + return; + } + + if (!item.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + item.SetIsPool(false); + _poolQueue.Enqueue(item); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs.meta b/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs.meta new file mode 100644 index 0000000..bc8e708 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/PoolCore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80ff78e5ea9bf304d98dbb7ed62f2177 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs b/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs new file mode 100644 index 0000000..3f97f1c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.Pool +{ + /// + /// 静态通用对象池,用于存储实现了 IDisposable 接口的对象。 + /// + /// 要存储在对象池中的对象类型,必须实现 IDisposable 接口。 + public abstract class PoolWithDisposable : IDisposable where T : IPool, IDisposable, new() + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Queue _poolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolWithDisposable(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + public T Rent() + { + T dequeue; + if (_poolQueue.Count == 0) + { + dequeue = new T(); + } + else + { + _poolCount--; + dequeue = _poolQueue.Dequeue(); + } + + dequeue.SetIsPool(true); + return dequeue; + } + + /// + /// 租借 + /// + /// + /// + public T Rent(Func generator) + { + T dequeue; + + if (_poolQueue.Count == 0) + { + dequeue = generator(); + } + else + { + _poolCount--; + dequeue = _poolQueue.Dequeue(); + } + + dequeue.SetIsPool(true); + return dequeue; + } + + /// + /// 返还 + /// + /// + public void Return(T t) + { + if (t == null) + { + return; + } + + if (!t.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + t.SetIsPool(true); + _poolQueue.Enqueue(t); + t.Dispose(); + } + + /// + /// 返还 + /// + /// + /// + public void Return(T t, Action reset) + { + if (t == null) + { + return; + } + + if (!t.IsPool()) + { + reset(t); + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + reset(t); + _poolCount++; + t.SetIsPool(false); + _poolQueue.Enqueue(t); + t.Dispose(); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs.meta b/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs.meta new file mode 100644 index 0000000..6ca762e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/Normal/PoolWithDisposable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 897d83565f8c3594d9989f61735d9b8c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs b/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs new file mode 100644 index 0000000..d9214fd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs @@ -0,0 +1,79 @@ +using System; +using System.Reflection.Emit; +using Fantasy.Serialize; + +#pragma warning disable CS8604 // Possible null reference argument. + +namespace Fantasy.Pool +{ + internal static class CreateInstance where T : IPool + { + public static Func Create { get; } + + static CreateInstance() + { + var type = typeof(T); + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + Create = (Func) dynamicMethod.CreateDelegate(typeof(Func)); + } + } + + internal static class CreateInstance + { + public static Func CreateIPool(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + public static Func CreateObject(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + public static Func CreateMessage(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + } + + // public static class CreateInstance + // { + // public static Func Create(Type type) + // { + // var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + // var il = dynamicMethod.GetILGenerator(); + // il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + // il.Emit(OpCodes.Ret); + // return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + // } + // } + + // /// + // /// 利用泛型的特性来减少反射的使用。 + // /// + // /// + // public static class PoolChecker where T : new() + // { + // public static bool IsPool { get; } + // + // static PoolChecker() + // { + // IsPool = typeof(IPool).IsAssignableFrom(typeof(T)); + // } + // } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs.meta b/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs.meta new file mode 100644 index 0000000..4172f00 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Pool/PoolHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dff0ceaebd0ded44eaaf1c3af77d3d96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene.meta b/Runtime/CoreRuntime/Core/Scene.meta new file mode 100644 index 0000000..a66d4e0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7e2ba5c904126ea4382e7da14a10c5f0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs b/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs new file mode 100644 index 0000000..f83aec7 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs @@ -0,0 +1,31 @@ +namespace Fantasy +{ + internal interface ISceneUpdate + { + void Update(); + } + + internal sealed class EmptySceneUpdate : ISceneUpdate + { + public void Update() + { + + } + } + +#if FANTASY_UNITY + internal interface ISceneLateUpdate + { + void LateUpdate(); + } + + internal sealed class EmptySceneLateUpdate : ISceneLateUpdate + { + public void LateUpdate() + { + + } + } +#endif + +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs.meta b/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs.meta new file mode 100644 index 0000000..59a25e8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/ISceneUpdate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3fc68a07f85477b4284c994b21d09410 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scene.cs b/Runtime/CoreRuntime/Core/Scene/Scene.cs new file mode 100644 index 0000000..7b58c6e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scene.cs @@ -0,0 +1,645 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Event; +using Fantasy.IdFactory; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Pool; +using Fantasy.Scheduler; +using Fantasy.Timer; +#if FANTASY_NET +using Fantasy.DataBase; +using Fantasy.Platform.Net; +using Fantasy.SingleCollection; +using System.Runtime.CompilerServices; +using Fantasy.Network.Route; +using Fantasy.Network.Roaming; +#endif +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +namespace Fantasy +{ + /// + /// 当Scene创建完成后发送的事件参数 + /// + public struct OnCreateScene + { + /// + /// 获取与事件关联的场景实体。 + /// + public readonly Scene Scene; + /// + /// 初始化一个新的 OnCreateScene 实例。 + /// + /// + public OnCreateScene(Scene scene) + { + Scene = scene; + } + } + + /// + /// 表示一个场景实体,用于创建与管理特定的游戏场景信息。 + /// + public partial class Scene : Entity + { + #region Members + /// + /// Scene的运行类型 + /// + public SceneRuntimeType SceneRuntimeType { get; protected set; } +#if FANTASY_NET + /// + /// Scene类型,对应SceneConfig的SceneType + /// + public int SceneType { get; protected set; } + /// + /// 所属的世界 + /// + public World World { get; protected set; } + /// + /// 所在的Process + /// + public Process Process { get; protected set; } + /// + /// SceneConfig的Id + /// + public uint SceneConfigId { get; protected set; } + internal ANetwork InnerNetwork { get; private set; } + internal ANetwork OuterNetwork { get; private set; } + internal SceneConfig SceneConfig => SceneConfigData.Instance.Get(SceneConfigId); + private readonly Dictionary _processSessionInfos = new Dictionary(); +#endif + /// + /// 当前Scene的上下文 + /// + public ThreadSynchronizationContext ThreadSynchronizationContext { get; internal set; } + /// + /// 当前Scene的下创建的Entity + /// + private readonly Dictionary _entities = new Dictionary(); + internal readonly Dictionary> TypeInstance = new Dictionary>(); + #endregion + + #region IdFactory + + /// + /// Entity实体Id的生成器 + /// + public IEntityIdFactory EntityIdFactory { get; protected set; } + /// + /// Entity实体RuntimeId的生成器 + /// + public IRuntimeIdFactory RuntimeIdFactory { get; protected set; } + + #endregion + + #region Pool + + internal EntityPool EntityPool; + internal EntityListPool EntityListPool; + internal EntitySortedDictionaryPool EntitySortedDictionaryPool; + + #endregion + + #region Component + + /// + /// Scene下的任务调度器系统组件 + /// + public TimerComponent TimerComponent { get; internal set; } + /// + /// Scene下的事件系统组件 + /// + public EventComponent EventComponent { get; internal set; } + /// + /// Scene下的ESC系统组件 + /// + public EntityComponent EntityComponent { get; internal set; } + /// + /// Scene下的网络消息对象池组件 + /// + public MessagePoolComponent MessagePoolComponent { get; internal set; } + /// + /// Scene下的协程锁组件 + /// + public CoroutineLockComponent CoroutineLockComponent { get; internal set; } + /// + /// Scene下的网络消息派发组件 + /// + internal MessageDispatcherComponent MessageDispatcherComponent { get; set; } +#if FANTASY_NET + /// + /// Scene下的Entity分表组件 + /// + public SingleCollectionComponent SingleCollectionComponent { get; internal set; } + /// + /// Scene下的内网消息发送组件 + /// + public NetworkMessagingComponent NetworkMessagingComponent { get; internal set; } + /// + /// Scene下的漫游终端管理组件 + /// + public TerminusComponent TerminusComponent { get; internal set; } + /// + /// Scene下的Session漫游组件 + /// + public RoamingComponent RoamingComponent { get; internal set; } +#endif + #endregion + + #region Initialize + + private async FTask Initialize() + { + EntityPool = new EntityPool(); + EntityListPool = new EntityListPool(); + EntitySortedDictionaryPool = new EntitySortedDictionaryPool(); + EntityComponent = await Create(this, false, false).Initialize(); + SceneUpdate = EntityComponent; +#if FANTASY_UNITY + SceneLateUpdate = EntityComponent; +#endif + MessagePoolComponent = Create(this,false,true); + EventComponent = await Create(this,false,true).Initialize(); + TimerComponent = Create(this, false, true).Initialize(); + CoroutineLockComponent = Create(this, false, true).Initialize(); + MessageDispatcherComponent = await Create(this, false, true).Initialize(); +#if FANTASY_NET + NetworkMessagingComponent = Create(this, false, true); + SingleCollectionComponent = await Create(this, false, true).Initialize(); + TerminusComponent = Create(this, false, true); + RoamingComponent = Create(this, false, true).Initialize(); +#endif + } + + /// + /// Scene销毁方法,执行了该方法会把当前Scene下的所有实体都销毁掉。 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + base.Dispose(); + _entities.Remove(RuntimeId); + + switch (SceneRuntimeType) + { + case SceneRuntimeType.Root: + { +#if FANTASY_NET + foreach (var (_, processSessionInfo) in _processSessionInfos.ToList()) + { + processSessionInfo.Dispose(); + } + + _processSessionInfos.Clear(); +#endif + _entities.Remove(EntityComponent.RuntimeId); + + foreach (var (runtimeId, entity) in _entities.ToList()) + { + if (runtimeId != entity.RuntimeId) + { + continue; + } + entity.Dispose(); + } + + _entities.Clear(); +#if FANTASY_UNITY + _unityWorldId--; + _unitySceneId--; +#endif + TypeInstance.Clear(); +#if FANTASY_NET + Process.RemoveScene(this, false); + Process.RemoveSceneToProcess(this, false); +#endif + EntityComponent.Dispose(); + EntityPool.Dispose(); + EntityListPool.Dispose(); + EntitySortedDictionaryPool.Dispose(); + break; + } + case SceneRuntimeType.SubScene: + { + break; + } + default: + { + Log.Error($"SceneRuntimeType: {SceneRuntimeType} The unsupported SceneRuntimeType of the Scene executed Dispose."); + break; + } + } + + SceneUpdate = null; + EntityIdFactory = null; + RuntimeIdFactory = null; + + EntityPool = null; + EntityListPool = null; + EntitySortedDictionaryPool = null; + EntityComponent = null; + TimerComponent = null; + EventComponent = null; + MessagePoolComponent = null; + CoroutineLockComponent = null; + MessageDispatcherComponent = null; +#if FANTASY_NET + World = null; + Process = null; + SceneType = 0; + SceneConfigId = 0; + SingleCollectionComponent = null; + NetworkMessagingComponent = null; + TerminusComponent = null; + RoamingComponent = null; +#elif FANTASY_UNITY + Session = null; + UnityNetwork = null; + SceneLateUpdate = null; +#endif + ThreadSynchronizationContext = null; + SceneRuntimeType = SceneRuntimeType.None; + } + + #endregion + + internal ISceneUpdate SceneUpdate { get; set; } + internal void Update() + { + try + { + SceneUpdate.Update(); + } + catch (Exception e) + { + Log.Error(e); + } + } +#if FANTASY_UNITY + internal ISceneLateUpdate SceneLateUpdate { get; set; } + internal void LateUpdate() + { + try + { + SceneLateUpdate.LateUpdate(); + } + catch (Exception e) + { + Log.Error(e); + } + } +#endif + #region Create + +#if FANTASY_UNITY || FANTASY_CONSOLE + private static uint _unitySceneId = 0; + private static byte _unityWorldId = 0; + public Session Session { get; private set; } + private AClientNetwork UnityNetwork { get; set; } + /// + /// 创建一个Unity的Scene,注意:该方法只能在主线程下使用。 + /// + /// 选择Scene的运行方式 + /// + /// + public static async FTask Create(string sceneRuntimeMode = SceneRuntimeMode.MainThread) + { + var world = ++_unityWorldId; + + if (world > byte.MaxValue - 1) + { + throw new Exception($"World ID ({world}) exceeds the maximum allowed value of 255."); + } + + var sceneId = (uint)(++_unitySceneId + world * 1000); + + if (sceneId > 255255) + { + throw new Exception($"Scene ID ({sceneId}) exceeds the maximum allowed value of 255255."); + } + + var scene = new Scene(); + scene.Scene = scene; + scene.Parent = scene; + scene.Type = typeof(Scene); + scene.SceneRuntimeType = SceneRuntimeType.Root; + scene.EntityIdFactory = IdFactoryHelper.EntityIdFactory(sceneId, world); + scene.RuntimeIdFactory = IdFactoryHelper.RuntimeIdFactory(0, sceneId, world); + scene.Id = IdFactoryHelper.EntityId(0, sceneId, world, 0); + scene.RuntimeId = IdFactoryHelper.RuntimeId(0, sceneId, world, 0); + scene.AddEntity(scene); + await SetScheduler(scene, sceneRuntimeMode); + scene.ThreadSynchronizationContext.Post(() => + { + scene.EventComponent.PublishAsync(new OnCreateScene(scene)).Coroutine(); + }); + return scene; + } + public Session Connect(string remoteAddress, NetworkProtocolType networkProtocolType, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + UnityNetwork?.Dispose(); + UnityNetwork = NetworkProtocolFactory.CreateClient(this, networkProtocolType, NetworkTarget.Outer); + Session = UnityNetwork.Connect(remoteAddress, onConnectComplete, onConnectFail, onConnectDisconnect, isHttps, connectTimeout); + return Session; + } +#endif +#if FANTASY_NET + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Scene Create(Process process, byte worldId, uint sceneConfigId) + { + var scene = new Scene(); + scene.Scene = scene; + scene.Parent = scene; + scene.Type = typeof(Scene); + scene.Process = process; + scene.SceneRuntimeType = SceneRuntimeType.Root; + scene.EntityIdFactory = IdFactoryHelper.EntityIdFactory(sceneConfigId, worldId); + scene.RuntimeIdFactory = IdFactoryHelper.RuntimeIdFactory(0,sceneConfigId, worldId); + scene.Id = IdFactoryHelper.EntityId(0, sceneConfigId, worldId, 0); + scene.RuntimeId = IdFactoryHelper.RuntimeId(0, sceneConfigId, worldId, 0); + scene.AddEntity(scene); + return scene; + } + /// + /// 创建一个新的Scene + /// + /// 所属的Process + /// 对应的MachineConfig配置文件 + /// 对应的SceneConfig配置文件 + /// 创建成功后会返回创建的Scene的实例 + public static async FTask Create(Process process, MachineConfig machineConfig, SceneConfig sceneConfig) + { + var scene = Create(process, (byte)sceneConfig.WorldConfigId, sceneConfig.Id); + scene.SceneType = sceneConfig.SceneType; + scene.SceneConfigId = sceneConfig.Id; + await SetScheduler(scene, sceneConfig.SceneRuntimeMode); + + if (sceneConfig.WorldConfigId != 0) + { + scene.World = World.Create(scene, (byte)sceneConfig.WorldConfigId); + } + + if (sceneConfig.InnerPort != 0) + { + // 创建内网网络服务器 + scene.InnerNetwork = NetworkProtocolFactory.CreateServer(scene, ProcessDefine.InnerNetwork, NetworkTarget.Inner, machineConfig.InnerBindIP, sceneConfig.InnerPort); + } + + if (sceneConfig.OuterPort != 0) + { + // 创建外网网络服务 + var networkProtocolType = Enum.Parse(sceneConfig.NetworkProtocol); + scene.OuterNetwork = NetworkProtocolFactory.CreateServer(scene, networkProtocolType, NetworkTarget.Outer, machineConfig.OuterBindIP, sceneConfig.OuterPort); + } + + Process.AddScene(scene); + process.AddSceneToProcess(scene); + + scene.ThreadSynchronizationContext.Post(() => + { + if (sceneConfig.SceneTypeString == "Addressable") + { + // 如果是AddressableScene,自动添加上AddressableManageComponent。 + scene.AddComponent(); + } + + scene.EventComponent.PublishAsync(new OnCreateScene(scene)).Coroutine(); + }); + + return scene; + } + /// + /// 在Scene下面创建一个子Scene,一般用于副本,或者一些特殊的场景。 + /// + /// 主Scene的实例 + /// SceneType,可以在SceneType里找到,例如:SceneType.Addressable + /// 子Scene创建成功后执行的委托,可以传递null + /// + public static SubScene CreateSubScene(Scene parentScene, int sceneType, Action onSubSceneComplete = null) + { + var scene = new SubScene(); + scene.Scene = scene; + scene.Parent = scene; + scene.RootScene = parentScene; + scene.Type = typeof(SubScene); + scene.SceneType = sceneType; + scene.World = parentScene.World; + scene.Process = parentScene.Process; + scene.SceneRuntimeType = SceneRuntimeType.SubScene; + scene.EntityIdFactory = parentScene.EntityIdFactory; + scene.RuntimeIdFactory = parentScene.RuntimeIdFactory; + scene.Id = scene.EntityIdFactory.Create; + scene.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(scene); + scene.Initialize(parentScene); + scene.ThreadSynchronizationContext.Post(() => OnEvent().Coroutine()); + return scene; + async FTask OnEvent() + { + await scene.EventComponent.PublishAsync(new OnCreateScene(scene)); + onSubSceneComplete?.Invoke(scene, parentScene); + } + } +#endif + private static async FTask SetScheduler(Scene scene, string sceneRuntimeMode) + { + switch (sceneRuntimeMode) + { + case "MainThread": + { + scene.ThreadSynchronizationContext = ThreadScheduler.MainScheduler.ThreadSynchronizationContext; + scene.SceneUpdate = new EmptySceneUpdate(); +#if FANTASY_UNITY + scene.SceneLateUpdate = new EmptySceneLateUpdate(); +#endif + ThreadScheduler.AddMainScheduler(scene); + await scene.Initialize(); + break; + } + case "MultiThread": + { +#if !FANTASY_WEBGL + scene.ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#endif + scene.SceneUpdate = new EmptySceneUpdate(); +#if FANTASY_UNITY + scene.SceneLateUpdate = new EmptySceneLateUpdate(); +#endif + ThreadScheduler.AddToMultiThreadScheduler(scene); + await scene.Initialize(); + break; + } + case "ThreadPool": + { +#if !FANTASY_WEBGL + scene.ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#endif + scene.SceneUpdate = new EmptySceneUpdate(); +#if FANTASY_UNITY + scene.SceneLateUpdate = new EmptySceneLateUpdate(); +#endif + ThreadScheduler.AddToThreadPoolScheduler(scene); + await scene.Initialize(); + break; + } + } + } + #endregion + + #region Entities + + /// + /// 添加一个实体到当前Scene下 + /// + /// 实体实例 + public virtual void AddEntity(Entity entity) + { + _entities.Add(entity.RuntimeId, entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 返回的实体 + public virtual Entity GetEntity(long runTimeId) + { + return _entities.TryGetValue(runTimeId, out var entity) ? entity : null; + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 返回一个bool值来提示是否查找到这个实体 + public virtual bool TryGetEntity(long runTimeId, out Entity entity) + { + return _entities.TryGetValue(runTimeId, out entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 要查询实体的泛型类型 + /// 返回的实体 + public virtual T GetEntity(long runTimeId) where T : Entity + { + return _entities.TryGetValue(runTimeId, out var entity) ? (T)entity : null; + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 要查询实体的泛型类型 + /// 返回一个bool值来提示是否查找到这个实体 + public virtual bool TryGetEntity(long runTimeId, out T entity) where T : Entity + { + if (_entities.TryGetValue(runTimeId, out var getEntity)) + { + entity = (T)getEntity; + return true; + } + + entity = null; + return false; + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体的RunTimeId + /// 返回一个bool值来提示是否删除了这个实体 + public virtual bool RemoveEntity(long runTimeId) + { + return _entities.Remove(runTimeId); + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体实例 + /// 返回一个bool值来提示是否删除了这个实体 + public virtual bool RemoveEntity(Entity entity) + { + return _entities.Remove(entity.RuntimeId); + } + + #endregion + + #region InnerSession + +#if FANTASY_NET + /// + /// 根据runTimeId获得Session + /// + /// + /// + /// + internal virtual Session GetSession(long runTimeId) + { + var sceneId = IdFactoryHelper.RuntimeIdTool.GetSceneId(ref runTimeId); + + if (_processSessionInfos.TryGetValue(sceneId, out var processSessionInfo)) + { + if (!processSessionInfo.Session.IsDisposed) + { + return processSessionInfo.Session; + } + + _processSessionInfos.Remove(sceneId); + } + + if (Process.IsInAppliaction(ref sceneId)) + { + // 如果在同一个Process下,不需要通过Socket发送了,直接通过Process下转发。 + var processSession = Session.CreateInnerSession(Scene); + _processSessionInfos.Add(sceneId, new ProcessSessionInfo(processSession, null)); + return processSession; + } + + if (!SceneConfigData.Instance.TryGet(sceneId, out var sceneConfig)) + { + throw new Exception($"The scene with sceneId {sceneId} was not found in the configuration file"); + } + + if (!ProcessConfigData.Instance.TryGet(sceneConfig.ProcessConfigId, out var processConfig)) + { + throw new Exception($"The process with processId {sceneConfig.ProcessConfigId} was not found in the configuration file"); + } + + if (!MachineConfigData.Instance.TryGet(processConfig.MachineId, out var machineConfig)) + { + throw new Exception($"The machine with machineId {processConfig.MachineId} was not found in the configuration file"); + } + + var remoteAddress = $"{machineConfig.InnerBindIP}:{sceneConfig.InnerPort}"; + var client = NetworkProtocolFactory.CreateClient(Scene, ProcessDefine.InnerNetwork, NetworkTarget.Inner); + var session = client.Connect(remoteAddress, null, () => + { + Log.Error($"Unable to connect to the target server sourceServerId:{Scene.Process.Id} targetServerId:{sceneConfig.ProcessConfigId}"); + }, null, false); + _processSessionInfos.Add(sceneId, new ProcessSessionInfo(session, client)); + return session; + } +#endif + #endregion + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/Scene.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scene.cs.meta new file mode 100644 index 0000000..3b5ed78 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 329e4c874e7d0934d8a2a4ec23ea9d59 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs new file mode 100644 index 0000000..60dbc85 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs @@ -0,0 +1,21 @@ +namespace Fantasy +{ + /// + /// Scene的运行类型 + /// + public class SceneRuntimeMode + { + /// + /// Scene在主线程中运行. + /// + public const string MainThread = "MainThread"; + /// + /// Scene在一个独立的线程中运行. + /// + public const string MultiThread = "MultiThread"; + /// + /// Scene在一个根据当前CPU核心数创建的线程池中运行. + /// + public const string ThreadPool = "ThreadPool"; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs.meta b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs.meta new file mode 100644 index 0000000..7c08ef3 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e28c3ddb8abe62442abcff2a1d381d44 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs new file mode 100644 index 0000000..664107f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs @@ -0,0 +1,21 @@ +namespace Fantasy +{ + /// + /// 代表一个Scene的类型 + /// + public enum SceneRuntimeType + { + /// + /// 默认 + /// + None = 0, + /// + /// 代表一个普通的Scene,一个普通的Scene肯定是是Root的 + /// + Root = 1, + /// + /// 代表一个子场景,子场景肯定是有父场景的 + /// + SubScene = 2, + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs.meta b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs.meta new file mode 100644 index 0000000..35c5f21 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SceneRuntimeType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69274c1f770425f478d0c536e5c366ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler.meta new file mode 100644 index 0000000..6334cb8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 43880feec6c54c04da26424d7baae7f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs b/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs new file mode 100644 index 0000000..c04cc30 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs @@ -0,0 +1,11 @@ +using System; + +namespace Fantasy +{ + internal interface ISceneScheduler : IDisposable + { + void Add(Scene scene); + void Remove(Scene scene); + void Update(); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs.meta new file mode 100644 index 0000000..bb12dc8 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ISceneScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f82845b857bf694cbf27b874d7f2e17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs b/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs new file mode 100644 index 0000000..b9b1019 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs @@ -0,0 +1,105 @@ +using System.Collections.Generic; +#if FANTASY_UNITY || FANTASY_NET || !FANTASY_WEBGL +using System.Threading; +#endif +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif +namespace Fantasy +{ + internal sealed class MainScheduler : ISceneScheduler + { + private readonly Queue _queue = new Queue(); + public readonly ThreadSynchronizationContext ThreadSynchronizationContext; + + public MainScheduler() + { + ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#if !FANTASY_WEBGL + SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext); +#endif + } + public void Dispose() + { + _queue.Clear(); + } + + public void Add(Scene scene) + { + ThreadSynchronizationContext.Post(() => + { + if (scene.IsDisposed) + { + return; + } + + _queue.Enqueue(scene); + }); + } + + public void Remove(Scene scene) + { + ThreadSynchronizationContext.Post(() => + { + if (scene.IsDisposed) + { + return; + } + + var initialCount = _queue.Count; + for (var i = 0; i < initialCount; i++) + { + var currentScene = _queue.Dequeue(); + if (currentScene != scene) + { + _queue.Enqueue(currentScene); + } + } + }); + } + + public void Update() + { + ThreadSynchronizationContext.Update(); + var initialCount = _queue.Count; + + while (initialCount-- > 0) + { + if(!_queue.TryDequeue(out var scene)) + { + continue; + } + + if (scene.IsDisposed) + { + continue; + } + + scene.Update(); + _queue.Enqueue(scene); + } + } +#if FANTASY_UNITY + public void LateUpdate() + { + var initialCount = _queue.Count; + + while (initialCount-- > 0) + { + if(!_queue.TryDequeue(out var scene)) + { + continue; + } + + if (scene.IsDisposed) + { + continue; + } + + scene.LateUpdate(); + _queue.Enqueue(scene); + } + } +#endif + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs.meta new file mode 100644 index 0000000..bed17d4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/MainScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3082089ca17f2ac40ad05766feb5ab7c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs b/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs new file mode 100644 index 0000000..28f2d42 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs @@ -0,0 +1,103 @@ +#if !FANTASY_WEBGL || !FANTASY_SINGLETHREAD +using System; +using System.Collections.Concurrent; +using System.Threading; +namespace Fantasy +{ + internal struct MultiThreadStruct : IDisposable + { + public readonly Thread Thread; + public readonly CancellationTokenSource Cts; + + public MultiThreadStruct(Thread thread, CancellationTokenSource cts) + { + Thread = thread; + Cts = cts; + } + + public void Dispose() + { + Cts.Cancel(); + if (Thread.IsAlive) + { + Thread.Join(); + } + Cts.Dispose(); + } + } + + internal sealed class MultiThreadScheduler : ISceneScheduler + { + private bool _isDisposed; + private readonly ConcurrentDictionary _threads = new ConcurrentDictionary(); + public int ThreadCount => _threads.Count; + + public void Dispose() + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + + foreach (var (_, multiThreadStruct) in _threads.ToArray()) + { + multiThreadStruct.Dispose(); + } + + _threads.Clear(); + } + + public void Add(Scene scene) + { + var cts = new CancellationTokenSource(); + var thread = new Thread(() => Loop(scene, cts.Token)); + _threads.TryAdd(scene.RuntimeId, new MultiThreadStruct(thread, cts)); + thread.Start(); + } + + public void Remove(Scene scene) + { + if (_threads.TryRemove(scene.RuntimeId, out var multiThreadStruct)) + { + multiThreadStruct.Dispose(); + } + } + + public void Update() + { + throw new NotImplementedException(); + } + + private void Loop(Scene scene, CancellationToken cancellationToken) + { + var sceneThreadSynchronizationContext = scene.ThreadSynchronizationContext; + SynchronizationContext.SetSynchronizationContext(sceneThreadSynchronizationContext); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + if (scene.IsDisposed) + { + Remove(scene); + return; + } + + sceneThreadSynchronizationContext.Update(); + scene.Update(); + } + catch (Exception e) + { + Log.Error($"Error in MultiThreadScheduler loop: {e.Message}"); + } + finally + { + Thread.Sleep(1); + } + } + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta new file mode 100644 index 0000000..c8b3c9f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6a2024c609ed77469996ea6f1620052 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs new file mode 100644 index 0000000..d8353f5 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs @@ -0,0 +1,138 @@ +#if !FANTASY_WEBGL || !FANTASY_SINGLETHREAD +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8604 // Possible null reference argument. +namespace Fantasy +{ + internal sealed class ThreadPoolScheduler : ISceneScheduler + { + private bool _isDisposed; + private readonly List _threads; + private readonly ConcurrentQueue _queue = new ConcurrentQueue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public ThreadPoolScheduler() + { + // 最大线程数、避免线程过多发生的资源抢占问题。 + // 但如果使用了MultiThreadScheduler,那么这里的线程数就算是设置了也有可能导致线程过多的问题。 + // 线程过多看每个线程的抢占情况,如果抢占资源占用不是很大也没什么大问题。如果过大的情况,就会有性能问题。 + // 所以根据情况来使用不同的调度器。 + var maxThreadCount = Environment.ProcessorCount; + _threads = new List(maxThreadCount); + + for (var i = 0; i < maxThreadCount; ++i) + { + Thread thread = new(() => Loop(_cancellationTokenSource.Token)) + { + IsBackground = true + }; + _threads.Add(thread); + thread.Start(); + } + } + + public void Dispose() + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + _cancellationTokenSource.Cancel(); + + foreach (var thread in _threads) + { + if (thread.IsAlive) + { + thread.Join(); + } + } + + _cancellationTokenSource.Dispose(); + _threads.Clear(); + } + + public void Add(Scene scene) + { + if (_isDisposed) + { + return; + } + + _queue.Enqueue(scene); + } + + public void Remove(Scene scene) + { + if (_isDisposed) + { + return; + } + + var newQueue = new Queue(); + + while (_queue.TryDequeue(out var currentScene)) + { + if (currentScene == scene) + { + continue; + } + newQueue.Enqueue(currentScene); + } + + while (newQueue.TryDequeue(out var newScene)) + { + _queue.Enqueue(newScene); + } + } + + public void Update() + { + throw new NotImplementedException(); + } + + private void Loop(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + if (_queue.TryDequeue(out var scene)) + { + if (scene == null || scene.IsDisposed) + { + continue; + } + + var sceneThreadSynchronizationContext = scene.ThreadSynchronizationContext; + SynchronizationContext.SetSynchronizationContext(sceneThreadSynchronizationContext); + + try + { + sceneThreadSynchronizationContext.Update(); + scene.Update(); + } + catch (Exception e) + { + Log.Error($"Error in ThreadPoolScheduler scene: {e.Message}"); + } + finally + { + SynchronizationContext.SetSynchronizationContext(null); + } + // 先停止线程后再如队列,避免同一个Scene多次重复执行 + Thread.Sleep(1); + _queue.Enqueue(scene); + } + else + { + // 当队列为空的时候、避免无效循环消耗CPU。 + Thread.Sleep(10); + } + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta new file mode 100644 index 0000000..e332af6 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41ff4e0fcd94ed24ab5191278dfecaab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs new file mode 100644 index 0000000..9610581 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs @@ -0,0 +1,73 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy +{ + /// + /// 线程调度器 + /// + internal static class ThreadScheduler + { + /// + /// 主线程调度器 + /// + public static MainScheduler MainScheduler { get; private set; } + /// + /// 多线程调度器,根据当前CPU核心数量创建的固定线程。 + /// + public static ISceneScheduler MultiThreadScheduler { get; private set; } + /// + /// 线程池调度器 + /// + public static ISceneScheduler ThreadPoolScheduler { get; private set; } + + static ThreadScheduler() + { + MainScheduler = new MainScheduler(); + } + + internal static void Update() + { + MainScheduler.Update(); + } + +#if FANTASY_UNITY + internal static void LateUpdate() + { + MainScheduler.LateUpdate(); + } +#endif + + internal static void AddMainScheduler(Scene scene) + { + MainScheduler.Add(scene); + } + + internal static void AddToMultiThreadScheduler(Scene scene) + { + if (MultiThreadScheduler == null) + { +#if FANTASY_SINGLETHREAD || FANTASY_WEBGL + MultiThreadScheduler = MainScheduler; +#else + MultiThreadScheduler = new MultiThreadScheduler(); +#endif + } + + MultiThreadScheduler.Add(scene); + } + + internal static void AddToThreadPoolScheduler(Scene scene) + { + if (ThreadPoolScheduler == null) + { +#if FANTASY_SINGLETHREAD || FANTASY_WEBGL + ThreadPoolScheduler = MainScheduler; +#else + ThreadPoolScheduler = new ThreadPoolScheduler(); +#endif + } + + ThreadPoolScheduler.Add(scene); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs.meta b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs.meta new file mode 100644 index 0000000..869fdf1 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/Scheduler/ThreadScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0d6b896cd4b37d04090d2cc6204a0c4f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Scene/SubScene.cs b/Runtime/CoreRuntime/Core/Scene/SubScene.cs new file mode 100644 index 0000000..a8c2e73 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SubScene.cs @@ -0,0 +1,174 @@ +using System.Collections.Generic; +using System.Linq; +using Fantasy.Entitas; +using Fantasy.Network; +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +namespace Fantasy +{ + /// + /// 代表一个Scene下的子Scene + /// + public sealed partial class SubScene : Scene + { + /// + /// 子Scene的根Scene + /// + public Scene RootScene { get; internal set; } + /// + /// 存储当前Scene下管理的实体。 + /// + private readonly Dictionary _entities = new Dictionary(); + + internal void Initialize(Scene rootScene) + { + EntityPool = rootScene.EntityPool; + EntityListPool = rootScene.EntityListPool; + EntitySortedDictionaryPool = rootScene.EntitySortedDictionaryPool; + SceneUpdate = rootScene.SceneUpdate; +#if FANTASY_UNITY + SceneLateUpdate = rootScene.SceneLateUpdate; +#endif + TimerComponent = rootScene.TimerComponent; + EventComponent = rootScene.EventComponent; + EntityComponent = rootScene.EntityComponent; + MessagePoolComponent = rootScene.MessagePoolComponent; + CoroutineLockComponent = rootScene.CoroutineLockComponent; + MessageDispatcherComponent = rootScene.MessageDispatcherComponent; +#if FANTASY_NET + NetworkMessagingComponent = rootScene.NetworkMessagingComponent; + SingleCollectionComponent = rootScene.SingleCollectionComponent; + TerminusComponent = rootScene.TerminusComponent; +#endif + ThreadSynchronizationContext = rootScene.ThreadSynchronizationContext; + } + + /// + /// 当子Scene销毁时执行 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + ThreadSynchronizationContext.Post(() => + { + if (IsDisposed) + { + return; + } + + foreach (var (runtimeId, entity) in _entities.ToList()) + { + if (runtimeId != entity.RuntimeId) + { + continue; + } + entity.Dispose(); + } + + _entities.Clear(); + base.Dispose(); + }); + } + + /// + /// 添加一个实体到当前Scene下 + /// + /// 实体实例 + public override void AddEntity(Entity entity) + { + _entities.Add(entity.RuntimeId, entity); + RootScene.AddEntity(entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 返回的实体 + public override Entity GetEntity(long runTimeId) + { + return _entities.GetValueOrDefault(runTimeId); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 返回一个bool值来提示是否查找到这个实体 + public override bool TryGetEntity(long runTimeId, out Entity entity) + { + return _entities.TryGetValue(runTimeId, out entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 要查询实体的泛型类型 + /// 返回的实体 + public override T GetEntity(long runTimeId) + { + return _entities.TryGetValue(runTimeId, out var entity) ? (T)entity : null; + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 要查询实体的泛型类型 + /// 返回一个bool值来提示是否查找到这个实体 + public override bool TryGetEntity(long runTimeId, out T entity) + { + if (_entities.TryGetValue(runTimeId, out var getEntity)) + { + entity = (T)getEntity; + return true; + } + + entity = null; + return false; + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体的RunTimeId + /// 返回一个bool值来提示是否删除了这个实体 + public override bool RemoveEntity(long runTimeId) + { + return _entities.Remove(runTimeId) && RootScene.RemoveEntity(runTimeId); + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体实例 + /// 返回一个bool值来提示是否删除了这个实体 + public override bool RemoveEntity(Entity entity) + { + return RemoveEntity(entity.RuntimeId); + } + +#if FANTASY_NET + /// + /// 根据runTimeId获得Session + /// + /// + /// + /// + internal override Session GetSession(long runTimeId) + { + return RootScene.GetSession(runTimeId); + } + #endif + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Scene/SubScene.cs.meta b/Runtime/CoreRuntime/Core/Scene/SubScene.cs.meta new file mode 100644 index 0000000..ab2d9cc --- /dev/null +++ b/Runtime/CoreRuntime/Core/Scene/SubScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c4911fd1fcf6c9409a120381ff51be9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize.meta b/Runtime/CoreRuntime/Core/Serialize.meta new file mode 100644 index 0000000..c11b09e --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c0541e975f1bf054090b58ad10be60f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack.meta b/Runtime/CoreRuntime/Core/Serialize/BsonPack.meta new file mode 100644 index 0000000..906bdb4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4528d473e6f4b6647bea2eb1878b9f66 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs new file mode 100644 index 0000000..cf97a8c --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs @@ -0,0 +1,311 @@ +#if FANTASY_NET +using System.Buffers; +using System.Collections; +using System.ComponentModel; +using System.Reflection; +using Fantasy.Assembly; +using Fantasy.Entitas; +using MongoDB.Bson; +using MongoDB.Bson.IO; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Conventions; +using MongoDB.Bson.Serialization.Serializers; +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +namespace Fantasy.Serialize +{ + /// + /// BSON帮助方法 + /// + public class BsonPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "Bson"; + + /// + /// 构造函数 + /// + public BsonPackHelper() + { + // 清除掉注册过的LookupClassMap。 + + var classMapRegistryField = typeof(BsonClassMap).GetField("__classMaps", BindingFlags.Static | BindingFlags.NonPublic); + + if (classMapRegistryField != null) + { + ((Dictionary)classMapRegistryField.GetValue(null)).Clear(); + } + + // 清除掉注册过的ConventionRegistry。 + + var registryField = typeof(ConventionRegistry).GetField("_lookup", BindingFlags.Static | BindingFlags.NonPublic); + + if (registryField != null) + { + var registry = registryField.GetValue(null); + var dictionaryField = registry.GetType().GetField("_conventions", BindingFlags.Instance | BindingFlags.NonPublic); + if (dictionaryField != null) + { + ((IDictionary)dictionaryField.GetValue(registry)).Clear(); + } + } + + // 初始化ConventionRegistry、注册IgnoreExtraElements。 + + ConventionRegistry.Register("IgnoreExtraElements", new ConventionPack { new IgnoreExtraElementsConvention(true) }, type => true); + + // 注册一个自定义的序列化器。 + + // BsonSerializer.TryRegisterSerializer(typeof(float2), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(float3), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(float4), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(quaternion), new StructBsonSerialize()); + BsonSerializer.RegisterSerializer(new ObjectSerializer(x => true)); + + // 注册LookupClassMap。 + + foreach (var type in AssemblySystem.ForEach()) + { + if (type.IsInterface || type.IsAbstract || type.IsGenericType || !typeof(Entity).IsAssignableFrom(type)) + { + continue; + } + + BsonClassMap.LookupClassMap(type); + } + } + + /// + /// 反序列化 + /// + /// + /// + /// + public T Deserialize(byte[] bytes) + { + var @object = BsonSerializer.Deserialize(bytes); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = BsonSerializer.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes) + { + var @object = BsonSerializer.Deserialize(bytes, type); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = BsonSerializer.Deserialize(buffer, type); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes, int index, int count) + { + T @object; + + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + @object = BsonSerializer.Deserialize(stream); + } + + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes, int index, int count) + { + object @object; + + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + @object = BsonSerializer.Deserialize(stream, type); + } + + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + + /// + /// 序列化 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, @object); + } + + /// + /// 序列化 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, @object.GetType(), @object); + } + + /// + /// 序列化 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, type, @object); + } + + /// + /// 序列化并返回的长度 + /// + /// + /// + /// + /// + public int SerializeAndReturnLength(Type type, object @object, MemoryStreamBuffer buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = new BsonBinaryWriter(buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, type, @object); + return (int)buffer.Length; + } + + /// + /// 序列化 + /// + /// + /// + public byte[] Serialize(object @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + return @object.ToBson(@object.GetType()); + } + + /// + /// 序列化 + /// + /// + /// + /// + public byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + return @object.ToBson(); + } + + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs.meta b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs.meta new file mode 100644 index 0000000..1305f93 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperNet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 92eba2e3f8c543640b63311ee7f7d155 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs new file mode 100644 index 0000000..bfcc95f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs @@ -0,0 +1,70 @@ +#if FANTASY_UNITY +using System; +using System.Buffers; +namespace Fantasy.Serialize +{ + public class BsonPackHelper : ISerialize + { + public string SerializeName { get; } = "Bson"; + public T Deserialize(byte[] bytes) + { + throw new NotImplementedException(); + } + + public T Deserialize(MemoryStreamBuffer buffer) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, byte[] bytes) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + throw new NotImplementedException(); + } + + public T Deserialize(byte[] bytes, int index, int count) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, byte[] bytes, int index, int count) + { + throw new NotImplementedException(); + } + + public byte[] Serialize(object obj) + { + throw new NotImplementedException(); + } + + public byte[] Serialize(T @object) + { + throw new NotImplementedException(); + } + + public void Serialize(T @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public void Serialize(object @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public T Clone(T t) + { + throw new NotImplementedException(); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs.meta b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs.meta new file mode 100644 index 0000000..c21631f --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/BsonPackHelperUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 23d9c857ec148674fb9a64fd9b0a3e31 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs b/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs new file mode 100644 index 0000000..15d8663 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs @@ -0,0 +1,65 @@ +#if FANTASY_NET +using System.Reflection; +using MongoDB.Bson; +using MongoDB.Bson.IO; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Serializers; + +namespace Fantasy.Serialize; + +/// +/// 提供对结构体类型进行 BSON 序列化和反序列化的辅助类。 +/// +/// 要序列化和反序列化的结构体类型。 +public class StructBsonSerialize : StructSerializerBase where TValue : struct +{ + /// + /// 将结构体对象序列化为 BSON 数据。 + /// + /// 序列化上下文。 + /// 序列化参数。 + /// 要序列化的结构体对象。 + public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) + { + var nominalType = args.NominalType; + var bsonWriter = context.Writer; + bsonWriter.WriteStartDocument(); + var fields = nominalType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (var field in fields) + { + bsonWriter.WriteName(field.Name); + BsonSerializer.Serialize(bsonWriter, field.FieldType, field.GetValue(value)); + } + bsonWriter.WriteEndDocument(); + } + + /// + /// 将 BSON 数据反序列化为结构体对象。 + /// + /// 反序列化上下文。 + /// 反序列化参数。 + /// 反序列化得到的结构体对象。 + public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) + { + //boxing is required for SetValue to work + object obj = new TValue(); + var actualType = args.NominalType; + var bsonReader = context.Reader; + bsonReader.ReadStartDocument(); + while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) + { + var name = bsonReader.ReadName(Utf8NameDecoder.Instance); + + var field = actualType.GetField(name, + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (field != null) + { + var value = BsonSerializer.Deserialize(bsonReader, field.FieldType); + field.SetValue(obj, value); + } + } + bsonReader.ReadEndDocument(); + return (TValue) obj; + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta b/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta new file mode 100644 index 0000000..9e00dff --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87edf0cf36718b14bb286e0a99a215d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs b/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs new file mode 100644 index 0000000..82c6829 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs @@ -0,0 +1,17 @@ +#if FANTASY_NET +using System.ComponentModel; +using Fantasy.Entitas; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Serialize; + +public static class SupportInitializeChecker where T : Entity +{ + public static bool IsSupported { get; } + + static SupportInitializeChecker() + { + IsSupported = typeof(ISupportInitialize).IsAssignableFrom(typeof(T)); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta b/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta new file mode 100644 index 0000000..6dc4113 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e0105926bdcf64b41944f107976574ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/Interface.meta b/Runtime/CoreRuntime/Core/Serialize/Interface.meta new file mode 100644 index 0000000..82be633 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 721c17140dcedda40b0ae3209bdec833 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs b/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs new file mode 100644 index 0000000..7487b86 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs @@ -0,0 +1,60 @@ +using System; +using System.ComponentModel; +using System.Runtime.Serialization; +using Fantasy.Pool; +#if FANTASY_NET || FANTASY_UNITY || FANTASY_CONSOLE +using MongoDB.Bson.Serialization.Attributes; +#endif +using Newtonsoft.Json; +using ProtoBuf; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Serialize +{ + public abstract class ASerialize : ISupportInitialize, IDisposable + { + public virtual void Dispose() { } + public virtual void BeginInit() { } + public virtual void EndInit() { } + public virtual void AfterDeserialization() => EndInit(); + } + + public abstract class AMessage : ASerialize, IPool + { +#if FANTASY_NET || FANTASY_UNITY || FANTASY_CONSOLE + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + private Scene _scene; + protected Scene GetScene() + { + return _scene; + } + + public void SetScene(Scene scene) + { + _scene = scene; + } +#endif +#if FANTASY_NET + [BsonIgnore] +#endif + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + private bool _isPool; + + public bool IsPool() + { + return _isPool; + } + + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs.meta b/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs.meta new file mode 100644 index 0000000..0402f95 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/Interface/ASerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d6b0751b86964c48962eccbfa2fa36c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs b/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs new file mode 100644 index 0000000..3152f53 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs @@ -0,0 +1,100 @@ +using System; +using System.Buffers; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Serialize +{ + public interface ISerialize + { + /// + /// 序列化器的名字,用于在协议里指定用什么协议序列化使用 + /// + string SerializeName { get; } + /// + /// 反序列化 + /// + /// + /// + /// + T Deserialize(byte[] bytes); + /// + /// 反序列化 + /// + /// + /// + /// + T Deserialize(MemoryStreamBuffer buffer); + /// + /// 反序列化 + /// + /// + /// + /// + object Deserialize(Type type, byte[] bytes); + /// + /// 反序列化 + /// + /// + /// + /// + object Deserialize(Type type, MemoryStreamBuffer buffer); + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + T Deserialize(byte[] bytes, int index, int count); + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + object Deserialize(Type type, byte[] bytes, int index, int count); + /// + /// 序列化 + /// + /// + /// + byte[] Serialize(object obj); + /// + /// 序列化 + /// + /// + /// + /// + byte[] Serialize(T @object); + /// + /// 序列化 + /// + /// + /// + /// + void Serialize(T @object, IBufferWriter buffer); + /// + /// 序列化 + /// + /// + /// + void Serialize(object @object, IBufferWriter buffer); + /// + /// 序列化 + /// + /// + /// + /// + void Serialize(Type type, object @object, IBufferWriter buffer); + /// + /// 克隆 + /// + /// + /// + /// + T Clone(T t); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs.meta b/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs.meta new file mode 100644 index 0000000..15a74c0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/Interface/ISerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6296b60af794c64e8eeb1fa96c22b9c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs b/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs new file mode 100644 index 0000000..23919b4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs @@ -0,0 +1,73 @@ +using System; +using System.Buffers; +using System.IO; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Serialize +{ + public enum MemoryStreamBufferSource + { + None = 0, + Pack = 1, + UnPack = 2, + } + + public sealed class MemoryStreamBuffer : MemoryStream, IBufferWriter + { + public MemoryStreamBufferSource MemoryStreamBufferSource; + public MemoryStreamBuffer() { } + + public MemoryStreamBuffer(MemoryStreamBufferSource memoryStreamBufferSource, int capacity) : base(capacity) + { + MemoryStreamBufferSource = memoryStreamBufferSource; + } + public MemoryStreamBuffer(byte[] buffer): base(buffer) { } + + public void Advance(int count) + { + if (count < 0) + { + throw new ArgumentOutOfRangeException(nameof(count), count, "The value of 'count' cannot be negative."); + } + + var newLength = Position + count; + + if (newLength != Length) + { + SetLength(newLength); + } + + Position = newLength; + } + + public Memory GetMemory(int sizeHint = 0) + { + if (sizeHint < 0) + { + throw new ArgumentOutOfRangeException(nameof(sizeHint), sizeHint, "The value of 'count' cannot be negative."); + } + + if (Length - Position <= sizeHint) + { + SetLength(Position + sizeHint); + } + + return new Memory(GetBuffer(), (int)Position, (int)(Length - Position)); + } + + public Span GetSpan(int sizeHint = 0) + { + if (sizeHint < 0) + { + throw new ArgumentOutOfRangeException(nameof(sizeHint), sizeHint, "The value of 'count' cannot be negative."); + } + + if (Length - Position <= sizeHint) + { + SetLength(Position + sizeHint); + } + + return new Span(GetBuffer(), (int)Position, (int)(Length - Position)); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs.meta b/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs.meta new file mode 100644 index 0000000..e9793e4 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/MemoryStreamBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a64b8cd86e5fb446a4791e322806d78 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper.meta b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper.meta new file mode 100644 index 0000000..2dba840 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cc84c0b94ee7cf543880619478c526c8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs new file mode 100644 index 0000000..2267dd2 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs @@ -0,0 +1,9 @@ +namespace Fantasy.Serialize +{ + /// + /// 代表是一个ProtoBuf协议 + /// + public interface IProto + { + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta new file mode 100644 index 0000000..c0c0dd0 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a849556e6e5f7043865ada5c0dfad7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs new file mode 100644 index 0000000..5e28808 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs @@ -0,0 +1,234 @@ +#if FANTASY_NET || FANTASY_EXPORTER +using System.Buffers; +using Fantasy.Assembly; +using ProtoBuf.Meta; +namespace Fantasy.Serialize +{ + /// + /// ProtoBufP帮助类,Net平台使用 + /// + public sealed class ProtoBufPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "ProtoBuf"; + + /// + /// 构造函数 + /// + public ProtoBufPackHelper () + { +#if FANTASY_NET + RuntimeTypeModel.Default.AutoAddMissingTypes = true; + RuntimeTypeModel.Default.AllowParseableTypes = true; + RuntimeTypeModel.Default.AutoAddMissingTypes = true; + RuntimeTypeModel.Default.AutoCompile = true; + RuntimeTypeModel.Default.UseImplicitZeroDefaults = true; + RuntimeTypeModel.Default.InferTagFromNameDefault = true; + + foreach (var type in AssemblySystem.ForEach(typeof(IProto))) + { + RuntimeTypeModel.Default.Add(type, true); + } + + RuntimeTypeModel.Default.CompileInPlace(); +#endif + } + + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(byte[] bytes) + { + var memory = new ReadOnlyMemory(bytes); + var @object = RuntimeTypeModel.Default.Deserialize(memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = RuntimeTypeModel.Default.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes) + { + var memory = new ReadOnlyMemory(bytes); + var @object = RuntimeTypeModel.Default.Deserialize(type, memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = RuntimeTypeModel.Default.Deserialize(type, buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public T Deserialize(byte[] bytes, int index, int count) + { + var memory = new ReadOnlyMemory(bytes, index, count); + var @object = RuntimeTypeModel.Default.Deserialize(memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes, int index, int count) + { + var memory = new ReadOnlyMemory(bytes, index, count); + var @object = RuntimeTypeModel.Default.Deserialize(type, memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到byte[] + /// + /// + /// + public byte[] Serialize(object @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using (var buffer = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + } + /// + /// 使用ProtoBuf序列化某一个实例到byte[] + /// + /// + /// + /// + public byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using (var buffer = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + } + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta new file mode 100644 index 0000000..8c1e421 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cece259a2d5d5b244917f657e66ce26c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs new file mode 100644 index 0000000..0e386af --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs @@ -0,0 +1,225 @@ +#if FANTASY_UNITY || FANTASY_CONSOLE +using System; +using System.Buffers; +using System.IO; +using Fantasy.Assembly; +using ProtoBuf; +using ProtoBuf.Meta; + +namespace Fantasy.Serialize +{ + /// + /// ProtoBufP帮助类,Unity平台使用 + /// + public sealed class ProtoBufPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "ProtoBuf"; + + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes) + { + fixed (byte* ptr = bytes) + { + using var stream = new UnmanagedMemoryStream(ptr, bytes.Length); + var @object = ProtoBuf.Serializer.Deserialize(stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = ProtoBuf.Serializer.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes) + { + fixed (byte* ptr = bytes) + { + using var stream = new UnmanagedMemoryStream(ptr, bytes.Length); + var @object = ProtoBuf.Serializer.Deserialize(type, stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = ProtoBuf.Serializer.Deserialize(type, buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes, int index, int count) + { + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + var @object = ProtoBuf.Serializer.Deserialize(stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes, int index, int count) + { + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + var @object = ProtoBuf.Serializer.Deserialize(type, stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到byte[] + /// + /// + /// + public byte[] Serialize(object @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using (var buffer = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + } + /// + /// 使用ProtoBuf序列化某一个实例到byte[] + /// + /// + /// + public byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using (var buffer = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + } + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta new file mode 100644 index 0000000..e472bdd --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17ccebfd188db9746b79deba48af4adc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs b/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs new file mode 100644 index 0000000..6b86678 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using Fantasy.Assembly; +using Fantasy.Helper; +#if !FANTASY_EXPORTER +using Fantasy.Network; +#endif +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.Serialize +{ + /// + /// 框架内置的序列化器类型 + /// + public static class FantasySerializerType + { + /// + /// ProtoBuf在SerializerManager的数组下标 + /// + public const int ProtoBuf = 0; + /// + /// Bson在SerializerManager的数组下标 + /// + public const int Bson = 1; + } + + /// + /// 管理序列化静态方法,主要是优化网络协议时使用。 + /// + public static class SerializerManager + { + private static ISerialize[] _serializers; + private static bool _isInitialized = false; + +#if FANTASY_NET || FANTASY_UNITY + /// + /// 初始化方法 + /// + public static void Initialize() + { + if (_isInitialized) + { + return; + } + + try + { + var sort = new SortedList(); + + foreach (var serializerType in AssemblySystem.ForEach(typeof(ISerialize))) + { + var serializer = (ISerialize)Activator.CreateInstance(serializerType); + var computeHash64 = HashCodeHelper.ComputeHash64(serializer.SerializeName); + sort.Add(computeHash64, serializer); + } + + var index = 1; + _serializers = new ISerialize[sort.Count]; + + foreach (var (_, serialize) in sort) + { + var serializerIndex = 0; + + switch (serialize) + { + case ProtoBufPackHelper: + { + serializerIndex = FantasySerializerType.ProtoBuf; + break; + } + case BsonPackHelper: + { + serializerIndex = FantasySerializerType.Bson; + break; + } + default: + { + serializerIndex = ++index; + break; + } + } + + _serializers[serializerIndex] = serialize; + } + + _isInitialized = true; +#if FANTASY_DEBUG + Log.Info($"初始化序列化器成功,数量为:{_serializers.Length}"); +#endif + } + catch (Exception e) + { + Log.Error(e); + Dispose(); + } + } +#else + /// + /// 初始化方法 + /// + public static void Initialize() + { + if (_isInitialized) + { + return; + } + + _serializers = new ISerialize[1]; + _serializers[0] = new ProtoBufPackHelper(); + } +#endif + + /// + /// 销毁方法 + /// + public static void Dispose() + { + _isInitialized = false; + Array.Clear(_serializers, 0, _serializers.Length); + } + + /// + /// 根据协议类型获取序列化器 + /// + /// + /// + public static ISerialize GetSerializer(uint opCodeProtocolType) + { + return _serializers[opCodeProtocolType]; + } + + /// + /// 获得一个序列化器 + /// + /// + /// + /// + public static bool TryGetSerializer(uint opCodeProtocolType, out ISerialize serializer) + { + if (opCodeProtocolType < _serializers.Length) + { + serializer = _serializers[opCodeProtocolType]; + return true; + } + + serializer = default; + return false; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs.meta b/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs.meta new file mode 100644 index 0000000..0fae738 --- /dev/null +++ b/Runtime/CoreRuntime/Core/Serialize/SerializerManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa7d0b482df3e49468e440617b2b35ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins.meta b/Runtime/CoreRuntime/Plugins.meta new file mode 100644 index 0000000..38d5ab7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 83d89049147bb914585f074b1870959d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Other.meta b/Runtime/CoreRuntime/Plugins/Other.meta new file mode 100644 index 0000000..6027fdc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Other.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c94f9e85ecfaa1142ae41442da371059 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll b/Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll new file mode 100644 index 0000000000000000000000000000000000000000..308228874f4790a0915835637dad30b7750fc7e1 GIT binary patch literal 252680 zcmcGX2b^71wg2y&bMCoiN^)m1_l5*W2qYYDnIscH1f>c}5ClY>pwbi&R1W463&V`T zf(>HBh8?i?-g`$y>hC!F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k~|JX#9m_0F%C9<12&4=LU^W3>x>cD9pKM7v~*U>)*9F`S>y3x5lL@y|P!Q z{=aP!JEy;T%`9t!#uv44R;9d;`?c=WG3!E$wGJFRcfMPcAFsU4 zZ-act2ecf)(!|8D;Z#K5xq!p#gZ|y!&``Bp`|jFk4aQ>}w;w)Ae{ngKC2@Aq72(K) z&Xe`s?{yAXTebvf8a#S*Z{Byi3%>5GGfozE3e2@A3UAWP{#F;Z@5=w@{tK@NcSqjY z_4nPTHLWVoK6J*?AvaV ztgwV@!^#H9I*ywuH}Gyl%_-!_}rkL;aa)lx`_Zv;Q1sXLuzfR_B@!D%o;@*~@|9J8={iQLilAn!F9_%if zWcPNL$qjYYrak6fS;v=MdDD5}xq!zf&lTy3x_OK1m6A74s%E`Bsqvok-aEfSTRhov z*K7P=vG_~v&K`MpyU*)cXP7?`lCCYcR$IDp-e$4ceyWohI^Pxav%73nyX!l@=yB$p zw2$w(EriWXJHG9=>QdjjW2-^LhoHG!Ei;xz%vHI0u~Tfd+1VeP&fS~C=KK3t^`X+V lj;rrjmYIi4ZL_vd(VBFtTOy8KZOh$LswOj+l)5GN0RZHP^-BN% literal 0 HcmV?d00001 diff --git a/Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll.meta b/Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll.meta new file mode 100644 index 0000000..48db18a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Other/System.Collections.Immutable.dll.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: 6716dcef103ac3a4a8008346a88f1e74 +labels: +- NuGetForUnity +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Other/System.IO.Pipelines.dll b/Runtime/CoreRuntime/Plugins/Other/System.IO.Pipelines.dll new file mode 100644 index 0000000000000000000000000000000000000000..003bcd00194ea58b71cc854602314b874d0fd54b GIT binary patch literal 84744 zcmb@v34E2s^*%oHzVBUf6O!DUodlAQg_rDMD~k&V?x>)s;06e&pmLQ!U6PB5;99k! zh%LU2;#MpQF1S{0tC*rvmujtbU*qq2&dj~J0sPkg=kvdsGjomX^6>Z5Pf9(6l%H_||8LLEVWNlm3 zpo&c0qExX~Dr~4dBap8^ejHMzawYE=yGaNV@Y4xC=ubYR(XN^2P?Z1orWPd$pWC7L zAZDOk>ykC-5q)Zp-Fz|iS$~7&Td-@{aULouSPudE* z(?1ocy=h_F!r35-ZLm=q+8=4!XB@0=S~&NlI0R`cZDt>+iXG(kAUpl@5B4iQw9Qcg zm6cHHbc{rXP?cIXM60JG7$da5)6)L0WT4{@P%2WFOph_RQ*`kxrF2c9dtCw*dUazg z-Q6CA-RWHTW;zNt_3HXB!9aO+s^*z*Tb`dK4gDboFSkgh2S^p*(tRV;Fs+fZvt6**E& zfGbw`m`P$vjihxq@62i!R;L?MOWB8aX10;6Dehy$V2ZzP#0T}UyH~uXBs;B!K(^=m zEcFMkVX!sb?KR!&W4h-Lp{QH8WC^CRSJPNn`x1uJ@iA_Zwt9e?PBQA67KShsGFr%w zNXws^mcK78|9)D&ME90GIxT;3TK<8w{J+!kgPq>8v(xf7q~%{u%SYW_`CZfUbJOz6 zQ+fCy{jnG++&{W-6F4#DH=yN>ZehI+c8bF%=hV-oy>klPdv<0WST>KkmDvK19{AHLy!yz(Ii1KAjFac$<*a2*Yg|ce#bbCnF|X%bxKZ-!}+U}ILkkr;-uXEJutH-3fkm;?W_{9;s6x)UXNEv`BT zI^Ype7dHGVWrJ7PQn>ISpx#BtVMzS~RMa+{bvtoPu?UpqJModo!7{&$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^ODOP+?~ZV;k-qM3wkO*2=Ki#r)Sl9a6(KltUQj|FO7HDEe@XNX0o zkyd2If%>6Sq9S!8*n@V|s-JR^TK?>MRokP5I<<`rYX__4)IX-_zdUSS@cgoybio_D zd#|214{m)PsJ1GLIfZvI!~2rU=A%ij + /// Provides support for common .NET types that do not have a direct representation + /// in protobuf, using the definitions from bcl.proto + /// + public static class BclHelpers + { + /// + /// Creates a new instance of the specified type, bypassing the constructor. + /// + /// The type to create + /// The new instance + /// If the platform does not support constructor-skipping + public static object GetUninitializedObject(Type type) + { +#if COREFX + object obj = TryGetUninitializedObjectWithFormatterServices(type); + if (obj != null) return obj; +#endif +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type); +#else + throw new NotSupportedException("Constructor-skipping is not supported on this platform"); +#endif + } + +#if COREFX // this is inspired by DCS: https://github.com/dotnet/corefx/blob/c02d33b18398199f6acc17d375dab154e9a1df66/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs#L854-L894 + static Func getUninitializedObject; + static internal object TryGetUninitializedObjectWithFormatterServices(Type type) + { + if (getUninitializedObject == null) + { + try { + var formatterServiceType = typeof(string).GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.FormatterServices"); + if (formatterServiceType == null) + { + // fallback for .Net Core 3.0 + var formatterAssembly = Assembly.Load(new AssemblyName("System.Runtime.Serialization.Formatters")); + formatterServiceType = formatterAssembly.GetType("System.Runtime.Serialization.FormatterServices"); + } + MethodInfo method = formatterServiceType?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + if (method != null) + { + getUninitializedObject = (Func)method.CreateDelegate(typeof(Func)); + } + } + catch { /* best efforts only */ } + if(getUninitializedObject == null) getUninitializedObject = x => null; + } + return getUninitializedObject(type); + } +#endif + + const int FieldTimeSpanValue = 0x01, FieldTimeSpanScale = 0x02, FieldTimeSpanKind = 0x03; + + internal static readonly DateTime[] EpochOrigin = { + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local) + }; + + /// + /// The default value for dates that are following google.protobuf.Timestamp semantics + /// + private static readonly DateTime TimestampEpoch = EpochOrigin[(int)DateTimeKind.Utc]; + + /// + /// Writes a TimeSpan to a protobuf stream using protobuf-net's own representation, bcl.TimeSpan + /// + public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest) + { + WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified); + } + + private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind) + { + if (dest == null) throw new ArgumentNullException(nameof(dest)); + long value; + switch (dest.WireType) + { + case WireType.String: + case WireType.StartGroup: + TimeSpanScale scale; + value = timeSpan.Ticks; + if (timeSpan == TimeSpan.MaxValue) + { + value = 1; + scale = TimeSpanScale.MinMax; + } + else if (timeSpan == TimeSpan.MinValue) + { + value = -1; + scale = TimeSpanScale.MinMax; + } + else if (value % TimeSpan.TicksPerDay == 0) + { + scale = TimeSpanScale.Days; + value /= TimeSpan.TicksPerDay; + } + else if (value % TimeSpan.TicksPerHour == 0) + { + scale = TimeSpanScale.Hours; + value /= TimeSpan.TicksPerHour; + } + else if (value % TimeSpan.TicksPerMinute == 0) + { + scale = TimeSpanScale.Minutes; + value /= TimeSpan.TicksPerMinute; + } + else if (value % TimeSpan.TicksPerSecond == 0) + { + scale = TimeSpanScale.Seconds; + value /= TimeSpan.TicksPerSecond; + } + else if (value % TimeSpan.TicksPerMillisecond == 0) + { + scale = TimeSpanScale.Milliseconds; + value /= TimeSpan.TicksPerMillisecond; + } + else + { + scale = TimeSpanScale.Ticks; + } + + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + + if (value != 0) + { + ProtoWriter.WriteFieldHeader(FieldTimeSpanValue, WireType.SignedVariant, dest); + ProtoWriter.WriteInt64(value, dest); + } + if (scale != TimeSpanScale.Days) + { + ProtoWriter.WriteFieldHeader(FieldTimeSpanScale, WireType.Variant, dest); + ProtoWriter.WriteInt32((int)scale, dest); + } + if (kind != DateTimeKind.Unspecified) + { + ProtoWriter.WriteFieldHeader(FieldTimeSpanKind, WireType.Variant, dest); + ProtoWriter.WriteInt32((int)kind, dest); + } + ProtoWriter.EndSubItem(token, dest); + break; + case WireType.Fixed64: + ProtoWriter.WriteInt64(timeSpan.Ticks, dest); + break; + default: + throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString()); + } + } + + /// + /// Parses a TimeSpan from a protobuf stream using protobuf-net's own representation, bcl.TimeSpan + /// + public static TimeSpan ReadTimeSpan(ProtoReader source) + { + long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind); + if (ticks == long.MinValue) return TimeSpan.MinValue; + if (ticks == long.MaxValue) return TimeSpan.MaxValue; + return TimeSpan.FromTicks(ticks); + } + + /// + /// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration + /// + public static TimeSpan ReadDuration(ProtoReader source) + { + long seconds = 0; + int nanos = 0; + SubItemToken token = ProtoReader.StartSubItem(source); + int fieldNumber; + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + switch (fieldNumber) + { + case 1: + seconds = source.ReadInt64(); + break; + case 2: + nanos = source.ReadInt32(); + break; + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + return FromDurationSeconds(seconds, nanos); + } + + /// + /// Writes a TimeSpan to a protobuf stream using the standardized format, google.protobuf.Duration + /// + public static void WriteDuration(TimeSpan value, ProtoWriter dest) + { + var seconds = ToDurationSeconds(value, out int nanos); + WriteSecondsNanos(seconds, nanos, dest); + } + + private static void WriteSecondsNanos(long seconds, int nanos, ProtoWriter dest) + { + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (seconds != 0) + { + ProtoWriter.WriteFieldHeader(1, WireType.Variant, dest); + ProtoWriter.WriteInt64(seconds, dest); + } + if (nanos != 0) + { + ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest); + ProtoWriter.WriteInt32(nanos, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + + /// + /// Parses a DateTime from a protobuf stream using the standardized format, google.protobuf.Timestamp + /// + public static DateTime ReadTimestamp(ProtoReader source) + { + // note: DateTime is only defined for just over 0000 to just below 10000; + // TimeSpan has a range of +/- 10,675,199 days === 29k years; + // so we can just use epoch time delta + return TimestampEpoch + ReadDuration(source); + } + + /// + /// Writes a DateTime to a protobuf stream using the standardized format, google.protobuf.Timestamp + /// + public static void WriteTimestamp(DateTime value, ProtoWriter dest) + { + var seconds = ToDurationSeconds(value - TimestampEpoch, out int nanos); + + if (nanos < 0) + { // from Timestamp.proto: + // "Negative second values with fractions must still have + // non -negative nanos values that count forward in time." + seconds--; + nanos += 1000000000; + } + WriteSecondsNanos(seconds, nanos, dest); + } + + static TimeSpan FromDurationSeconds(long seconds, int nanos) + { + + long ticks = checked((seconds * TimeSpan.TicksPerSecond) + + (nanos * TimeSpan.TicksPerMillisecond) / 1000000); + return TimeSpan.FromTicks(ticks); + } + + static long ToDurationSeconds(TimeSpan value, out int nanos) + { + nanos = (int)(((value.Ticks % TimeSpan.TicksPerSecond) * 1000000) + / TimeSpan.TicksPerMillisecond); + return value.Ticks / TimeSpan.TicksPerSecond; + } + + /// + /// Parses a DateTime from a protobuf stream + /// + public static DateTime ReadDateTime(ProtoReader source) + { + long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind); + if (ticks == long.MinValue) return DateTime.MinValue; + if (ticks == long.MaxValue) return DateTime.MaxValue; + return EpochOrigin[(int)kind].AddTicks(ticks); + } + + /// + /// Writes a DateTime to a protobuf stream, excluding the Kind + /// + public static void WriteDateTime(DateTime value, ProtoWriter dest) + { + WriteDateTimeImpl(value, dest, false); + } + + /// + /// Writes a DateTime to a protobuf stream, including the Kind + /// + public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest) + { + WriteDateTimeImpl(value, dest, true); + } + + private static void WriteDateTimeImpl(DateTime value, ProtoWriter dest, bool includeKind) + { + if (dest == null) throw new ArgumentNullException(nameof(dest)); + TimeSpan delta; + switch (dest.WireType) + { + case WireType.StartGroup: + case WireType.String: + if (value == DateTime.MaxValue) + { + delta = TimeSpan.MaxValue; + includeKind = false; + } + else if (value == DateTime.MinValue) + { + delta = TimeSpan.MinValue; + includeKind = false; + } + else + { + delta = value - EpochOrigin[0]; + } + break; + default: + delta = value - EpochOrigin[0]; + break; + } + WriteTimeSpanImpl(delta, dest, includeKind ? value.Kind : DateTimeKind.Unspecified); + } + + private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) + { + kind = DateTimeKind.Unspecified; + switch (source.WireType) + { + case WireType.String: + case WireType.StartGroup: + SubItemToken token = ProtoReader.StartSubItem(source); + int fieldNumber; + TimeSpanScale scale = TimeSpanScale.Days; + long value = 0; + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + switch (fieldNumber) + { + case FieldTimeSpanScale: + scale = (TimeSpanScale)source.ReadInt32(); + break; + case FieldTimeSpanValue: + source.Assert(WireType.SignedVariant); + value = source.ReadInt64(); + break; + case FieldTimeSpanKind: + kind = (DateTimeKind)source.ReadInt32(); + switch (kind) + { + case DateTimeKind.Unspecified: + case DateTimeKind.Utc: + case DateTimeKind.Local: + break; // fine + default: + throw new ProtoException("Invalid date/time kind: " + kind.ToString()); + } + break; + default: + source.SkipField(); + break; + } + } + ProtoReader.EndSubItem(token, source); + switch (scale) + { + case TimeSpanScale.Days: + return value * TimeSpan.TicksPerDay; + case TimeSpanScale.Hours: + return value * TimeSpan.TicksPerHour; + case TimeSpanScale.Minutes: + return value * TimeSpan.TicksPerMinute; + case TimeSpanScale.Seconds: + return value * TimeSpan.TicksPerSecond; + case TimeSpanScale.Milliseconds: + return value * TimeSpan.TicksPerMillisecond; + case TimeSpanScale.Ticks: + return value; + case TimeSpanScale.MinMax: + switch (value) + { + case 1: return long.MaxValue; + case -1: return long.MinValue; + default: throw new ProtoException("Unknown min/max value: " + value.ToString()); + } + default: + throw new ProtoException("Unknown timescale: " + scale.ToString()); + } + case WireType.Fixed64: + return source.ReadInt64(); + default: + throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString()); + } + } + + const int FieldDecimalLow = 0x01, FieldDecimalHigh = 0x02, FieldDecimalSignScale = 0x03; + + /// + /// Parses a decimal from a protobuf stream + /// + public static decimal ReadDecimal(ProtoReader reader) + { + ulong low = 0; + uint high = 0; + uint signScale = 0; + + int fieldNumber; + SubItemToken token = ProtoReader.StartSubItem(reader); + while ((fieldNumber = reader.ReadFieldHeader()) > 0) + { + switch (fieldNumber) + { + case FieldDecimalLow: low = reader.ReadUInt64(); break; + case FieldDecimalHigh: high = reader.ReadUInt32(); break; + case FieldDecimalSignScale: signScale = reader.ReadUInt32(); break; + default: reader.SkipField(); break; + } + + } + ProtoReader.EndSubItem(token, reader); + + int lo = (int)(low & 0xFFFFFFFFL), + mid = (int)((low >> 32) & 0xFFFFFFFFL), + hi = (int)high; + bool isNeg = (signScale & 0x0001) == 0x0001; + byte scale = (byte)((signScale & 0x01FE) >> 1); + return new decimal(lo, mid, hi, isNeg, scale); + } + + /// + /// Writes a decimal to a protobuf stream + /// + public static void WriteDecimal(decimal value, ProtoWriter writer) + { + int[] bits = decimal.GetBits(value); + ulong a = ((ulong)bits[1]) << 32, b = ((ulong)bits[0]) & 0xFFFFFFFFL; + ulong low = a | b; + uint high = (uint)bits[2]; + uint signScale = (uint)(((bits[3] >> 15) & 0x01FE) | ((bits[3] >> 31) & 0x0001)); + + SubItemToken token = ProtoWriter.StartSubItem(null, writer); + if (low != 0) + { + ProtoWriter.WriteFieldHeader(FieldDecimalLow, WireType.Variant, writer); + ProtoWriter.WriteUInt64(low, writer); + } + if (high != 0) + { + ProtoWriter.WriteFieldHeader(FieldDecimalHigh, WireType.Variant, writer); + ProtoWriter.WriteUInt32(high, writer); + } + if (signScale != 0) + { + ProtoWriter.WriteFieldHeader(FieldDecimalSignScale, WireType.Variant, writer); + ProtoWriter.WriteUInt32(signScale, writer); + } + ProtoWriter.EndSubItem(token, writer); + } + + const int FieldGuidLow = 1, FieldGuidHigh = 2; + /// + /// Writes a Guid to a protobuf stream + /// + public static void WriteGuid(Guid value, ProtoWriter dest) + { + byte[] blob = value.ToByteArray(); + + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (value != Guid.Empty) + { + ProtoWriter.WriteFieldHeader(FieldGuidLow, WireType.Fixed64, dest); + ProtoWriter.WriteBytes(blob, 0, 8, dest); + ProtoWriter.WriteFieldHeader(FieldGuidHigh, WireType.Fixed64, dest); + ProtoWriter.WriteBytes(blob, 8, 8, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + /// + /// Parses a Guid from a protobuf stream + /// + public static Guid ReadGuid(ProtoReader source) + { + ulong low = 0, high = 0; + int fieldNumber; + SubItemToken token = ProtoReader.StartSubItem(source); + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + switch (fieldNumber) + { + case FieldGuidLow: low = source.ReadUInt64(); break; + case FieldGuidHigh: high = source.ReadUInt64(); break; + default: source.SkipField(); break; + } + } + ProtoReader.EndSubItem(token, source); + if (low == 0 && high == 0) return Guid.Empty; + uint a = (uint)(low >> 32), b = (uint)low, c = (uint)(high >> 32), d = (uint)high; + return new Guid((int)b, (short)a, (short)(a >> 16), + (byte)d, (byte)(d >> 8), (byte)(d >> 16), (byte)(d >> 24), + (byte)c, (byte)(c >> 8), (byte)(c >> 16), (byte)(c >> 24)); + + } + + + private const int + FieldExistingObjectKey = 1, + FieldNewObjectKey = 2, + FieldExistingTypeKey = 3, + FieldNewTypeKey = 4, + FieldTypeName = 8, + FieldObject = 10; + + /// + /// Optional behaviours that introduce .NET-specific functionality + /// + [Flags] + public enum NetObjectOptions : byte + { + /// + /// No special behaviour + /// + None = 0, + /// + /// Enables full object-tracking/full-graph support. + /// + AsReference = 1, + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + DynamicType = 2, + /// + /// If false, the constructor for the type is bypassed during deserialization, meaning any field initializers + /// or other initialization code is skipped. + /// + UseConstructor = 4, + /// + /// Should the object index be reserved, rather than creating an object promptly + /// + LateSet = 8 + } + + /// + /// Reads an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc. + /// + public static object ReadNetObject(object value, ProtoReader source, int key, Type type, NetObjectOptions options) + { + SubItemToken token = ProtoReader.StartSubItem(source); + int fieldNumber; + int newObjectKey = -1, newTypeKey = -1, tmp; + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + switch (fieldNumber) + { + case FieldExistingObjectKey: + tmp = source.ReadInt32(); + value = source.NetCache.GetKeyedObject(tmp); + break; + case FieldNewObjectKey: + newObjectKey = source.ReadInt32(); + break; + case FieldExistingTypeKey: + tmp = source.ReadInt32(); + type = (Type)source.NetCache.GetKeyedObject(tmp); + key = source.GetTypeKey(ref type); + break; + case FieldNewTypeKey: + newTypeKey = source.ReadInt32(); + break; + case FieldTypeName: + string typeName = source.ReadString(); + type = source.DeserializeType(typeName); + if (type == null) + { + throw new ProtoException("Unable to resolve type: " + typeName + " (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)"); + } + if (type == typeof(string)) + { + key = -1; + } + else + { + key = source.GetTypeKey(ref type); + if (key < 0) + throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name); + } + break; + case FieldObject: + bool isString = type == typeof(string); + bool wasNull = value == null; + bool lateSet = wasNull && (isString || ((options & NetObjectOptions.LateSet) != 0)); + + if (newObjectKey >= 0 && !lateSet) + { + if (value == null) + { + source.TrapNextObject(newObjectKey); + } + else + { + source.NetCache.SetKeyedObject(newObjectKey, value); + } + if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type); + } + object oldValue = value; + if (isString) + { + value = source.ReadString(); + } + else + { + value = ProtoReader.ReadTypedObject(oldValue, key, source, type); + } + + if (newObjectKey >= 0) + { + if (wasNull && !lateSet) + { // this both ensures (via exception) that it *was* set, and makes sure we don't shout + // about changed references + oldValue = source.NetCache.GetKeyedObject(newObjectKey); + } + if (lateSet) + { + source.NetCache.SetKeyedObject(newObjectKey, value); + if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type); + } + } + if (newObjectKey >= 0 && !lateSet && !ReferenceEquals(oldValue, value)) + { + throw new ProtoException("A reference-tracked object changed reference during deserialization"); + } + if (newObjectKey < 0 && newTypeKey >= 0) + { // have a new type, but not a new object + source.NetCache.SetKeyedObject(newTypeKey, type); + } + break; + default: + source.SkipField(); + break; + } + } + if (newObjectKey >= 0 && (options & NetObjectOptions.AsReference) == 0) + { + throw new ProtoException("Object key in input stream, but reference-tracking was not expected"); + } + ProtoReader.EndSubItem(token, source); + + return value; + } + + /// + /// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc. + /// + public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options) + { + if (dest == null) throw new ArgumentNullException("dest"); + bool dynamicType = (options & NetObjectOptions.DynamicType) != 0, + asReference = (options & NetObjectOptions.AsReference) != 0; + WireType wireType = dest.WireType; + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + bool writeObject = true; + if (asReference) + { + int objectKey = dest.NetCache.AddObjectKey(value, out bool existing); + ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant, dest); + ProtoWriter.WriteInt32(objectKey, dest); + if (existing) + { + writeObject = false; + } + } + + if (writeObject) + { + if (dynamicType) + { + Type type = value.GetType(); + + if (!(value is string)) + { + key = dest.GetTypeKey(ref type); + if (key < 0) throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name); + } + int typeKey = dest.NetCache.AddObjectKey(type, out bool existing); + ProtoWriter.WriteFieldHeader(existing ? FieldExistingTypeKey : FieldNewTypeKey, WireType.Variant, dest); + ProtoWriter.WriteInt32(typeKey, dest); + if (!existing) + { + ProtoWriter.WriteFieldHeader(FieldTypeName, WireType.String, dest); + ProtoWriter.WriteString(dest.SerializeType(type), dest); + } + + } + ProtoWriter.WriteFieldHeader(FieldObject, wireType, dest); + if (value is string) + { + ProtoWriter.WriteString((string)value, dest); + } + else + { + ProtoWriter.WriteObject(value, key, dest); + } + } + ProtoWriter.EndSubItem(token, dest); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/BclHelpers.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/BclHelpers.cs.meta new file mode 100644 index 0000000..e9abea8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/BclHelpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c204ba8f30e46f3449f357f194de70f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs new file mode 100644 index 0000000..ea428dd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs @@ -0,0 +1,78 @@ +using System; +using System.IO; + +namespace ProtoBuf +{ + /// + /// Provides a simple buffer-based implementation of an extension object. + /// + public sealed class BufferExtension : IExtension, IExtensionResettable + { + private byte[] buffer; + + void IExtensionResettable.Reset() + { + buffer = null; + } + + int IExtension.GetLength() + { + return buffer == null ? 0 : buffer.Length; + } + + Stream IExtension.BeginAppend() + { + return new MemoryStream(); + } + + void IExtension.EndAppend(Stream stream, bool commit) + { + using (stream) + { + int len; + if (commit && (len = (int)stream.Length) > 0) + { + MemoryStream ms = (MemoryStream)stream; + + if (buffer == null) + { // allocate new buffer + buffer = ms.ToArray(); + } + else + { // resize and copy the data + // note: Array.Resize not available on CF + int offset = buffer.Length; + byte[] tmp = new byte[offset + len]; + Buffer.BlockCopy(buffer, 0, tmp, 0, offset); + +#if PORTABLE // no GetBuffer() - fine, we'll use Read instead + int bytesRead; + long oldPos = ms.Position; + ms.Position = 0; + while (len > 0 && (bytesRead = ms.Read(tmp, offset, len)) > 0) + { + len -= bytesRead; + offset += bytesRead; + } + if(len != 0) throw new EndOfStreamException(); + ms.Position = oldPos; +#else + Buffer.BlockCopy(Helpers.GetBuffer(ms), 0, tmp, offset, len); +#endif + buffer = tmp; + } + } + } + } + + Stream IExtension.BeginQuery() + { + return buffer == null ? Stream.Null : new MemoryStream(buffer); + } + + void IExtension.EndQuery(Stream stream) + { + using (stream) { } // just clean up + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs.meta new file mode 100644 index 0000000..e10c122 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e2414f37b0b8a449be8be54abf903c3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs new file mode 100644 index 0000000..8ad3d1a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs @@ -0,0 +1,149 @@ +using System; + +namespace ProtoBuf +{ + internal sealed class BufferPool + { + internal static void Flush() + { + lock (Pool) + { + for (var i = 0; i < Pool.Length; i++) + Pool[i] = null; + } + } + + private BufferPool() { } + private const int POOL_SIZE = 20; + internal const int BUFFER_LENGTH = 1024; + private static readonly CachedBuffer[] Pool = new CachedBuffer[POOL_SIZE]; + + internal static byte[] GetBuffer() => GetBuffer(BUFFER_LENGTH); + + internal static byte[] GetBuffer(int minSize) + { + byte[] cachedBuff = GetCachedBuffer(minSize); + return cachedBuff ?? new byte[minSize]; + } + + internal static byte[] GetCachedBuffer(int minSize) + { + lock (Pool) + { + var bestIndex = -1; + byte[] bestMatch = null; + for (var i = 0; i < Pool.Length; i++) + { + var buffer = Pool[i]; + if (buffer == null || buffer.Size < minSize) + { + continue; + } + if (bestMatch != null && bestMatch.Length < buffer.Size) + { + continue; + } + + var tmp = buffer.Buffer; + if (tmp == null) + { + Pool[i] = null; + } + else + { + bestMatch = tmp; + bestIndex = i; + } + } + + if (bestIndex >= 0) + { + Pool[bestIndex] = null; + } + + return bestMatch; + } + } + + /// + /// https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element + /// + private const int MaxByteArraySize = int.MaxValue - 56; + + internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes) + { + Helpers.DebugAssert(buffer != null); + Helpers.DebugAssert(toFitAtLeastBytes > buffer.Length); + Helpers.DebugAssert(copyFromIndex >= 0); + Helpers.DebugAssert(copyBytes >= 0); + + int newLength = buffer.Length * 2; + if (newLength < 0) + { + newLength = MaxByteArraySize; + } + + if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes; + + if (copyBytes == 0) + { + ReleaseBufferToPool(ref buffer); + } + + var newBuffer = GetCachedBuffer(toFitAtLeastBytes) ?? new byte[newLength]; + + if (copyBytes > 0) + { + Buffer.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes); + ReleaseBufferToPool(ref buffer); + } + + buffer = newBuffer; + } + + internal static void ReleaseBufferToPool(ref byte[] buffer) + { + if (buffer == null) return; + + lock (Pool) + { + var minIndex = 0; + var minSize = int.MaxValue; + for (var i = 0; i < Pool.Length; i++) + { + var tmp = Pool[i]; + if (tmp == null || !tmp.IsAlive) + { + minIndex = 0; + break; + } + if (tmp.Size < minSize) + { + minIndex = i; + minSize = tmp.Size; + } + } + + Pool[minIndex] = new CachedBuffer(buffer); + } + + buffer = null; + } + + private class CachedBuffer + { + private readonly WeakReference _reference; + + public int Size { get; } + + public bool IsAlive => _reference.IsAlive; + public byte[] Buffer => (byte[])_reference.Target; + + public CachedBuffer(byte[] buffer) + { + Size = buffer.Length; + _reference = new WeakReference(buffer); + } + } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs.meta new file mode 100644 index 0000000..ddcd240 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/BufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38128b740cd61204786d82957bc2c2b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs new file mode 100644 index 0000000..1adb8e5 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs @@ -0,0 +1,33 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf +{ + /// Specifies a method on the root-contract in an hierarchy to be invoked before serialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoBeforeSerializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked after serialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoAfterSerializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked before deserialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoBeforeDeserializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked after deserialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoAfterDeserializationAttribute : Attribute { } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs.meta new file mode 100644 index 0000000..3a29d73 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/CallbackAttributes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 693031ba9f59b854781ce21eb1e6d92e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler.meta new file mode 100644 index 0000000..bf1a031 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bc5e7ee549da1bd43bcb9bb3fe372ba2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs new file mode 100644 index 0000000..6100200 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs @@ -0,0 +1,1435 @@ +#if FEAT_COMPILER +//#define DEBUG_COMPILE +using System; +using System.Threading; +using ProtoBuf.Meta; +using ProtoBuf.Serializers; +using System.Reflection; +using System.Reflection.Emit; + +namespace ProtoBuf.Compiler +{ + internal readonly struct CodeLabel + { + public readonly Label Value; + public readonly int Index; + public CodeLabel(Label value, int index) + { + this.Value = value; + this.Index = index; + } + } + internal sealed class CompilerContext + { + public TypeModel Model => model; + + readonly DynamicMethod method; + static int next; + + internal CodeLabel DefineLabel() + { + CodeLabel result = new CodeLabel(il.DefineLabel(), nextLabel++); + return result; + } +#if DEBUG_COMPILE + static readonly string traceCompilePath; + static CompilerContext() + { + traceCompilePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), + "TraceCompile.txt"); + Console.WriteLine("DEBUG_COMPILE enabled; writing to " + traceCompilePath); + } +#endif + [System.Diagnostics.Conditional("DEBUG_COMPILE")] + private void TraceCompile(string value) + { +#if DEBUG_COMPILE + if (!string.IsNullOrWhiteSpace(value)) + { + using (System.IO.StreamWriter sw = System.IO.File.AppendText(traceCompilePath)) + { + sw.WriteLine(value); + } + } +#endif + } + internal void MarkLabel(CodeLabel label) + { + il.MarkLabel(label.Value); + TraceCompile("#: " + label.Index); + } + + public static ProtoSerializer BuildSerializer(IProtoSerializer head, TypeModel model) + { + Type type = head.ExpectedType; + try + { + CompilerContext ctx = new CompilerContext(type, true, true, model, typeof(object)); + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.WriteNullCheckedTail(type, head, null); + ctx.Emit(OpCodes.Ret); + return (ProtoSerializer)ctx.method.CreateDelegate( + typeof(ProtoSerializer)); + } + catch (Exception ex) + { + string name = type.FullName; + if (string.IsNullOrEmpty(name)) name = type.Name; + throw new InvalidOperationException("It was not possible to prepare a serializer for: " + name, ex); + } + } + /*public static ProtoCallback BuildCallback(IProtoTypeSerializer head) + { + Type type = head.ExpectedType; + CompilerContext ctx = new CompilerContext(type, true, true); + using (Local typedVal = new Local(ctx, type)) + { + ctx.LoadValue(Local.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + CodeLabel[] jumpTable = new CodeLabel[4]; + for(int i = 0 ; i < jumpTable.Length ; i++) { + jumpTable[i] = ctx.DefineLabel(); + } + ctx.LoadReaderWriter(); + ctx.Switch(jumpTable); + ctx.Return(); + for(int i = 0 ; i < jumpTable.Length ; i++) { + ctx.MarkLabel(jumpTable[i]); + if (head.HasCallbacks((TypeModel.CallbackType)i)) + { + head.EmitCallback(ctx, typedVal, (TypeModel.CallbackType)i); + } + ctx.Return(); + } + } + + ctx.Emit(OpCodes.Ret); + return (ProtoCallback)ctx.method.CreateDelegate( + typeof(ProtoCallback)); + }*/ + public static ProtoDeserializer BuildDeserializer(IProtoSerializer head, TypeModel model) + { + Type type = head.ExpectedType; + CompilerContext ctx = new CompilerContext(type, false, true, model, typeof(object)); + + using (Local typedVal = new Local(ctx, type)) + { + if (!Helpers.IsValueType(type)) + { + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + } + else + { + ctx.LoadValue(ctx.InputValue); + CodeLabel notNull = ctx.DefineLabel(), endNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + + ctx.LoadAddress(typedVal, type); + ctx.EmitCtor(type); + ctx.Branch(endNull, true); + + ctx.MarkLabel(notNull); + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + + ctx.MarkLabel(endNull); + } + head.EmitRead(ctx, typedVal); + + if (head.ReturnsValue) + { + ctx.StoreValue(typedVal); + } + + ctx.LoadValue(typedVal); + ctx.CastToObject(type); + } + ctx.Emit(OpCodes.Ret); + return (ProtoDeserializer)ctx.method.CreateDelegate( + typeof(ProtoDeserializer)); + } + + internal void Return() + { + Emit(OpCodes.Ret); + } + + static bool IsObject(Type type) + { + return type == typeof(object); + } + + internal void CastToObject(Type type) + { + if (IsObject(type)) + { } + else if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Box, type); + TraceCompile(OpCodes.Box + ": " + type); + } + else + { + il.Emit(OpCodes.Castclass, MapType(typeof(object))); + TraceCompile(OpCodes.Castclass + ": " + type); + } + } + + internal void CastFromObject(Type type) + { + if (IsObject(type)) + { } + else if (Helpers.IsValueType(type)) + { + switch (MetadataVersion) + { + case ILVersion.Net1: + il.Emit(OpCodes.Unbox, type); + il.Emit(OpCodes.Ldobj, type); + TraceCompile(OpCodes.Unbox + ": " + type); + TraceCompile(OpCodes.Ldobj + ": " + type); + break; + default: + + il.Emit(OpCodes.Unbox_Any, type); + TraceCompile(OpCodes.Unbox_Any + ": " + type); + break; + } + } + else + { + il.Emit(OpCodes.Castclass, type); + TraceCompile(OpCodes.Castclass + ": " + type); + } + } + private readonly bool isStatic; + private readonly RuntimeTypeModel.SerializerPair[] methodPairs; + + internal MethodBuilder GetDedicatedMethod(int metaKey, bool read) + { + if (methodPairs == null) return null; + // but if we *do* have pairs, we demand that we find a match... + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) { return read ? methodPairs[i].Deserialize : methodPairs[i].Serialize; } + } + throw new ArgumentException("Meta-key not found", "metaKey"); + } + + internal int MapMetaKeyToCompiledKey(int metaKey) + { + if (metaKey < 0 || methodPairs == null) return metaKey; // all meta, or a dummy/wildcard key + + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) return i; + } + throw new ArgumentException("Key could not be mapped: " + metaKey.ToString(), "metaKey"); + } + + + private readonly bool isWriter; + + private readonly bool nonPublic; + internal bool NonPublic { get { return nonPublic; } } + + private readonly Local inputValue; + public Local InputValue { get { return inputValue; } } + + private readonly string assemblyName; + internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs, TypeModel model, ILVersion metadataVersion, string assemblyName, Type inputType, string traceName) + { + if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException(nameof(assemblyName)); + this.assemblyName = assemblyName; + this.isStatic = isStatic; + this.methodPairs = methodPairs ?? throw new ArgumentNullException(nameof(methodPairs)); + this.il = il ?? throw new ArgumentNullException(nameof(il)); + // nonPublic = false; <== implicit + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.metadataVersion = metadataVersion; + if (inputType != null) this.inputValue = new Local(null, inputType); + TraceCompile(">> " + traceName); + } + + private CompilerContext(Type associatedType, bool isWriter, bool isStatic, TypeModel model, Type inputType) + { + metadataVersion = ILVersion.Net2; + this.isStatic = isStatic; + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException(nameof(model)); + nonPublic = true; + Type[] paramTypes; + Type returnType; + if (isWriter) + { + returnType = typeof(void); + paramTypes = new Type[] { typeof(object), typeof(ProtoWriter) }; + } + else + { + returnType = typeof(object); + paramTypes = new Type[] { typeof(object), typeof(ProtoReader) }; + } + int uniqueIdentifier; +#if PLAT_NO_INTERLOCKED + uniqueIdentifier = ++next; +#else + uniqueIdentifier = Interlocked.Increment(ref next); +#endif + method = new DynamicMethod("proto_" + uniqueIdentifier.ToString(), returnType, paramTypes, associatedType +#if COREFX + .GetTypeInfo() +#endif + .IsInterface ? typeof(object) : associatedType, true); + this.il = method.GetILGenerator(); + if (inputType != null) this.inputValue = new Local(null, inputType); + TraceCompile(">> " + method.Name); + } + + private readonly ILGenerator il; + + private void Emit(OpCode opcode) + { + il.Emit(opcode); + TraceCompile(opcode.ToString()); + } + + public void LoadValue(string value) + { + if (value == null) + { + LoadNullRef(); + } + else + { + il.Emit(OpCodes.Ldstr, value); + TraceCompile(OpCodes.Ldstr + ": " + value); + } + } + + public void LoadValue(float value) + { + il.Emit(OpCodes.Ldc_R4, value); + TraceCompile(OpCodes.Ldc_R4 + ": " + value); + } + + public void LoadValue(double value) + { + il.Emit(OpCodes.Ldc_R8, value); + TraceCompile(OpCodes.Ldc_R8 + ": " + value); + } + + public void LoadValue(long value) + { + il.Emit(OpCodes.Ldc_I8, value); + TraceCompile(OpCodes.Ldc_I8 + ": " + value); + } + + public void LoadValue(int value) + { + switch (value) + { + case 0: Emit(OpCodes.Ldc_I4_0); break; + case 1: Emit(OpCodes.Ldc_I4_1); break; + case 2: Emit(OpCodes.Ldc_I4_2); break; + case 3: Emit(OpCodes.Ldc_I4_3); break; + case 4: Emit(OpCodes.Ldc_I4_4); break; + case 5: Emit(OpCodes.Ldc_I4_5); break; + case 6: Emit(OpCodes.Ldc_I4_6); break; + case 7: Emit(OpCodes.Ldc_I4_7); break; + case 8: Emit(OpCodes.Ldc_I4_8); break; + case -1: Emit(OpCodes.Ldc_I4_M1); break; + default: + if (value >= -128 && value <= 127) + { + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + TraceCompile(OpCodes.Ldc_I4_S + ": " + value); + } + else + { + il.Emit(OpCodes.Ldc_I4, value); + TraceCompile(OpCodes.Ldc_I4 + ": " + value); + } + break; + + } + } + + MutableList locals = new MutableList(); + internal LocalBuilder GetFromPool(Type type) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + LocalBuilder item = (LocalBuilder)locals[i]; + if (item != null && item.LocalType == type) + { + locals[i] = null; // remove from pool + return item; + } + } + LocalBuilder result = il.DeclareLocal(type); + TraceCompile("$ " + result + ": " + type); + return result; + } + + // + internal void ReleaseToPool(LocalBuilder value) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + if (locals[i] == null) + { + locals[i] = value; // released into existing slot + return; + } + } + locals.Add(value); // create a new slot + } + + public void LoadReaderWriter() + { + Emit(isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2); + } + + public void StoreValue(Local local) + { + if (local == this.InputValue) + { + byte b = isStatic ? (byte)0 : (byte)1; + il.Emit(OpCodes.Starg_S, b); + TraceCompile(OpCodes.Starg_S + ": $" + b); + } + else + { + + switch (local.Value.LocalIndex) + { + case 0: Emit(OpCodes.Stloc_0); break; + case 1: Emit(OpCodes.Stloc_1); break; + case 2: Emit(OpCodes.Stloc_2); break; + case 3: Emit(OpCodes.Stloc_3); break; + default: + + OpCode code = UseShortForm(local) ? OpCodes.Stloc_S : OpCodes.Stloc; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + + break; + } + } + } + + public void LoadValue(Local local) + { + if (local == null) { /* nothing to do; top of stack */} + else if (local == this.InputValue) + { + Emit(isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); + } + else + { + + switch (local.Value.LocalIndex) + { + case 0: Emit(OpCodes.Ldloc_0); break; + case 1: Emit(OpCodes.Ldloc_1); break; + case 2: Emit(OpCodes.Ldloc_2); break; + case 3: Emit(OpCodes.Ldloc_3); break; + default: + + OpCode code = UseShortForm(local) ? OpCodes.Ldloc_S : OpCodes.Ldloc; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + + break; + } + } + } + + public Local GetLocalWithValue(Type type, Compiler.Local fromValue) + { + if (fromValue != null) + { + if (fromValue.Type == type) return fromValue.AsCopy(); + // otherwise, load onto the stack and let the default handling (below) deal with it + LoadValue(fromValue); + if (!Helpers.IsValueType(type) && (fromValue.Type == null || !type.IsAssignableFrom(fromValue.Type))) + { // need to cast + Cast(type); + } + } + // need to store the value from the stack + Local result = new Local(this, type); + StoreValue(result); + return result; + } + + internal void EmitBasicRead(string methodName, Type expectedType) + { + MethodInfo method = MapType(typeof(ProtoReader)).GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + if (method == null || method.ReturnType != expectedType + || method.GetParameters().Length != 0) throw new ArgumentException("methodName"); + LoadReaderWriter(); + EmitCall(method); + } + + internal void EmitBasicRead(Type helperType, string methodName, Type expectedType) + { + MethodInfo method = helperType.GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + if (method == null || method.ReturnType != expectedType + || method.GetParameters().Length != 1) throw new ArgumentException("methodName"); + LoadReaderWriter(); + EmitCall(method); + } + + internal void EmitBasicWrite(string methodName, Compiler.Local fromValue) + { + if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName"); + LoadValue(fromValue); + LoadReaderWriter(); + EmitCall(GetWriterMethod(methodName)); + } + + private MethodInfo GetWriterMethod(string methodName) + { + Type writerType = MapType(typeof(ProtoWriter)); + MethodInfo[] methods = writerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + foreach (MethodInfo method in methods) + { + if (method.Name != methodName) continue; + ParameterInfo[] pis = method.GetParameters(); + if (pis.Length == 2 && pis[1].ParameterType == writerType) return method; + } + throw new ArgumentException("No suitable method found for: " + methodName, "methodName"); + } + + internal void EmitWrite(Type helperType, string methodName, Compiler.Local valueFrom) + { + if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName"); + MethodInfo method = helperType.GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + if (method == null || method.ReturnType != MapType(typeof(void))) throw new ArgumentException("methodName"); + LoadValue(valueFrom); + LoadReaderWriter(); + EmitCall(method); + } + + public void EmitCall(MethodInfo method) { EmitCall(method, null); } + + public void EmitCall(MethodInfo method, Type targetType) + { + Helpers.DebugAssert(method != null); + MemberInfo member = method; + CheckAccessibility(ref member); + OpCode opcode; + if (method.IsStatic || Helpers.IsValueType(method.DeclaringType)) + { + opcode = OpCodes.Call; + } + else + { + opcode = OpCodes.Callvirt; + if (targetType != null && Helpers.IsValueType(targetType) && !Helpers.IsValueType(method.DeclaringType)) + { + Constrain(targetType); + } + } + il.EmitCall(opcode, method, null); + TraceCompile(opcode + ": " + method + " on " + method.DeclaringType + (targetType == null ? "" : (" via " + targetType))); + } + + /// + /// Pushes a null reference onto the stack. Note that this should only + /// be used to return a null (or set a variable to null); for null-tests + /// use BranchIfTrue / BranchIfFalse. + /// + public void LoadNullRef() + { + Emit(OpCodes.Ldnull); + } + + private int nextLabel; + + internal void WriteNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom) + { + if (Helpers.IsValueType(type)) + { + Type underlyingType = Helpers.GetUnderlyingType(type); + + if (underlyingType == null) + { // not a nullable T; can invoke directly + tail.EmitWrite(this, valueFrom); + } + else + { // nullable T; check HasValue + using (Compiler.Local valOrNull = GetLocalWithValue(type, valueFrom)) + { + LoadAddress(valOrNull, type); + LoadValue(type.GetProperty("HasValue")); + CodeLabel @end = DefineLabel(); + BranchIfFalse(@end, false); + LoadAddress(valOrNull, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + tail.EmitWrite(this, null); + MarkLabel(@end); + } + } + } + else + { // ref-type; do a null-check + LoadValue(valueFrom); + CopyValue(); + CodeLabel hasVal = DefineLabel(), @end = DefineLabel(); + BranchIfTrue(hasVal, true); + DiscardValue(); + Branch(@end, false); + MarkLabel(hasVal); + tail.EmitWrite(this, null); + MarkLabel(@end); + } + } + + internal void ReadNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom) + { + + Type underlyingType; + + if (Helpers.IsValueType(type) && (underlyingType = Helpers.GetUnderlyingType(type)) != null) + { + if (tail.RequiresOldValue) + { + // we expect the input value to be in valueFrom; need to unpack it from T? + using (Local loc = GetLocalWithValue(type, valueFrom)) + { + LoadAddress(loc, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + } + else + { + Helpers.DebugAssert(valueFrom == null); // not expecting a valueFrom in this case + } + tail.EmitRead(this, null); // either unwrapped on the stack or not provided + if (tail.ReturnsValue) + { + // now re-wrap the value + EmitCtor(type, underlyingType); + } + return; + } + + // either a ref-type of a non-nullable struct; treat "as is", even if null + // (the type-serializer will handle the null case; it needs to allow null + // inputs to perform the correct type of subclass creation) + tail.EmitRead(this, valueFrom); + } + + public void EmitCtor(Type type) + { + EmitCtor(type, Helpers.EmptyTypes); + } + + public void EmitCtor(ConstructorInfo ctor) + { + if (ctor == null) throw new ArgumentNullException("ctor"); + MemberInfo ctorMember = ctor; + CheckAccessibility(ref ctorMember); + il.Emit(OpCodes.Newobj, ctor); + TraceCompile(OpCodes.Newobj + ": " + ctor.DeclaringType); + } + + public void InitLocal(Type type, Compiler.Local target) + { + LoadAddress(target, type, evenIfClass: true); // for class, initobj is a load-null, store-indirect + il.Emit(OpCodes.Initobj, type); + TraceCompile(OpCodes.Initobj + ": " + type); + } + + public void EmitCtor(Type type, params Type[] parameterTypes) + { + Helpers.DebugAssert(type != null); + Helpers.DebugAssert(parameterTypes != null); + if (Helpers.IsValueType(type) && parameterTypes.Length == 0) + { + il.Emit(OpCodes.Initobj, type); + TraceCompile(OpCodes.Initobj + ": " + type); + } + else + { + ConstructorInfo ctor = Helpers.GetConstructor(type +#if COREFX + .GetTypeInfo() +#endif + , parameterTypes, true); + if (ctor == null) throw new InvalidOperationException("No suitable constructor found for " + type.FullName); + EmitCtor(ctor); + } + } + + BasicList knownTrustedAssemblies, knownUntrustedAssemblies; + + bool InternalsVisible(Assembly assembly) + { + if (string.IsNullOrEmpty(assemblyName)) return false; + if (knownTrustedAssemblies != null) + { + if (knownTrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return true; + } + } + if (knownUntrustedAssemblies != null) + { + if (knownUntrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return false; + } + } + bool isTrusted = false; + Type attributeType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute)); + if (attributeType == null) return false; + +#if COREFX + foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType)) +#else + foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType, false)) +#endif + { + if (attrib.AssemblyName == assemblyName || attrib.AssemblyName.StartsWith(assemblyName + ",")) + { + isTrusted = true; + break; + } + } + + if (isTrusted) + { + if (knownTrustedAssemblies == null) knownTrustedAssemblies = new BasicList(); + knownTrustedAssemblies.Add(assembly); + } + else + { + if (knownUntrustedAssemblies == null) knownUntrustedAssemblies = new BasicList(); + knownUntrustedAssemblies.Add(assembly); + } + return isTrusted; + } + + internal void CheckAccessibility(ref MemberInfo member) + { + if (member == null) + { + throw new ArgumentNullException(nameof(member)); + } +#if !COREFX + Type type; +#endif + if (!NonPublic) + { + if (member is FieldInfo && member.Name.StartsWith("<") & member.Name.EndsWith(">k__BackingField")) + { + var propName = member.Name.Substring(1, member.Name.Length - 17); + var prop = member.DeclaringType.GetProperty(propName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + if (prop != null) member = prop; + } + bool isPublic; +#if COREFX + if (member is TypeInfo) + { + TypeInfo ti = (TypeInfo)member; + do + { + isPublic = ti.IsNestedPublic || ti.IsPublic || ((ti.IsNested || ti.IsNestedAssembly || ti.IsNestedFamORAssem) && InternalsVisible(ti.Assembly)); + } while (isPublic && ti.IsNested && (ti = ti.DeclaringType.GetTypeInfo()) != null); + } + else if (member is FieldInfo) + { + FieldInfo field = ((FieldInfo)member); + isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(field.DeclaringType))); + } + else if (member is PropertyInfo) + { + isPublic = true; // defer to get/set + } + else if (member is ConstructorInfo) + { + ConstructorInfo ctor = ((ConstructorInfo)member); + isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(ctor.DeclaringType))); + } + else if (member is MethodInfo) + { + MethodInfo method = ((MethodInfo)member); + isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(method.DeclaringType))); + if (!isPublic) + { + // allow calls to TypeModel protected methods, and methods we are in the process of creating + if ( + member is MethodBuilder || + member.DeclaringType == MapType(typeof(TypeModel))) + isPublic = true; + } + } + else + { + throw new NotSupportedException(member.GetType().Name); + } +#else + MemberTypes memberType = member.MemberType; + switch (memberType) + { + case MemberTypes.TypeInfo: + // top-level type + type = (Type)member; + isPublic = type.IsPublic || InternalsVisible(type.Assembly); + break; + case MemberTypes.NestedType: + type = (Type)member; + do + { + isPublic = type.IsNestedPublic || type.IsPublic || ((type.DeclaringType == null || type.IsNestedAssembly || type.IsNestedFamORAssem) && InternalsVisible(type.Assembly)); + } while (isPublic && (type = type.DeclaringType) != null); // ^^^ !type.IsNested, but not all runtimes have that + break; + case MemberTypes.Field: + FieldInfo field = ((FieldInfo)member); + isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(field.DeclaringType.Assembly)); + break; + case MemberTypes.Constructor: + ConstructorInfo ctor = ((ConstructorInfo)member); + isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(ctor.DeclaringType.Assembly)); + break; + case MemberTypes.Method: + MethodInfo method = ((MethodInfo)member); + isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(method.DeclaringType.Assembly)); + if (!isPublic) + { + // allow calls to TypeModel protected methods, and methods we are in the process of creating + if ( + member is MethodBuilder || + member.DeclaringType == MapType(typeof(TypeModel))) isPublic = true; + } + break; + case MemberTypes.Property: + isPublic = true; // defer to get/set + break; + default: + throw new NotSupportedException(memberType.ToString()); + } +#endif + if (!isPublic) + { +#if COREFX + if (member is TypeInfo) + { + throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + + ((TypeInfo)member).FullName); + } + else + { + throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + + member.DeclaringType.FullName + "." + member.Name); + } + +#else + switch (memberType) + { + case MemberTypes.TypeInfo: + case MemberTypes.NestedType: + throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + + ((Type)member).FullName); + default: + throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + + member.DeclaringType.FullName + "." + member.Name); + } +#endif + + } + } + } + + public void LoadValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + LoadValue((PropertyInfo)member); + } + else + { + OpCode code = field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld; + il.Emit(code, field); + TraceCompile(code + ": " + field + " on " + field.DeclaringType); + } + } + + public void StoreValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + StoreValue((PropertyInfo)member); + } + else + { + OpCode code = field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld; + il.Emit(code, field); + TraceCompile(code + ": " + field + " on " + field.DeclaringType); + } + } + + public void LoadValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetGetMethod(property, true, true)); + } + + public void StoreValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetSetMethod(property, true, true)); + } + + //internal void EmitInstance() + //{ + // if (isStatic) throw new InvalidOperationException(); + // Emit(OpCodes.Ldarg_0); + //} + + internal static void LoadValue(ILGenerator il, int value) + { + switch (value) + { + case 0: il.Emit(OpCodes.Ldc_I4_0); break; + case 1: il.Emit(OpCodes.Ldc_I4_1); break; + case 2: il.Emit(OpCodes.Ldc_I4_2); break; + case 3: il.Emit(OpCodes.Ldc_I4_3); break; + case 4: il.Emit(OpCodes.Ldc_I4_4); break; + case 5: il.Emit(OpCodes.Ldc_I4_5); break; + case 6: il.Emit(OpCodes.Ldc_I4_6); break; + case 7: il.Emit(OpCodes.Ldc_I4_7); break; + case 8: il.Emit(OpCodes.Ldc_I4_8); break; + case -1: il.Emit(OpCodes.Ldc_I4_M1); break; + default: il.Emit(OpCodes.Ldc_I4, value); break; + } + } + + private bool UseShortForm(Local local) + { + return local.Value.LocalIndex < 256; + } + + internal void LoadAddress(Local local, Type type, bool evenIfClass = false) + { + if (evenIfClass || Helpers.IsValueType(type)) + { + if (local == null) + { + throw new InvalidOperationException("Cannot load the address of the head of the stack"); + } + + if (local == this.InputValue) + { + il.Emit(OpCodes.Ldarga_S, (isStatic ? (byte)0 : (byte)1)); + TraceCompile(OpCodes.Ldarga_S + ": $" + (isStatic ? 0 : 1)); + } + else + { + OpCode code = UseShortForm(local) ? OpCodes.Ldloca_S : OpCodes.Ldloca; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + } + + } + else + { // reference-type; already *is* the address; just load it + LoadValue(local); + } + } + + internal void Branch(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Br_S : OpCodes.Br; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfFalse(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Brfalse_S : OpCodes.Brfalse; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfTrue(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Brtrue_S : OpCodes.Brtrue; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfEqual(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Beq_S : OpCodes.Beq; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + //internal void TestEqual() + //{ + // Emit(OpCodes.Ceq); + //} + + internal void CopyValue() + { + Emit(OpCodes.Dup); + } + + internal void BranchIfGreater(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Bgt_S : OpCodes.Bgt; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfLess(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Blt_S : OpCodes.Blt; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void DiscardValue() + { + Emit(OpCodes.Pop); + } + + public void Subtract() + { + Emit(OpCodes.Sub); + } + + public void Switch(CodeLabel[] jumpTable) + { + const int MAX_JUMPS = 128; + + if (jumpTable.Length <= MAX_JUMPS) + { + // simple case + Label[] labels = new Label[jumpTable.Length]; + for (int i = 0; i < labels.Length; i++) + { + labels[i] = jumpTable[i].Value; + } + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, labels); + } + else + { + // too many to jump easily (especially on Android) - need to split up (note: uses a local pulled from the stack) + using (Local val = GetLocalWithValue(MapType(typeof(int)), null)) + { + int count = jumpTable.Length, offset = 0; + int blockCount = count / MAX_JUMPS; + if ((count % MAX_JUMPS) != 0) blockCount++; + + Label[] blockLabels = new Label[blockCount]; + for (int i = 0; i < blockCount; i++) + { + blockLabels[i] = il.DefineLabel(); + } + CodeLabel endOfSwitch = DefineLabel(); + + LoadValue(val); + LoadValue(MAX_JUMPS); + Emit(OpCodes.Div); + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, blockLabels); + Branch(endOfSwitch, false); + + Label[] innerLabels = new Label[MAX_JUMPS]; + for (int blockIndex = 0; blockIndex < blockCount; blockIndex++) + { + il.MarkLabel(blockLabels[blockIndex]); + + int itemsThisBlock = Math.Min(MAX_JUMPS, count); + count -= itemsThisBlock; + if (innerLabels.Length != itemsThisBlock) innerLabels = new Label[itemsThisBlock]; + + int subtract = offset; + for (int j = 0; j < itemsThisBlock; j++) + { + innerLabels[j] = jumpTable[offset++].Value; + } + LoadValue(val); + if (subtract != 0) // switches are always zero-based + { + LoadValue(subtract); + Emit(OpCodes.Sub); + } + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, innerLabels); + if (count != 0) + { // force default to the very bottom + Branch(endOfSwitch, false); + } + } + Helpers.DebugAssert(count == 0, "Should use exactly all switch items"); + MarkLabel(endOfSwitch); + } + } + } + + internal void EndFinally() + { + il.EndExceptionBlock(); + TraceCompile("EndExceptionBlock"); + } + + internal void BeginFinally() + { + il.BeginFinallyBlock(); + TraceCompile("BeginFinallyBlock"); + } + + internal void EndTry(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Leave_S : OpCodes.Leave; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal CodeLabel BeginTry() + { + CodeLabel label = new CodeLabel(il.BeginExceptionBlock(), nextLabel++); + TraceCompile("BeginExceptionBlock: " + label.Index); + return label; + } + + internal void Constrain(Type type) + { + il.Emit(OpCodes.Constrained, type); + TraceCompile(OpCodes.Constrained + ": " + type); + } + + internal void TryCast(Type type) + { + il.Emit(OpCodes.Isinst, type); + TraceCompile(OpCodes.Isinst + ": " + type); + } + + internal void Cast(Type type) + { + il.Emit(OpCodes.Castclass, type); + TraceCompile(OpCodes.Castclass + ": " + type); + } + + public IDisposable Using(Local local) + { + return new UsingBlock(this, local); + } + + private sealed class UsingBlock : IDisposable + { + private Local local; + CompilerContext ctx; + CodeLabel label; + /// + /// Creates a new "using" block (equivalent) around a variable; + /// the variable must exist, and note that (unlike in C#) it is + /// the variables *final* value that gets disposed. If you need + /// *original* disposal, copy your variable first. + /// + /// It is the callers responsibility to ensure that the variable's + /// scope fully-encapsulates the "using"; if not, the variable + /// may be re-used (and thus re-assigned) unexpectedly. + /// + public UsingBlock(CompilerContext ctx, Local local) + { + if (ctx == null) throw new ArgumentNullException("ctx"); + if (local == null) throw new ArgumentNullException("local"); + + Type type = local.Type; + // check if **never** disposable + if ((Helpers.IsValueType(type) || Helpers.IsSealed(type)) && + !ctx.MapType(typeof(IDisposable)).IsAssignableFrom(type)) + { + return; // nothing to do! easiest "using" block ever + // (note that C# wouldn't allow this as a "using" block, + // but we'll be generous and simply not do anything) + } + this.local = local; + this.ctx = ctx; + label = ctx.BeginTry(); + + } + public void Dispose() + { + if (local == null || ctx == null) return; + + ctx.EndTry(label, false); + ctx.BeginFinally(); + Type disposableType = ctx.MapType(typeof(IDisposable)); + MethodInfo dispose = disposableType.GetMethod("Dispose"); + Type type = local.Type; + // remember that we've already (in the .ctor) excluded the case + // where it *cannot* be disposable + if (Helpers.IsValueType(type)) + { + ctx.LoadAddress(local, type); + switch (ctx.MetadataVersion) + { + case ILVersion.Net1: + ctx.LoadValue(local); + ctx.CastToObject(type); + break; + default: + ctx.Constrain(type); + break; + } + ctx.EmitCall(dispose); + } + else + { + Compiler.CodeLabel @null = ctx.DefineLabel(); + if (disposableType.IsAssignableFrom(type)) + { // *known* to be IDisposable; just needs a null-check + ctx.LoadValue(local); + ctx.BranchIfFalse(@null, true); + ctx.LoadAddress(local, type); + } + else + { // *could* be IDisposable; test via "as" + using (Compiler.Local disp = new Compiler.Local(ctx, disposableType)) + { + ctx.LoadValue(local); + ctx.TryCast(disposableType); + ctx.CopyValue(); + ctx.StoreValue(disp); + ctx.BranchIfFalse(@null, true); + ctx.LoadAddress(disp, disposableType); + } + } + ctx.EmitCall(dispose); + ctx.MarkLabel(@null); + } + ctx.EndFinally(); + this.local = null; + this.ctx = null; + label = new CodeLabel(); // default + } + } + + internal void Add() + { + Emit(OpCodes.Add); + } + + internal void LoadLength(Local arr, bool zeroIfNull) + { + Helpers.DebugAssert(arr.Type.IsArray && arr.Type.GetArrayRank() == 1); + + if (zeroIfNull) + { + Compiler.CodeLabel notNull = DefineLabel(), done = DefineLabel(); + LoadValue(arr); + CopyValue(); // optimised for non-null case + BranchIfTrue(notNull, true); + DiscardValue(); + LoadValue(0); + Branch(done, true); + MarkLabel(notNull); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + MarkLabel(done); + } + else + { + LoadValue(arr); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + } + } + + internal void CreateArray(Type elementType, Local length) + { + LoadValue(length); + il.Emit(OpCodes.Newarr, elementType); + TraceCompile(OpCodes.Newarr + ": " + elementType); + } + + internal void LoadArrayValue(Local arr, Local i) + { + Type type = arr.Type; + Helpers.DebugAssert(type.IsArray && arr.Type.GetArrayRank() == 1); + type = type.GetElementType(); + Helpers.DebugAssert(type != null, "Not an array: " + arr.Type.FullName); + LoadValue(arr); + LoadValue(i); + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.SByte: Emit(OpCodes.Ldelem_I1); break; + case ProtoTypeCode.Int16: Emit(OpCodes.Ldelem_I2); break; + case ProtoTypeCode.Int32: Emit(OpCodes.Ldelem_I4); break; + case ProtoTypeCode.Int64: Emit(OpCodes.Ldelem_I8); break; + + case ProtoTypeCode.Byte: Emit(OpCodes.Ldelem_U1); break; + case ProtoTypeCode.UInt16: Emit(OpCodes.Ldelem_U2); break; + case ProtoTypeCode.UInt32: Emit(OpCodes.Ldelem_U4); break; + case ProtoTypeCode.UInt64: Emit(OpCodes.Ldelem_I8); break; // odd, but this is what C# does... + + case ProtoTypeCode.Single: Emit(OpCodes.Ldelem_R4); break; + case ProtoTypeCode.Double: Emit(OpCodes.Ldelem_R8); break; + default: + if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Ldelema, type); + il.Emit(OpCodes.Ldobj, type); + TraceCompile(OpCodes.Ldelema + ": " + type); + TraceCompile(OpCodes.Ldobj + ": " + type); + } + else + { + Emit(OpCodes.Ldelem_Ref); + } + + break; + } + } + + internal void LoadValue(Type type) + { + il.Emit(OpCodes.Ldtoken, type); + TraceCompile(OpCodes.Ldtoken + ": " + type); + EmitCall(MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle")); + } + + internal void ConvertToInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.Byte: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.UInt16: + Emit(OpCodes.Conv_I4); + break; + case ProtoTypeCode.Int32: + break; + case ProtoTypeCode.Int64: + Emit(OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt32: + Emit(uint32Overflow ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt64: + Emit(OpCodes.Conv_Ovf_I4_Un); + break; + default: + throw new InvalidOperationException("ConvertToInt32 not implemented for: " + typeCode.ToString()); + } + } + + internal void ConvertFromInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.SByte: Emit(OpCodes.Conv_Ovf_I1); break; + case ProtoTypeCode.Byte: Emit(OpCodes.Conv_Ovf_U1); break; + case ProtoTypeCode.Int16: Emit(OpCodes.Conv_Ovf_I2); break; + case ProtoTypeCode.UInt16: Emit(OpCodes.Conv_Ovf_U2); break; + case ProtoTypeCode.Int32: break; + case ProtoTypeCode.UInt32: Emit(uint32Overflow ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); break; + case ProtoTypeCode.Int64: Emit(OpCodes.Conv_I8); break; + case ProtoTypeCode.UInt64: Emit(OpCodes.Conv_U8); break; + default: throw new InvalidOperationException(); + } + } + + internal void LoadValue(decimal value) + { + if (value == 0M) + { + LoadValue(typeof(decimal).GetField("Zero")); + } + else + { + int[] bits = decimal.GetBits(value); + LoadValue(bits[0]); // lo + LoadValue(bits[1]); // mid + LoadValue(bits[2]); // hi + LoadValue((int)(((uint)bits[3]) >> 31)); // isNegative (bool, but int for CLI purposes) + LoadValue((bits[3] >> 16) & 0xFF); // scale (byte, but int for CLI purposes) + + EmitCtor(MapType(typeof(decimal)), new Type[] { MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(bool)), MapType(typeof(byte)) }); + } + } + + internal void LoadValue(Guid value) + { + if (value == Guid.Empty) + { + LoadValue(typeof(Guid).GetField("Empty")); + } + else + { // note we're adding lots of shorts/bytes here - but at the IL level they are I4, not I1/I2 (which barely exist) + byte[] bytes = value.ToByteArray(); + int i = (bytes[0]) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); + LoadValue(i); + short s = (short)((bytes[4]) | (bytes[5] << 8)); + LoadValue(s); + s = (short)((bytes[6]) | (bytes[7] << 8)); + LoadValue(s); + for (i = 8; i <= 15; i++) + { + LoadValue(bytes[i]); + } + EmitCtor(MapType(typeof(Guid)), new Type[] { MapType(typeof(int)), MapType(typeof(short)), MapType(typeof(short)), + MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)) }); + } + } + + //internal void LoadValue(bool value) + //{ + // Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + //} + + internal void LoadSerializationContext() + { + LoadReaderWriter(); + LoadValue((isWriter ? typeof(ProtoWriter) : typeof(ProtoReader)).GetProperty("Context")); + } + + private readonly TypeModel model; + + internal Type MapType(Type type) + { + return model.MapType(type); + } + + private readonly ILVersion metadataVersion; + public ILVersion MetadataVersion { get { return metadataVersion; } } + public enum ILVersion + { + Net1, Net2 + } + + internal bool AllowInternal(PropertyInfo property) + { + return NonPublic ? true : InternalsVisible(Helpers.GetAssembly(property.DeclaringType)); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta new file mode 100644 index 0000000..2ca53a4 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfc4de6c372641f4ab45618478a6c733 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs new file mode 100644 index 0000000..e7f0508 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs @@ -0,0 +1,7 @@ +#if FEAT_COMPILER +namespace ProtoBuf.Compiler +{ + internal delegate void ProtoSerializer(object value, ProtoWriter dest); + internal delegate object ProtoDeserializer(object value, ProtoReader source); +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta new file mode 100644 index 0000000..fc1d56e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ea97fb7a1f52904d93e4c583e4672d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs new file mode 100644 index 0000000..fd3dfa9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs @@ -0,0 +1,58 @@ +#if FEAT_COMPILER +using System; +using System.Reflection.Emit; + +namespace ProtoBuf.Compiler +{ + internal sealed class Local : IDisposable + { + // public static readonly Local InputValue = new Local(null, null); + private LocalBuilder value; + private readonly Type type; + private CompilerContext ctx; + + private Local(LocalBuilder value, Type type) + { + this.value = value; + this.type = type; + } + + internal Local(CompilerContext ctx, Type type) + { + this.ctx = ctx; + if (ctx != null) { value = ctx.GetFromPool(type); } + this.type = type; + } + + internal LocalBuilder Value => value ?? throw new ObjectDisposedException(GetType().Name); + + public Type Type => type; + + public Local AsCopy() + { + if (ctx == null) return this; // can re-use if context-free + return new Local(value, this.type); + } + + public void Dispose() + { + if (ctx != null) + { + // only *actually* dispose if this is context-bound; note that non-bound + // objects are cheekily re-used, and *must* be left intact agter a "using" etc + ctx.ReleaseToPool(value); + value = null; + ctx = null; + } + } + + internal bool IsSame(Local other) + { + if((object)this == (object)other) return true; + + object ourVal = value; // use prop to ensure obj-disposed etc + return other != null && ourVal == (object)(other.value); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs.meta new file mode 100644 index 0000000..b0f6caf --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Compiler/Local.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e94b0a61fe7b6349b60d327967464e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs new file mode 100644 index 0000000..4d97b4f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs @@ -0,0 +1,49 @@ + +namespace ProtoBuf +{ + /// + /// Sub-format to use when serializing/deserializing data + /// + public enum DataFormat + { + /// + /// Uses the default encoding for the data-type. + /// + Default, + + /// + /// When applied to signed integer-based data (including Decimal), this + /// indicates that zigzag variant encoding will be used. This means that values + /// with small magnitude (regardless of sign) take a small amount + /// of space to encode. + /// + ZigZag, + + /// + /// When applied to signed integer-based data (including Decimal), this + /// indicates that two's-complement variant encoding will be used. + /// This means that any -ve number will take 10 bytes (even for 32-bit), + /// so should only be used for compatibility. + /// + TwosComplement, + + /// + /// When applied to signed integer-based data (including Decimal), this + /// indicates that a fixed amount of space will be used. + /// + FixedSize, + + /// + /// When applied to a sub-message, indicates that the value should be treated + /// as group-delimited. + /// + Group, + + /// + /// When applied to members of types such as DateTime or TimeSpan, specifies + /// that the "well known" standardized representation should be use; DateTime uses Timestamp, + /// + /// + WellKnown + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs.meta new file mode 100644 index 0000000..59f18ee --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DataFormat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e874dd5b56bb8e74292037e26e2ce21b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs new file mode 100644 index 0000000..0fd671f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs @@ -0,0 +1,176 @@ +#if PLAT_BINARYFORMATTER +using System; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; + +namespace ProtoBuf +{ + [Serializable] + public readonly partial struct DiscriminatedUnionObject : ISerializable + { + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (Discriminator != default) info.AddValue("d", Discriminator); + if (Object is object) info.AddValue("o", Object); + } + private DiscriminatedUnionObject(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": Discriminator = (int)field.Value; break; + case "o": Object = field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion128Object : ISerializable + { + [FieldOffset(8)] private readonly long _lo; + [FieldOffset(16)] private readonly long _hi; + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (_lo != default) info.AddValue("l", _lo); + if (_hi != default) info.AddValue("h", _hi); + if (Object != null) info.AddValue("o", Object); + } + private DiscriminatedUnion128Object(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "l": _lo = (long)field.Value; break; + case "h": _hi = (long)field.Value; break; + case "o": Object = field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion128 : ISerializable + { + [FieldOffset(8)] private readonly long _lo; + [FieldOffset(16)] private readonly long _hi; + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (_lo != default) info.AddValue("l", _lo); + if (_hi != default) info.AddValue("h", _hi); + } + private DiscriminatedUnion128(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "l": _lo = (long)field.Value; break; + case "h": _hi = (long)field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion64 : ISerializable + { + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (Int64 != default) info.AddValue("i", Int64); + } + private DiscriminatedUnion64(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "i": Int64 = (long)field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion64Object : ISerializable + { + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (Int64 != default) info.AddValue("i", Int64); + if (Object is object) info.AddValue("o", Object); + } + private DiscriminatedUnion64Object(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "i": Int64 = (long)field.Value; break; + case "o": Object = field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion32 : ISerializable + { + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (Int32 != default) info.AddValue("i", Int32); + } + private DiscriminatedUnion32(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "i": Int32 = (int)field.Value; break; + } + } + } + } + + [Serializable] + public readonly partial struct DiscriminatedUnion32Object : ISerializable + { + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_discriminator != default) info.AddValue("d", _discriminator); + if (Int32 != default) info.AddValue("i", Int32); + if (Object is object) info.AddValue("o", Object); + } + private DiscriminatedUnion32Object(SerializationInfo info, StreamingContext context) + { + this = default; + foreach (var field in info) + { + switch (field.Name) + { + case "d": _discriminator = (int)field.Value; break; + case "i": Int32 = (int)field.Value; break; + case "o": Object = field.Value; break; + } + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta new file mode 100644 index 0000000..7a54bb1 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cab97faadd2158a429014e3b42057d04 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs new file mode 100644 index 0000000..7cc8cf8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs @@ -0,0 +1,416 @@ +using System; +using System.Runtime.InteropServices; + +namespace ProtoBuf +{ + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + public readonly partial struct DiscriminatedUnionObject + { + + /// The value typed as Object + public readonly object Object; + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => Discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnionObject(int discriminator, object value) + { + Discriminator = discriminator; + Object = value; + } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnionObject value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + + /// The discriminator value + public int Discriminator { get; } + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion64 + { +#if !FEAT_SAFE + unsafe static DiscriminatedUnion64() + { + if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64)); + if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64)); + } +#endif + [FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + + private DiscriminatedUnion64(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion64 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion128Object + { +#if !FEAT_SAFE + unsafe static DiscriminatedUnion128Object() + { + if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object)); + if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object)); + if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128Object)); + } +#endif + + [FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Guid + [FieldOffset(8)] public readonly Guid Guid; + /// The value typed as Object + [FieldOffset(24)] public readonly object Object; + + private DiscriminatedUnion128Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion128Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion128 + { +#if !FEAT_SAFE + unsafe static DiscriminatedUnion128() + { + if (sizeof(DateTime) > 16) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128)); + if (sizeof(TimeSpan) > 16) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128)); + if (sizeof(Guid) > 16) throw new InvalidOperationException(nameof(Guid) + " was unexpectedly too big for " + nameof(DiscriminatedUnion128)); + } +#endif + [FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Guid + [FieldOffset(8)] public readonly Guid Guid; + + private DiscriminatedUnion128(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion128 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion64Object + { +#if !FEAT_SAFE + unsafe static DiscriminatedUnion64Object() + { + if (sizeof(DateTime) > 8) throw new InvalidOperationException(nameof(DateTime) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object)); + if (sizeof(TimeSpan) > 8) throw new InvalidOperationException(nameof(TimeSpan) + " was unexpectedly too big for " + nameof(DiscriminatedUnion64Object)); + } +#endif + [FieldOffset(0)] private readonly int _discriminator; // note that we can't pack further because Object needs x8 alignment/padding on x64 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Object + [FieldOffset(16)] public readonly object Object; + + private DiscriminatedUnion64Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion64Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion32 + { + [FieldOffset(0)] private readonly int _discriminator; + + /// The value typed as Int32 + [FieldOffset(4)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(4)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(4)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(4)] public readonly float Single; + + private DiscriminatedUnion32(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, bool value) : this(discriminator) { Boolean = value; } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion32 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// Represent multiple types as a union; this is used as part of OneOf - + /// note that it is the caller's responsbility to only read/write the value as the same type + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion32Object + { + [FieldOffset(0)] private readonly int _discriminator; + + /// The value typed as Int32 + [FieldOffset(4)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(4)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(4)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(4)] public readonly float Single; + /// The value typed as Object + [FieldOffset(8)] public readonly object Object; + + private DiscriminatedUnion32Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion32Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta new file mode 100644 index 0000000..aacd34e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 517d2a7f43de7c7419bece53f23a124e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs new file mode 100644 index 0000000..6bd528b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using ProtoBuf.Meta; +using System.Collections; + +namespace ProtoBuf +{ + /// + /// Simple base class for supporting unexpected fields allowing + /// for loss-less round-tips/merge, even if the data is not understod. + /// The additional fields are (by default) stored in-memory in a buffer. + /// + /// As an example of an alternative implementation, you might + /// choose to use the file system (temporary files) as the back-end, tracking + /// only the paths [such an object would ideally be IDisposable and use + /// a finalizer to ensure that the files are removed]. + /// + public abstract class Extensible : IExtensible + { + // note: not marked ProtoContract - no local state, and can't + // predict sub-classes + + private IExtension extensionObject; + + IExtension IExtensible.GetExtensionObject(bool createIfMissing) + { + return GetExtensionObject(createIfMissing); + } + + /// + /// Retrieves the extension object for the current + /// instance, optionally creating it if it does not already exist. + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + protected virtual IExtension GetExtensionObject(bool createIfMissing) + { + return GetExtensionObject(ref extensionObject, createIfMissing); + } + + /// + /// Provides a simple, default implementation for extension support, + /// optionally creating it if it does not already exist. Designed to be called by + /// classes implementing . + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension field to check (and possibly update). + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing) + { + if (createIfMissing && extensionObject == null) + { + extensionObject = new BufferExtension(); + } + return extensionObject; + } + +#if !NO_RUNTIME + /// + /// Appends the value as an additional (unexpected) data-field for the instance. + /// Note that for non-repeated sub-objects, this equates to a merge operation; + /// for repeated sub-objects this adds a new instance to the set; for simple + /// values the new value supercedes the old value. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The type of the value to append. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(IExtensible instance, int tag, TValue value) + { + AppendValue(instance, tag, DataFormat.Default, value); + } + + /// + /// Appends the value as an additional (unexpected) data-field for the instance. + /// Note that for non-repeated sub-objects, this equates to a merge operation; + /// for repeated sub-objects this adds a new instance to the set; for simple + /// values the new value supercedes the old value. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The data-type of the field. + /// The data-format to use when encoding the value. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(IExtensible instance, int tag, DataFormat format, TValue value) + { + ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value); + } + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned is the composed value after merging any duplicated content; if the + /// value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The effective value of the field, or the default value if not found. + public static TValue GetValue(IExtensible instance, int tag) + { + return GetValue(instance, tag, DataFormat.Default); + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned is the composed value after merging any duplicated content; if the + /// value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// The effective value of the field, or the default value if not found. + public static TValue GetValue(IExtensible instance, int tag, DataFormat format) + { + TryGetValue(instance, tag, format, out TValue value); + return value; + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned (in "value") is the composed value after merging any duplicated content; + /// if the value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, out TValue value) + { + return TryGetValue(instance, tag, DataFormat.Default, out value); + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned (in "value") is the composed value after merging any duplicated content; + /// if the value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, out TValue value) + { + return TryGetValue(instance, tag, format, false, out value); + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned (in "value") is the composed value after merging any duplicated content; + /// if the value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// Allow tags that are present as part of the definition; for example, to query unknown enum values. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value) + { + value = default; + bool set = false; + foreach (TValue val in ExtensibleUtil.GetExtendedValues(instance, tag, format, true, allowDefinedTag)) + { + // expecting at most one yield... + // but don't break; need to read entire stream + value = val; + set = true; + } + + return set; + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated" + /// (list) fields. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(IExtensible instance, int tag) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, DataFormat.Default, false, false); + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated" + /// (list) fields. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, format, false, false); + } +#endif + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// The value returned (in "value") is the composed value after merging any duplicated content; + /// if the value is "repeated" (a list), then use GetValues instead. + /// + /// The data-type of the field. + /// The model to use for configuration. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// Allow tags that are present as part of the definition; for example, to query unknown enum values. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out object value) + { + value = null; + bool set = false; + foreach (object val in ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, true, allowDefinedTag)) + { + // expecting at most one yield... + // but don't break; need to read entire stream + value = val; + set = true; + } + + return set; + } + + /// + /// Queries an extensible object for an additional (unexpected) data-field for the instance. + /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated" + /// (list) fields. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The model to use for configuration. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, false, false); + } + + /// + /// Appends the value as an additional (unexpected) data-field for the instance. + /// Note that for non-repeated sub-objects, this equates to a merge operation; + /// for repeated sub-objects this adds a new instance to the set; for simple + /// values the new value supercedes the old value. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The model to use for configuration. + /// The data-format to use when encoding the value. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) + { + ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs.meta new file mode 100644 index 0000000..53ecded --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Extensible.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f24ffac9f5da28a44afda868f42fbbd6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs new file mode 100644 index 0000000..9cc1613 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// This class acts as an internal wrapper allowing us to do a dynamic + /// methodinfo invoke; an't put into Serializer as don't want on public + /// API; can't put into Serializer<T> since we need to invoke + /// across classes + /// + internal static class ExtensibleUtil + { + +#if !NO_RUNTIME + /// + /// All this does is call GetExtendedValuesTyped with the correct type for "instance"; + /// this ensures that we don't get issues with subclasses declaring conflicting types - + /// the caller must respect the fields defined for the type they pass in. + /// + internal static IEnumerable GetExtendedValues(IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) + { + foreach (TValue value in GetExtendedValues(RuntimeTypeModel.Default, typeof(TValue), instance, tag, format, singleton, allowDefinedTag)) + { + yield return value; + } + } +#endif + /// + /// All this does is call GetExtendedValuesTyped with the correct type for "instance"; + /// this ensures that we don't get issues with subclasses declaring conflicting types - + /// the caller must respect the fields defined for the type they pass in. + /// + internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag)); + IExtension extn = instance.GetExtensionObject(false); + + if (extn == null) + { + yield break; + } + + Stream stream = extn.BeginQuery(); + object value = null; + ProtoReader reader = null; + try + { + SerializationContext ctx = new SerializationContext(); + reader = ProtoReader.Create(stream, model, ctx, ProtoReader.TO_EOF); + while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, true, true, false, false, null) && value != null) + { + if (!singleton) + { + yield return value; + + value = null; // fresh item each time + } + } + if (singleton && value != null) + { + yield return value; + } + } + finally + { + ProtoReader.Recycle(reader); + extn.EndQuery(stream); + } + } + + internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + if (value == null) throw new ArgumentNullException(nameof(value)); + + // TODO + //model.CheckTagNotInUse(tag); + + // obtain the extension object and prepare to write + IExtension extn = instance.GetExtensionObject(true); + if (extn == null) throw new InvalidOperationException("No extension object available; appended data would be lost."); + bool commit = false; + Stream stream = extn.BeginAppend(); + try + { + using (ProtoWriter writer = ProtoWriter.Create(stream, model, null)) + { + model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false, null); + writer.Close(); + } + commit = true; + } + finally + { + extn.EndAppend(stream, commit); + } + } + + // /// + // /// Stores the given value into the instance's stream; the serializer + // /// is inferred from TValue and format. + // /// + // /// Needs to be public to be callable thru reflection in Silverlight + // public static void AppendExtendValueTyped( + // TypeModel model, TSource instance, int tag, DataFormat format, TValue value) + // where TSource : class, IExtensible + // { + // AppendExtendValue(model, instance, tag, format, value); + // } + + } + +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta new file mode 100644 index 0000000..e18276c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12a113a3bff7cdc499bfc7aefdb182b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/GlobalSuppressions.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/GlobalSuppressions.cs new file mode 100644 index 0000000000000000000000000000000000000000..48b91900b51b472ffc30340fc102117033e243b7 GIT binary patch literal 2750 zcmeH|UuzRl5XI+N@H;H~q|l}cf>`jOR)juOgycoUhc(&!(PUGyyM=st^>=1^+06z; z1RpFVB)j*{+%sp+%-sC=er9Ku*~FH%vYNL!&$X4j#kys;v>EF!w&(ZKwyb2ou*wR2 z_jrVFgDtZSyDMzX-7~YXwRXd2$GMu%_1&|ug(E$-N3al&f>RBCE26c$$v@+{bc^i5 z&{KG8{DNCVmR~SYtgU^;I_31px(FW*ET^99Eq-fI>jBRd7?m?9!4-PR>CD;aOomk% zE7P6l(y-dPPhz^@qoyJayqv}lU8~dSL z@KOC!-PI+XwPW+U9*Z7oL2p1()El@*za@70QO9M2p3D7YQn=5xW0BjH^BZ<=QsNy^ zH7R*d(ab)=riIna6;*$zCo258F9Y#>`PRLn{iFFr}o*W{h=Z;>-~zv-7Fn- w$IrPdG#$- + /// Not all frameworks are created equal (fx1.1 vs fx2.0, + /// micro-framework, compact-framework, + /// silverlight, etc). This class simply wraps up a few things that would + /// otherwise make the real code unnecessarily messy, providing fallback + /// implementations if necessary. + /// + internal sealed class Helpers + { + private Helpers() { } + + public static StringBuilder AppendLine(StringBuilder builder) + { + return builder.AppendLine(); + } + + [System.Diagnostics.Conditional("DEBUG")] + public static void DebugWriteLine(string message, object obj) + { +#if DEBUG + string suffix; + try + { + suffix = obj == null ? "(null)" : obj.ToString(); + } + catch + { + suffix = "(exception)"; + } + DebugWriteLine(message + ": " + suffix); +#endif + } + [System.Diagnostics.Conditional("DEBUG")] + public static void DebugWriteLine(string message) + { +#if DEBUG + System.Diagnostics.Debug.WriteLine(message); +#endif + } + [System.Diagnostics.Conditional("TRACE")] + public static void TraceWriteLine(string message) + { +#if TRACE +#if CF2 || PORTABLE || COREFX || PROFILE259 + System.Diagnostics.Debug.WriteLine(message); +#else + System.Diagnostics.Trace.WriteLine(message); +#endif +#endif + } + + [System.Diagnostics.Conditional("DEBUG")] + public static void DebugAssert(bool condition, string message) + { +#if DEBUG + if (!condition) + { + System.Diagnostics.Debug.Assert(false, message); + } +#endif + } + [System.Diagnostics.Conditional("DEBUG")] + public static void DebugAssert(bool condition, string message, params object[] args) + { +#if DEBUG + if (!condition) DebugAssert(false, string.Format(message, args)); +#endif + } + [System.Diagnostics.Conditional("DEBUG")] + public static void DebugAssert(bool condition) + { +#if DEBUG + if (!condition && System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); + System.Diagnostics.Debug.Assert(condition); +#endif + } +#if !NO_RUNTIME + public static void Sort(int[] keys, object[] values) + { + // bubble-sort; it'll work on MF, has small code, + // and works well-enough for our sizes. This approach + // also allows us to do `int` compares without having + // to go via IComparable etc, so win:win + bool swapped; + do + { + swapped = false; + for (int i = 1; i < keys.Length; i++) + { + if (keys[i - 1] > keys[i]) + { + int tmpKey = keys[i]; + keys[i] = keys[i - 1]; + keys[i - 1] = tmpKey; + object tmpValue = values[i]; + values[i] = values[i - 1]; + values[i - 1] = tmpValue; + swapped = true; + } + } + } while (swapped); + } +#endif + +#if COREFX + internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name) + { + var members = declaringType.AsType().GetMember(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + switch(members.Length) + { + case 0: return null; + case 1: return members[0]; + default: throw new AmbiguousMatchException(name); + } + } + internal static MethodInfo GetInstanceMethod(Type declaringType, string name) + { + foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (method.Name == name) return method; + } + return null; + } + internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name) + { + return GetInstanceMethod(declaringType.AsType(), name); ; + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name) + { + foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (method.Name == name) return method; + } + return null; + } + + internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name) + { + return GetStaticMethod(declaringType.AsType(), name); + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes) + { + foreach(MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method; + } + return null; + } + internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes) + { + foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method; + } + return null; + } + internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types) + { + return GetInstanceMethod(declaringType.AsType(), name, types); + } +#elif PROFILE259 + internal static MemberInfo GetInstanceMember(TypeInfo declaringType, string name) + { + IEnumerable members = declaringType.DeclaredMembers; + IList found = new List(); + foreach (MemberInfo member in members) + { + if (member.Name.Equals(name)) + { + found.Add(member); + } + } + switch (found.Count) + { + case 0: return null; + case 1: return found.First(); + default: throw new AmbiguousMatchException(name); + } + } + internal static MethodInfo GetInstanceMethod(Type declaringType, string name) + { + var methods = declaringType.GetRuntimeMethods(); + foreach (MethodInfo method in methods) + { + if (method.Name == name) + { + return method; + } + } + return null; + } + internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name) + { + return GetInstanceMethod(declaringType.AsType(), name); ; + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name) + { + var methods = declaringType.GetRuntimeMethods(); + foreach (MethodInfo method in methods) + { + if (method.Name == name) + { + return method; + } + } + return null; + } + + internal static MethodInfo GetStaticMethod(TypeInfo declaringType, string name) + { + return GetStaticMethod(declaringType.AsType(), name); + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes) + { + var methods = declaringType.GetRuntimeMethods(); + foreach (MethodInfo method in methods) + { + if (method.Name == name && + IsMatch(method.GetParameters(), parameterTypes)) + { + return method; + } + } + return null; + } + internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] parameterTypes) + { + var methods = declaringType.GetRuntimeMethods(); + foreach (MethodInfo method in methods) + { + if (method.Name == name && + IsMatch(method.GetParameters(), parameterTypes)) + { + return method; + } + } + return null; + } + internal static MethodInfo GetInstanceMethod(TypeInfo declaringType, string name, Type[] types) + { + return GetInstanceMethod(declaringType.AsType(), name, types); + } +#else + internal static MethodInfo GetInstanceMethod(Type declaringType, string name) + { + return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name) + { + return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + } + internal static MethodInfo GetStaticMethod(Type declaringType, string name, Type[] parameterTypes) + { +#if PORTABLE + foreach (MethodInfo method in declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (method.Name == name && IsMatch(method.GetParameters(), parameterTypes)) return method; + } + return null; +#else + return declaringType.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null); +#endif + } + internal static MethodInfo GetInstanceMethod(Type declaringType, string name, Type[] types) + { + if (types == null) types = EmptyTypes; +#if PORTABLE || COREFX + MethodInfo method = declaringType.GetMethod(name, types); + if (method != null && method.IsStatic) method = null; + return method; +#else + return declaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + null, types, null); +#endif + } +#endif + + internal static bool IsSubclassOf(Type type, Type baseClass) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().IsSubclassOf(baseClass); +#else + return type.IsSubclassOf(baseClass); +#endif + } + + public readonly static Type[] EmptyTypes = +#if PORTABLE || CF2 || CF35 || PROFILE259 + new Type[0]; +#else + Type.EmptyTypes; +#endif + +#if COREFX || PROFILE259 + private static readonly Type[] knownTypes = new Type[] { + typeof(bool), typeof(char), typeof(sbyte), typeof(byte), + typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(float), typeof(double), + typeof(decimal), typeof(string), + typeof(DateTime), typeof(TimeSpan), typeof(Guid), typeof(Uri), + typeof(byte[]), typeof(Type)}; + private static readonly ProtoTypeCode[] knownCodes = new ProtoTypeCode[] { + ProtoTypeCode.Boolean, ProtoTypeCode.Char, ProtoTypeCode.SByte, ProtoTypeCode.Byte, + ProtoTypeCode.Int16, ProtoTypeCode.UInt16, ProtoTypeCode.Int32, ProtoTypeCode.UInt32, + ProtoTypeCode.Int64, ProtoTypeCode.UInt64, ProtoTypeCode.Single, ProtoTypeCode.Double, + ProtoTypeCode.Decimal, ProtoTypeCode.String, + ProtoTypeCode.DateTime, ProtoTypeCode.TimeSpan, ProtoTypeCode.Guid, ProtoTypeCode.Uri, + ProtoTypeCode.ByteArray, ProtoTypeCode.Type + }; + +#endif + + public static ProtoTypeCode GetTypeCode(Type type) + { +#if COREFX || PROFILE259 + if (IsEnum(type)) + { + type = Enum.GetUnderlyingType(type); + } + int idx = Array.IndexOf(knownTypes, type); + if (idx >= 0) return knownCodes[idx]; + return type == null ? ProtoTypeCode.Empty : ProtoTypeCode.Unknown; +#else + TypeCode code = Type.GetTypeCode(type); + switch (code) + { + case TypeCode.Empty: + case TypeCode.Boolean: + case TypeCode.Char: + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.UInt16: + case TypeCode.Int32: + case TypeCode.UInt32: + case TypeCode.Int64: + case TypeCode.UInt64: + case TypeCode.Single: + case TypeCode.Double: + case TypeCode.Decimal: + case TypeCode.DateTime: + case TypeCode.String: + return (ProtoTypeCode)code; + } + if (type == typeof(TimeSpan)) return ProtoTypeCode.TimeSpan; + if (type == typeof(Guid)) return ProtoTypeCode.Guid; + if (type == typeof(Uri)) return ProtoTypeCode.Uri; +#if PORTABLE + // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri), so match on the full name instead + if (type.FullName == typeof(Uri).FullName) return ProtoTypeCode.Uri; +#endif + if (type == typeof(byte[])) return ProtoTypeCode.ByteArray; + if (type == typeof(Type)) return ProtoTypeCode.Type; + + return ProtoTypeCode.Unknown; +#endif + } + + internal static Type GetUnderlyingType(Type type) + { + return Nullable.GetUnderlyingType(type); + } + + internal static bool IsValueType(Type type) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().IsValueType; +#else + return type.IsValueType; +#endif + } + internal static bool IsSealed(Type type) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().IsSealed; +#else + return type.IsSealed; +#endif + } + internal static bool IsClass(Type type) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().IsClass; +#else + return type.IsClass; +#endif + } + + internal static bool IsEnum(Type type) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().IsEnum; +#else + return type.IsEnum; +#endif + } + + internal static MethodInfo GetGetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) + { + if (property == null) return null; +#if COREFX || PROFILE259 + MethodInfo method = property.GetMethod; + if (!nonPublic && method != null && !method.IsPublic) method = null; + return method; +#else + MethodInfo method = property.GetGetMethod(nonPublic); + if (method == null && !nonPublic && allowInternal) + { // could be "internal" or "protected internal"; look for a non-public, then back-check + method = property.GetGetMethod(true); + if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly)) + { + method = null; + } + } + return method; +#endif + } + internal static MethodInfo GetSetMethod(PropertyInfo property, bool nonPublic, bool allowInternal) + { + if (property == null) return null; +#if COREFX || PROFILE259 + MethodInfo method = property.SetMethod; + if (!nonPublic && method != null && !method.IsPublic) method = null; + return method; +#else + MethodInfo method = property.GetSetMethod(nonPublic); + if (method == null && !nonPublic && allowInternal) + { // could be "internal" or "protected internal"; look for a non-public, then back-check + method = property.GetGetMethod(true); + if (method == null && !(method.IsAssembly || method.IsFamilyOrAssembly)) + { + method = null; + } + } + return method; +#endif + } + +#if COREFX || PORTABLE || PROFILE259 + private static bool IsMatch(ParameterInfo[] parameters, Type[] parameterTypes) + { + if (parameterTypes == null) parameterTypes = EmptyTypes; + if (parameters.Length != parameterTypes.Length) return false; + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].ParameterType != parameterTypes[i]) return false; + } + return true; + } +#endif +#if COREFX || PROFILE259 + internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic) + { + return GetConstructor(type.GetTypeInfo(), parameterTypes, nonPublic); + } + internal static ConstructorInfo GetConstructor(TypeInfo type, Type[] parameterTypes, bool nonPublic) + { + return GetConstructors(type, nonPublic).SingleOrDefault(ctor => IsMatch(ctor.GetParameters(), parameterTypes)); + } + internal static ConstructorInfo[] GetConstructors(TypeInfo typeInfo, bool nonPublic) + { + return typeInfo.DeclaredConstructors.Where(c => !c.IsStatic && ((!nonPublic && c.IsPublic) || nonPublic)).ToArray(); + } + internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic) + { + return GetProperty(type.GetTypeInfo(), name, nonPublic); + } + internal static PropertyInfo GetProperty(TypeInfo type, string name, bool nonPublic) + { + return type.GetDeclaredProperty(name); + } +#else + + internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic) + { +#if PORTABLE || COREFX + // pretty sure this will only ever return public, but... + ConstructorInfo ctor = type.GetConstructor(parameterTypes); + return (ctor != null && (nonPublic || ctor.IsPublic)) ? ctor : null; +#else + return type.GetConstructor( + nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + : BindingFlags.Instance | BindingFlags.Public, + null, parameterTypes, null); +#endif + + } + internal static ConstructorInfo[] GetConstructors(Type type, bool nonPublic) + { + return type.GetConstructors( + nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + : BindingFlags.Instance | BindingFlags.Public); + } + internal static PropertyInfo GetProperty(Type type, string name, bool nonPublic) + { + return type.GetProperty(name, + nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + : BindingFlags.Instance | BindingFlags.Public); + } +#endif + + + internal static object ParseEnum(Type type, string value) + { + return Enum.Parse(type, value, true); + } + + + internal static MemberInfo[] GetInstanceFieldsAndProperties(Type type, bool publicOnly) + { +#if PROFILE259 + var members = new List(); + foreach (FieldInfo field in type.GetRuntimeFields()) + { + if (field.IsStatic) continue; + if (field.IsPublic || !publicOnly) members.Add(field); + } + foreach (PropertyInfo prop in type.GetRuntimeProperties()) + { + MethodInfo getter = Helpers.GetGetMethod(prop, true, true); + if (getter == null || getter.IsStatic) continue; + if (getter.IsPublic || !publicOnly) members.Add(prop); + } + return members.ToArray(); +#else + BindingFlags flags = publicOnly ? BindingFlags.Public | BindingFlags.Instance : BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; + PropertyInfo[] props = type.GetProperties(flags); + FieldInfo[] fields = type.GetFields(flags); + MemberInfo[] members = new MemberInfo[fields.Length + props.Length]; + props.CopyTo(members, 0); + fields.CopyTo(members, props.Length); + return members; +#endif + } + + internal static Type GetMemberType(MemberInfo member) + { +#if PORTABLE || COREFX || PROFILE259 + if (member is PropertyInfo prop) return prop.PropertyType; + FieldInfo fld = member as FieldInfo; + return fld?.FieldType; +#else + switch (member.MemberType) + { + case MemberTypes.Field: return ((FieldInfo)member).FieldType; + case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; + default: return null; + } +#endif + } + + internal static bool IsAssignableFrom(Type target, Type type) + { +#if PROFILE259 + return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()); +#else + return target.IsAssignableFrom(type); +#endif + } + internal static Assembly GetAssembly(Type type) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().Assembly; +#else + return type.Assembly; +#endif + } + internal static byte[] GetBuffer(MemoryStream ms) + { +#if COREFX + if(!ms.TryGetBuffer(out var segment)) + { + throw new InvalidOperationException("Unable to obtain underlying MemoryStream buffer"); + } else if(segment.Offset != 0) + { + throw new InvalidOperationException("Underlying MemoryStream buffer was not zero-offset"); + } else + { + return segment.Array; + } +#elif PORTABLE || PROFILE259 + return ms.ToArray(); +#else + return ms.GetBuffer(); +#endif + } + } + /// + /// Intended to be a direct map to regular TypeCode, but: + /// - with missing types + /// - existing on WinRT + /// + internal enum ProtoTypeCode + { + Empty = 0, + Unknown = 1, // maps to TypeCode.Object + Boolean = 3, + Char = 4, + SByte = 5, + Byte = 6, + Int16 = 7, + UInt16 = 8, + Int32 = 9, + UInt32 = 10, + Int64 = 11, + UInt64 = 12, + Single = 13, + Double = 14, + Decimal = 15, + DateTime = 16, + String = 18, + + // additions + TimeSpan = 100, + ByteArray = 101, + Guid = 102, + Uri = 103, + Type = 104 + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Helpers.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Helpers.cs.meta new file mode 100644 index 0000000..f721e09 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Helpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e7554bae4f35ce4fab5c5dcd2769de8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs new file mode 100644 index 0000000..b7c0b57 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs @@ -0,0 +1,23 @@ + +namespace ProtoBuf +{ + /// + /// Indicates that the implementing type has support for protocol-buffer + /// extensions. + /// + /// Can be implemented by deriving from Extensible. + public interface IExtensible + { + /// + /// Retrieves the extension object for the current + /// instance, optionally creating it if it does not already exist. + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + IExtension GetExtensionObject(bool createIfMissing); + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs.meta new file mode 100644 index 0000000..6877bd3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtensible.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07514d3b32ffc8f4891622be5e7e21d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs new file mode 100644 index 0000000..0a137ac --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs @@ -0,0 +1,58 @@ + +using System.IO; +namespace ProtoBuf +{ + /// + /// Provides addition capability for supporting unexpected fields during + /// protocol-buffer serialization/deserialization. This allows for loss-less + /// round-trip/merge, even when the data is not fully understood. + /// + public interface IExtension + { + /// + /// Requests a stream into which any unexpected fields can be persisted. + /// + /// A new stream suitable for storing data. + Stream BeginAppend(); + + /// + /// Indicates that all unexpected fields have now been stored. The + /// implementing class is responsible for closing the stream. If + /// "commit" is not true the data may be discarded. + /// + /// The stream originally obtained by BeginAppend. + /// True if the append operation completed successfully. + void EndAppend(Stream stream, bool commit); + + /// + /// Requests a stream of the unexpected fields previously stored. + /// + /// A prepared stream of the unexpected fields. + Stream BeginQuery(); + + /// + /// Indicates that all unexpected fields have now been read. The + /// implementing class is responsible for closing the stream. + /// + /// The stream originally obtained by BeginQuery. + void EndQuery(Stream stream); + + /// + /// Requests the length of the raw binary stream; this is used + /// when serializing sub-entities to indicate the expected size. + /// + /// The length of the binary stream representing unexpected data. + int GetLength(); + } + + /// + /// Provides the ability to remove all existing extension data + /// + public interface IExtensionResettable : IExtension + { + /// + /// Remove all existing extension data + /// + void Reset(); + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs.meta new file mode 100644 index 0000000..7ffcfc0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3c86c16d6d59c34bb4bf94ad088339a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs new file mode 100644 index 0000000..6eaa0ce --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs @@ -0,0 +1,13 @@ +namespace ProtoBuf +{ + /// + /// Represents the ability to deserialize values from an input of type + /// + public interface IProtoInput + { + /// + /// Deserialize a value from the input + /// + T Deserialize(TInput source, T value = default, object userState = null); + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs.meta new file mode 100644 index 0000000..66b6bba --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoInputT.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c04b4c608bf369843bb8906e42284802 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs new file mode 100644 index 0000000..1c7dd42 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs @@ -0,0 +1,55 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Represents the ability to serialize values to an output of type + /// + public interface IProtoOutput + { + /// + /// Serialize the provided value + /// + void Serialize(TOutput destination, T value, object userState = null); + } + + /// + /// Represents the ability to serialize values to an output of type + /// with pre-computation of the length + /// + public interface IMeasuredProtoOutput : IProtoOutput + { + /// + /// Measure the length of a value in advance of serialization + /// + MeasureState Measure(T value, object userState = null); + + /// + /// Serialize the previously measured value + /// + void Serialize(MeasureState measured, TOutput destination); + } + + /// + /// Represents the outcome of computing the length of an object; since this may have required computing lengths + /// for multiple objects, some metadata is retained so that a subsequent serialize operation using + /// this instance can re-use the previously calculated lengths. If the object state changes between the + /// measure and serialize operations, the behavior is undefined. + /// + public struct MeasureState : IDisposable + // note: 2.4.* does not actually implement this API; + // it only advertises it for 3.* capability/feature-testing, i.e. + // callers can check whether a model implements + // IMeasuredProtoOutput, and *work from that* + { + /// + /// Releases all resources associated with this value + /// + public void Dispose() => throw new NotImplementedException(); + + /// + /// Gets the calculated length of this serialize operation, in bytes + /// + public long Length => throw new NotImplementedException(); + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs.meta new file mode 100644 index 0000000..4a513a8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/IProtoOutputT.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e37e529af1eced348af0529dc1848b0c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs new file mode 100644 index 0000000..211abdd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs @@ -0,0 +1,29 @@ +namespace ProtoBuf +{ + /// + /// Specifies the method used to infer field tags for members of the type + /// under consideration. Tags are deduced using the invariant alphabetic + /// sequence of the members' names; this makes implicit field tags very brittle, + /// and susceptible to changes such as field names (normally an isolated + /// change). + /// + public enum ImplicitFields + { + /// + /// No members are serialized implicitly; all members require a suitable + /// attribute such as [ProtoMember]. This is the recmomended mode for + /// most scenarios. + /// + None = 0, + /// + /// Public properties and fields are eligible for implicit serialization; + /// this treats the public API as a contract. Ordering beings from ImplicitFirstTag. + /// + AllPublic = 1, + /// + /// Public and non-public fields are eligible for implicit serialization; + /// this acts as a state/implementation serializer. Ordering beings from ImplicitFirstTag. + /// + AllFields = 2 + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs.meta new file mode 100644 index 0000000..c93b1bc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ImplicitFields.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f4c8e2d9823c0d2408eb0aef9228b8b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs new file mode 100644 index 0000000..0da5761 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs @@ -0,0 +1,44 @@ +//using System.Collections.Generic; + +//namespace ProtoBuf +//{ +// /// +// /// Mutable version of the common key/value pair struct; used during serialization. This type is intended for internal use only and should not +// /// be used by calling code; it is required to be public for implementation reasons. +// /// +// [ProtoContract] +// public struct KeyValuePairSurrogate +// { +// private TKey key; +// private TValue value; +// /// +// /// The key of the pair. +// /// +// [ProtoMember(1, IsRequired = true)] +// public TKey Key { get { return key; } set { key = value; } } +// /// +// /// The value of the pair. +// /// +// [ProtoMember(2)] +// public TValue Value{ get { return value; } set { this.value = value; } } +// private KeyValuePairSurrogate(TKey key, TValue value) +// { +// this.key = key; +// this.value = value; +// } +// /// +// /// Convert a surrogate instance to a standard pair instance. +// /// +// public static implicit operator KeyValuePair (KeyValuePairSurrogate value) +// { +// return new KeyValuePair(value.key, value.value); +// } +// /// +// /// Convert a standard pair instance to a surrogate instance. +// /// +// public static implicit operator KeyValuePairSurrogate(KeyValuePair value) +// { +// return new KeyValuePairSurrogate(value.Key, value.Value); +// } +// } +//} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta new file mode 100644 index 0000000..94b5fb7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b48d7aba3f5f85f4d961b28f5e8a4054 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta.meta new file mode 100644 index 0000000..e7485ee --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7fe107cb05a05c04f8ffa6eb5312c866 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs new file mode 100644 index 0000000..5bab942 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs @@ -0,0 +1,108 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Meta +{ + internal abstract class AttributeMap + { +#if DEBUG + [Obsolete("Please use AttributeType instead")] + new public Type GetType() => AttributeType; +#endif + public override string ToString() => AttributeType?.FullName ?? ""; + public abstract bool TryGet(string key, bool publicOnly, out object value); + public bool TryGet(string key, out object value) + { + return TryGet(key, true, out value); + } + public abstract Type AttributeType { get; } + public static AttributeMap[] Create(TypeModel model, Type type, bool inherit) + { + +#if COREFX || PROFILE259 + Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType(type.GetTypeInfo().GetCustomAttributes(inherit))); +#else + object[] all = type.GetCustomAttributes(inherit); +#endif + AttributeMap[] result = new AttributeMap[all.Length]; + for(int i = 0 ; i < all.Length ; i++) + { + result[i] = new ReflectionAttributeMap((Attribute)all[i]); + } + return result; + } + + public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit) + { + +#if COREFX || PROFILE259 + Attribute[] all = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.OfType(member.GetCustomAttributes(inherit))); +#else + object[] all = member.GetCustomAttributes(inherit); +#endif + AttributeMap[] result = new AttributeMap[all.Length]; + for(int i = 0 ; i < all.Length ; i++) + { + result[i] = new ReflectionAttributeMap((Attribute)all[i]); + } + return result; + } + public static AttributeMap[] Create(TypeModel model, Assembly assembly) + { +#if COREFX || PROFILE259 + Attribute[] all = System.Linq.Enumerable.ToArray(assembly.GetCustomAttributes()); +#else + const bool inherit = false; + object[] all = assembly.GetCustomAttributes(inherit); +#endif + AttributeMap[] result = new AttributeMap[all.Length]; + for(int i = 0 ; i < all.Length ; i++) + { + result[i] = new ReflectionAttributeMap((Attribute)all[i]); + } + return result; + + } + + public abstract object Target { get; } + + private sealed class ReflectionAttributeMap : AttributeMap + { + private readonly Attribute attribute; + + public ReflectionAttributeMap(Attribute attribute) + { + this.attribute = attribute; + } + + public override object Target => attribute; + + public override Type AttributeType => attribute.GetType(); + + public override bool TryGet(string key, bool publicOnly, out object value) + { + MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly); + foreach (MemberInfo member in members) + { + if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase)) + { + if (member is PropertyInfo prop) { + value = prop.GetValue(attribute, null); + return true; + } + if (member is FieldInfo field) { + value = field.GetValue(attribute); + return true; + } + + throw new NotSupportedException(member.GetType().Name); + } + } + value = null; + return false; + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta new file mode 100644 index 0000000..c7ee80f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 47a327037b160634f85e9108c4984238 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs new file mode 100644 index 0000000..d1308f3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections; + +namespace ProtoBuf.Meta +{ + internal sealed class MutableList : BasicList + { + /* Like BasicList, but allows existing values to be changed + */ + public new object this[int index] + { + get { return head[index]; } + set { head[index] = value; } + } + public void RemoveLast() + { + head.RemoveLastWithMutate(); + } + + public void Clear() + { + head.Clear(); + } + } + + internal class BasicList : IEnumerable + { + /* Requirements: + * - Fast access by index + * - Immutable in the tail, so a node can be read (iterated) without locking + * - Lock-free tail handling must match the memory mode; struct for Node + * wouldn't work as "read" would not be atomic + * - Only operation required is append, but this shouldn't go out of its + * way to be inefficient + * - Assume that the caller is handling thread-safety (to co-ordinate with + * other code); no attempt to be thread-safe + * - Assume that the data is private; internal data structure is allowed to + * be mutable (i.e. array is fine as long as we don't screw it up) + */ + private static readonly Node nil = new Node(null, 0); + + public void CopyTo(Array array, int offset) + { + head.CopyTo(array, offset); + } + + protected Node head = nil; + + public int Add(object value) + { + return (head = head.Append(value)).Length - 1; + } + + public object this[int index] => head[index]; + + //public object TryGet(int index) + //{ + // return head.TryGet(index); + //} + + public void Trim() { head = head.Trim(); } + + public int Count => head.Length; + + IEnumerator IEnumerable.GetEnumerator() => new NodeEnumerator(head); + + public NodeEnumerator GetEnumerator() => new NodeEnumerator(head); + + public struct NodeEnumerator : IEnumerator + { + private int position; + private readonly Node node; + internal NodeEnumerator(Node node) + { + this.position = -1; + this.node = node; + } + void IEnumerator.Reset() { position = -1; } + public object Current { get { return node[position]; } } + public bool MoveNext() + { + int len = node.Length; + return (position <= len) && (++position < len); + } + } + + internal sealed class Node + { + public object this[int index] + { + get + { + if (index >= 0 && index < length) + { + return data[index]; + } + throw new ArgumentOutOfRangeException(nameof(index)); + } + set + { + if (index >= 0 && index < length) + { + data[index] = value; + } + else + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + } + } + //public object TryGet(int index) + //{ + // return (index >= 0 && index < length) ? data[index] : null; + //} + private readonly object[] data; + + private int length; + public int Length => length; + + internal Node(object[] data, int length) + { + Helpers.DebugAssert((data == null && length == 0) || + (data != null && length > 0 && length <= data.Length)); + this.data = data; + + this.length = length; + } + + public void RemoveLastWithMutate() + { + if (length == 0) throw new InvalidOperationException(); + length -= 1; + } + + public Node Append(object value) + { + object[] newData; + int newLength = length + 1; + if (data == null) + { + newData = new object[10]; + } + else if (length == data.Length) + { + newData = new object[data.Length * 2]; + Array.Copy(data, newData, length); + } + else + { + newData = data; + } + newData[length] = value; + return new Node(newData, newLength); + } + + public Node Trim() + { + if (length == 0 || length == data.Length) return this; + object[] newData = new object[length]; + Array.Copy(data, newData, length); + return new Node(newData, length); + } + + internal int IndexOfString(string value) + { + for (int i = 0; i < length; i++) + { + if ((string)value == (string)data[i]) return i; + } + return -1; + } + + internal int IndexOfReference(object instance) + { + for (int i = 0; i < length; i++) + { + if ((object)instance == (object)data[i]) return i; + } // ^^^ (object) above should be preserved, even if this was typed; needs + // to be a reference check + return -1; + } + + internal int IndexOf(MatchPredicate predicate, object ctx) + { + for (int i = 0; i < length; i++) + { + if (predicate(data[i], ctx)) return i; + } + return -1; + } + + internal void CopyTo(Array array, int offset) + { + if (length > 0) + { + Array.Copy(data, 0, array, offset, length); + } + } + + internal void Clear() + { + if (data != null) + { + Array.Clear(data, 0, data.Length); + } + length = 0; + } + } + + internal int IndexOf(MatchPredicate predicate, object ctx) + { + return head.IndexOf(predicate, ctx); + } + + internal int IndexOfString(string value) + { + return head.IndexOfString(value); + } + + internal int IndexOfReference(object instance) + { + return head.IndexOfReference(instance); + } + + internal delegate bool MatchPredicate(object value, object ctx); + + internal bool Contains(object value) + { + foreach (object obj in this) + { + if (object.Equals(obj, value)) return true; + } + return false; + } + + internal sealed class Group + { + public readonly int First; + public readonly BasicList Items; + public Group(int first) + { + this.First = first; + this.Items = new BasicList(); + } + } + + internal static BasicList GetContiguousGroups(int[] keys, object[] values) + { + if (keys == null) throw new ArgumentNullException(nameof(keys)); + if (values == null) throw new ArgumentNullException(nameof(values)); + if (values.Length < keys.Length) throw new ArgumentException("Not all keys are covered by values", nameof(values)); + BasicList outer = new BasicList(); + Group group = null; + for (int i = 0; i < keys.Length; i++) + { + if (i == 0 || keys[i] != keys[i - 1]) { group = null; } + if (group == null) + { + group = new Group(keys[i]); + outer.Add(group); + } + group.Items.Add(values[i]); + } + return outer; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs.meta new file mode 100644 index 0000000..5d207ff --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/BasicList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eaea8ceda8ddbb0409750a9642946399 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs new file mode 100644 index 0000000..8b08585 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs @@ -0,0 +1,110 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Meta +{ + /// + /// Represents the set of serialization callbacks to be used when serializing/deserializing a type. + /// + public class CallbackSet + { + private readonly MetaType metaType; + internal CallbackSet(MetaType metaType) + { + this.metaType = metaType ?? throw new ArgumentNullException(nameof(metaType)); + } + + internal MethodInfo this[TypeModel.CallbackType callbackType] + { + get + { + switch (callbackType) + { + case TypeModel.CallbackType.BeforeSerialize: return beforeSerialize; + case TypeModel.CallbackType.AfterSerialize: return afterSerialize; + case TypeModel.CallbackType.BeforeDeserialize: return beforeDeserialize; + case TypeModel.CallbackType.AfterDeserialize: return afterDeserialize; + default: throw new ArgumentException("Callback type not supported: " + callbackType.ToString(), "callbackType"); + } + } + } + + internal static bool CheckCallbackParameters(TypeModel model, MethodInfo method) + { + ParameterInfo[] args = method.GetParameters(); + for (int i = 0; i < args.Length; i++) + { + Type paramType = args[i].ParameterType; + if (paramType == model.MapType(typeof(SerializationContext))) { } + else if (paramType == model.MapType(typeof(System.Type))) { } +#if PLAT_BINARYFORMATTER + else if (paramType == model.MapType(typeof(System.Runtime.Serialization.StreamingContext))) { } +#endif + else return false; + } + return true; + } + + private MethodInfo SanityCheckCallback(TypeModel model, MethodInfo callback) + { + metaType.ThrowIfFrozen(); + if (callback == null) return callback; // fine + if (callback.IsStatic) throw new ArgumentException("Callbacks cannot be static", nameof(callback)); + if (callback.ReturnType != model.MapType(typeof(void)) + || !CheckCallbackParameters(model, callback)) + { + throw CreateInvalidCallbackSignature(callback); + } + return callback; + } + + internal static Exception CreateInvalidCallbackSignature(MethodInfo method) + { + return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name); + } + + private MethodInfo beforeSerialize, afterSerialize, beforeDeserialize, afterDeserialize; + + /// Called before serializing an instance + public MethodInfo BeforeSerialize + { + get { return beforeSerialize; } + set { beforeSerialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called before deserializing an instance + public MethodInfo BeforeDeserialize + { + get { return beforeDeserialize; } + set { beforeDeserialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called after serializing an instance + public MethodInfo AfterSerialize + { + get { return afterSerialize; } + set { afterSerialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called after deserializing an instance + public MethodInfo AfterDeserialize + { + get { return afterDeserialize; } + set { afterDeserialize = SanityCheckCallback(metaType.Model, value); } + } + + /// + /// True if any callback is set, else False + /// + public bool NonTrivial + { + get + { + return beforeSerialize != null || beforeDeserialize != null + || afterSerialize != null || afterDeserialize != null; + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta new file mode 100644 index 0000000..0d990c0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f588ab5e558c8a48ada610b5c4ed032 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs new file mode 100644 index 0000000..8d9bed6 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs @@ -0,0 +1,2171 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Text; +using ProtoBuf.Serializers; +using System.Reflection; +using System.Collections.Generic; + +#if PROFILE259 +using System.Linq; +#endif + +namespace ProtoBuf.Meta +{ + /// + /// Represents a type at runtime for use with protobuf, allowing the field mappings (etc) to be defined + /// + public class MetaType : ISerializerProxy + { + internal sealed class Comparer : IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + public int Compare(object x, object y) + { + return Compare(x as MetaType, y as MetaType); + } + public int Compare(MetaType x, MetaType y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return string.Compare(x.GetSchemaTypeName(), y.GetSchemaTypeName(), StringComparison.Ordinal); + } + } + /// + /// Get the name of the type being represented + /// + public override string ToString() + { + return type.ToString(); + } + + IProtoSerializer ISerializerProxy.Serializer => Serializer; + private MetaType baseType; + + /// + /// Gets the base-type for this type + /// + public MetaType BaseType => baseType; + + internal TypeModel Model => model; + + /// + /// When used to compile a model, should public serialization/deserialzation methods + /// be included for this type? + /// + public bool IncludeSerializerMethod + { // negated to minimize common-case / initializer + get { return !HasFlag(OPTIONS_PrivateOnApi); } + set { SetFlag(OPTIONS_PrivateOnApi, !value, true); } + } + + /// + /// Should this type be treated as a reference by default? + /// + public bool AsReferenceDefault + { + get { return HasFlag(OPTIONS_AsReferenceDefault); } + set { SetFlag(OPTIONS_AsReferenceDefault, value, true); } + } + + private BasicList subTypes; + private bool IsValidSubType(Type subType) + { +#if COREFX || PROFILE259 + return typeInfo.IsAssignableFrom(subType.GetTypeInfo()); +#else + return type.IsAssignableFrom(subType); +#endif + } + /// + /// Adds a known sub-type to the inheritance model + /// + public MetaType AddSubType(int fieldNumber, Type derivedType) + { + return AddSubType(fieldNumber, derivedType, DataFormat.Default); + } + /// + /// Adds a known sub-type to the inheritance model + /// + public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat) + { + if (derivedType == null) throw new ArgumentNullException("derivedType"); + if (fieldNumber < 1) throw new ArgumentOutOfRangeException("fieldNumber"); +#if COREFX || COREFX || PROFILE259 + if (!(typeInfo.IsClass || typeInfo.IsInterface) || typeInfo.IsSealed) { +#else + if (!(type.IsClass || type.IsInterface) || type.IsSealed) + { +#endif + throw new InvalidOperationException("Sub-types can only be added to non-sealed classes"); + } + if (!IsValidSubType(derivedType)) + { + throw new ArgumentException(derivedType.Name + " is not a valid sub-type of " + type.Name, "derivedType"); + } + MetaType derivedMeta = model[derivedType]; + ThrowIfFrozen(); + derivedMeta.ThrowIfFrozen(); + SubType subType = new SubType(fieldNumber, derivedMeta, dataFormat); + ThrowIfFrozen(); + + derivedMeta.SetBaseType(this); // includes ThrowIfFrozen + if (subTypes == null) subTypes = new BasicList(); + subTypes.Add(subType); + model.ResetKeyCache(); + return this; + } +#if COREFX || PROFILE259 + internal static readonly TypeInfo ienumerable = typeof(IEnumerable).GetTypeInfo(); +#else + internal static readonly Type ienumerable = typeof(IEnumerable); +#endif + private void SetBaseType(MetaType baseType) + { + if (baseType == null) throw new ArgumentNullException("baseType"); + if (this.baseType == baseType) return; + if (this.baseType != null) throw new InvalidOperationException($"Type '{this.baseType.Type.FullName}' can only participate in one inheritance hierarchy"); + + MetaType type = baseType; + while (type != null) + { + if (ReferenceEquals(type, this)) throw new InvalidOperationException($"Cyclic inheritance of '{this.baseType.Type.FullName}' is not allowed"); + type = type.baseType; + } + this.baseType = baseType; + } + + private CallbackSet callbacks; + + /// + /// Indicates whether the current type has defined callbacks + /// + public bool HasCallbacks => callbacks != null && callbacks.NonTrivial; + + /// + /// Indicates whether the current type has defined subtypes + /// + public bool HasSubtypes => subTypes != null && subTypes.Count != 0; + + /// + /// Returns the set of callbacks defined for this type + /// + public CallbackSet Callbacks + { + get + { + if (callbacks == null) callbacks = new CallbackSet(this); + return callbacks; + } + } + + private bool IsValueType + { + get + { +#if COREFX || PROFILE259 + return typeInfo.IsValueType; +#else + return type.IsValueType; +#endif + } + } + /// + /// Assigns the callbacks to use during serialiation/deserialization. + /// + /// The method (or null) called before serialization begins. + /// The method (or null) called when serialization is complete. + /// The method (or null) called before deserialization begins (or when a new instance is created during deserialization). + /// The method (or null) called when deserialization is complete. + /// The set of callbacks. + public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize) + { + CallbackSet callbacks = Callbacks; + callbacks.BeforeSerialize = beforeSerialize; + callbacks.AfterSerialize = afterSerialize; + callbacks.BeforeDeserialize = beforeDeserialize; + callbacks.AfterDeserialize = afterDeserialize; + return this; + } + /// + /// Assigns the callbacks to use during serialiation/deserialization. + /// + /// The name of the method (or null) called before serialization begins. + /// The name of the method (or null) called when serialization is complete. + /// The name of the method (or null) called before deserialization begins (or when a new instance is created during deserialization). + /// The name of the method (or null) called when deserialization is complete. + /// The set of callbacks. + public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize) + { + if (IsValueType) throw new InvalidOperationException(); + CallbackSet callbacks = Callbacks; + callbacks.BeforeSerialize = ResolveMethod(beforeSerialize, true); + callbacks.AfterSerialize = ResolveMethod(afterSerialize, true); + callbacks.BeforeDeserialize = ResolveMethod(beforeDeserialize, true); + callbacks.AfterDeserialize = ResolveMethod(afterDeserialize, true); + return this; + } + + /// + /// Returns the public Type name of this Type used in serialization + /// + public string GetSchemaTypeName() + { + if (surrogate != null) return model[surrogate].GetSchemaTypeName(); + + if (!string.IsNullOrEmpty(name)) return name; + + string typeName = type.Name; + if (type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsGenericType) + { + var sb = new StringBuilder(typeName); + int split = typeName.IndexOf('`'); + if (split >= 0) sb.Length = split; + foreach (Type arg in type +#if COREFX || PROFILE259 + .GetTypeInfo().GenericTypeArguments +#else + .GetGenericArguments() +#endif + ) + { + sb.Append('_'); + Type tmp = arg; + int key = model.GetKey(ref tmp); + MetaType mt; + if (key >= 0 && (mt = model[tmp]) != null && mt.surrogate == null) // <=== need to exclude surrogate to avoid chance of infinite loop + { + + sb.Append(mt.GetSchemaTypeName()); + } + else + { + sb.Append(tmp.Name); + } + } + return sb.ToString(); + } + + return typeName; + } + + private string name; + + /// + /// Gets or sets the name of this contract. + /// + public string Name + { + get + { + return name; + } + set + { + ThrowIfFrozen(); + name = value; + } + } + + private MethodInfo factory; + /// + /// Designate a factory-method to use to create instances of this type + /// + public MetaType SetFactory(MethodInfo factory) + { + model.VerifyFactory(factory, type); + ThrowIfFrozen(); + this.factory = factory; + return this; + } + + /// + /// Designate a factory-method to use to create instances of this type + /// + public MetaType SetFactory(string factory) + { + return SetFactory(ResolveMethod(factory, false)); + } + + private MethodInfo ResolveMethod(string name, bool instance) + { + if (string.IsNullOrEmpty(name)) return null; +#if COREFX + return instance ? Helpers.GetInstanceMethod(typeInfo, name) : Helpers.GetStaticMethod(typeInfo, name); +#else + return instance ? Helpers.GetInstanceMethod(type, name) : Helpers.GetStaticMethod(type, name); +#endif + } + + private readonly RuntimeTypeModel model; + + internal static Exception InbuiltType(Type type) + { + return new ArgumentException("Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName); + } + + internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory) + { + this.factory = factory; + if (model == null) throw new ArgumentNullException("model"); + if (type == null) throw new ArgumentNullException("type"); + + if (type.IsArray) throw InbuiltType(type); + IProtoSerializer coreSerializer = model.TryGetBasicTypeSerializer(type); + if (coreSerializer != null) + { + throw InbuiltType(type); + } + + this.type = type; +#if COREFX || PROFILE259 + this.typeInfo = type.GetTypeInfo(); +#endif + this.model = model; + + if (Helpers.IsEnum(type)) + { +#if COREFX || PROFILE259 + EnumPassthru = typeInfo.IsDefined(typeof(FlagsAttribute), false); +#else + EnumPassthru = type.IsDefined(model.MapType(typeof(FlagsAttribute)), false); +#endif + } + } +#if COREFX || PROFILE259 + private readonly TypeInfo typeInfo; +#endif + /// + /// Throws an exception if the type has been made immutable + /// + protected internal void ThrowIfFrozen() + { + if ((flags & OPTIONS_Frozen) != 0) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + type.FullName); + } + + // internal void Freeze() { flags |= OPTIONS_Frozen; } + + private readonly Type type; + /// + /// The runtime type that the meta-type represents + /// + public Type Type => type; + + private IProtoTypeSerializer serializer; + internal IProtoTypeSerializer Serializer + { + get + { + if (serializer == null) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + if (serializer == null) + { // double-check, but our main purpse with this lock is to ensure thread-safety with + // serializers needing to wait until another thread has finished adding the properties + SetFlag(OPTIONS_Frozen, true, false); + serializer = BuildSerializer(); +#if FEAT_COMPILER + if (model.AutoCompile) CompileInPlace(); +#endif + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + return serializer; + } + } + internal bool IsList + { + get + { + Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type); + return itemType != null; + } + } + private IProtoTypeSerializer BuildSerializer() + { + if (Helpers.IsEnum(type)) + { + return new TagDecorator(ProtoBuf.Serializer.ListItemTag, WireType.Variant, false, new EnumSerializer(type, GetEnumMap())); + } + Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type); + if (itemType != null) + { + if (surrogate != null) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate"); + } + if (subTypes != null && subTypes.Count != 0) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed"); + } + Type defaultType = null; + ResolveListTypes(model, type, ref itemType, ref defaultType); + ValueMember fakeMember = new ValueMember(model, ProtoBuf.Serializer.ListItemTag, type, itemType, defaultType, DataFormat.Default); + return new TypeSerializer(model, type, new int[] { ProtoBuf.Serializer.ListItemTag }, new IProtoSerializer[] { fakeMember.Serializer }, null, true, true, null, constructType, factory); + } + if (surrogate != null) + { + MetaType mt = model[surrogate], mtBase; + while ((mtBase = mt.baseType) != null) { mt = mtBase; } + return new SurrogateSerializer(model, type, surrogate, mt.Serializer); + } + if (IsAutoTuple) + { + ConstructorInfo ctor = ResolveTupleConstructor(type, out MemberInfo[] mapping); + if (ctor == null) throw new InvalidOperationException(); + return new TupleSerializer(model, ctor, mapping); + } + + fields.Trim(); + int fieldCount = fields.Count; + int subTypeCount = subTypes == null ? 0 : subTypes.Count; + int[] fieldNumbers = new int[fieldCount + subTypeCount]; + IProtoSerializer[] serializers = new IProtoSerializer[fieldCount + subTypeCount]; + int i = 0; + if (subTypeCount != 0) + { + foreach (SubType subType in subTypes) + { +#if COREFX || PROFILE259 + if (!subType.DerivedType.IgnoreListHandling && ienumerable.IsAssignableFrom(subType.DerivedType.Type.GetTypeInfo())) +#else + if (!subType.DerivedType.IgnoreListHandling && model.MapType(ienumerable).IsAssignableFrom(subType.DerivedType.Type)) +#endif + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass"); + } + fieldNumbers[i] = subType.FieldNumber; + serializers[i++] = subType.Serializer; + } + } + if (fieldCount != 0) + { + foreach (ValueMember member in fields) + { + fieldNumbers[i] = member.FieldNumber; + serializers[i++] = member.Serializer; + } + } + + BasicList baseCtorCallbacks = null; + MetaType tmp = BaseType; + + while (tmp != null) + { + MethodInfo method = tmp.HasCallbacks ? tmp.Callbacks.BeforeDeserialize : null; + if (method != null) + { + if (baseCtorCallbacks == null) baseCtorCallbacks = new BasicList(); + baseCtorCallbacks.Add(method); + } + tmp = tmp.BaseType; + } + MethodInfo[] arr = null; + if (baseCtorCallbacks != null) + { + arr = new MethodInfo[baseCtorCallbacks.Count]; + baseCtorCallbacks.CopyTo(arr, 0); + Array.Reverse(arr); + } + return new TypeSerializer(model, type, fieldNumbers, serializers, arr, baseType == null, UseConstructor, callbacks, constructType, factory); + } + + [Flags] + internal enum AttributeFamily + { + None = 0, ProtoBuf = 1, DataContractSerialier = 2, XmlSerializer = 4, AutoTuple = 8 + } + static Type GetBaseType(MetaType type) + { +#if COREFX || PROFILE259 + return type.typeInfo.BaseType; +#else + return type.type.BaseType; +#endif + } + internal static bool GetAsReferenceDefault(RuntimeTypeModel model, Type type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (Helpers.IsEnum(type)) return false; // never as-ref + AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false); + for (int i = 0; i < typeAttribs.Length; i++) + { + if (typeAttribs[i].AttributeType.FullName == "ProtoBuf.ProtoContractAttribute") + { + if (typeAttribs[i].TryGet("AsReferenceDefault", out object tmp)) return (bool)tmp; + } + } + return false; + } + + internal void ApplyDefaultBehaviour() + { + TypeAddedEventArgs args = null; // allows us to share the event-args between events + RuntimeTypeModel.OnBeforeApplyDefaultBehaviour(this, ref args); + if (args == null || args.ApplyDefaultBehaviour) ApplyDefaultBehaviourImpl(); + RuntimeTypeModel.OnAfterApplyDefaultBehaviour(this, ref args); + } + + internal void ApplyDefaultBehaviourImpl() + { + Type baseType = GetBaseType(this); + if (baseType != null && model.FindWithoutAdd(baseType) == null + && GetContractFamily(model, baseType, null) != MetaType.AttributeFamily.None) + { + model.FindOrAddAuto(baseType, true, false, false); + } + + AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false); + AttributeFamily family = GetContractFamily(model, type, typeAttribs); + if (family == AttributeFamily.AutoTuple) + { + SetFlag(OPTIONS_AutoTuple, true, true); + } + bool isEnum = !EnumPassthru && Helpers.IsEnum(type); + if (family == AttributeFamily.None && !isEnum) return; // and you'd like me to do what, exactly? + + bool enumShouldUseImplicitPassThru = isEnum; + BasicList partialIgnores = null, partialMembers = null; + int dataMemberOffset = 0, implicitFirstTag = 1; + bool inferTagByName = model.InferTagFromNameDefault; + ImplicitFields implicitMode = ImplicitFields.None; + string name = null; + for (int i = 0; i < typeAttribs.Length; i++) + { + AttributeMap item = (AttributeMap)typeAttribs[i]; + object tmp; + string fullAttributeTypeName = item.AttributeType.FullName; + if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoIncludeAttribute") + { + int tag = 0; + if (item.TryGet("tag", out tmp)) tag = (int)tmp; + DataFormat dataFormat = DataFormat.Default; + if (item.TryGet("DataFormat", out tmp)) + { + dataFormat = (DataFormat)(int)tmp; + } + Type knownType = null; + try + { + if (item.TryGet("knownTypeName", out tmp)) knownType = model.GetType((string)tmp, type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .Assembly); + else if (item.TryGet("knownType", out tmp)) knownType = (Type)tmp; + } + catch (Exception ex) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName, ex); + } + if (knownType == null) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName); + } + if (IsValidSubType(knownType)) AddSubType(tag, knownType, dataFormat); + } + + if (fullAttributeTypeName == "ProtoBuf.ProtoPartialIgnoreAttribute") + { + if (item.TryGet(nameof(ProtoPartialIgnoreAttribute.MemberName), out tmp) && tmp != null) + { + if (partialIgnores == null) partialIgnores = new BasicList(); + partialIgnores.Add((string)tmp); + } + } + if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoPartialMemberAttribute") + { + if (partialMembers == null) partialMembers = new BasicList(); + partialMembers.Add(item); + } + + if (fullAttributeTypeName == "ProtoBuf.ProtoContractAttribute") + { + if (item.TryGet(nameof(ProtoContractAttribute.Name), out tmp)) name = (string)tmp; + if (Helpers.IsEnum(type)) // note this is subtly different to isEnum; want to do this even if [Flags] + { + if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthruHasValue), false, out tmp) && (bool)tmp) + { + if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthru), out tmp)) + { + EnumPassthru = (bool)tmp; + enumShouldUseImplicitPassThru = false; + if (EnumPassthru) isEnum = false; // no longer treated as an enum + } + } + } + else + { + if (item.TryGet(nameof(ProtoContractAttribute.DataMemberOffset), out tmp)) dataMemberOffset = (int)tmp; + + if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromNameHasValue), false, out tmp) && (bool)tmp) + { + if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromName), out tmp)) inferTagByName = (bool)tmp; + } + + if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFields), out tmp) && tmp != null) + { + implicitMode = (ImplicitFields)(int)tmp; // note that this uses the bizarre unboxing rules of enums/underlying-types + } + + if (item.TryGet(nameof(ProtoContractAttribute.SkipConstructor), out tmp)) UseConstructor = !(bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.IgnoreListHandling), out tmp)) IgnoreListHandling = (bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.AsReferenceDefault), out tmp)) AsReferenceDefault = (bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFirstTag), out tmp) && (int)tmp > 0) implicitFirstTag = (int)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.IsGroup), out tmp)) IsGroup = (bool)tmp; + + if (item.TryGet(nameof(ProtoContractAttribute.Surrogate), out tmp)) + { + SetSurrogate((Type)tmp); + } + } + } + + if (fullAttributeTypeName == "System.Runtime.Serialization.DataContractAttribute") + { + if (name == null && item.TryGet("Name", out tmp)) name = (string)tmp; + } + if (fullAttributeTypeName == "System.Xml.Serialization.XmlTypeAttribute") + { + if (name == null && item.TryGet("TypeName", out tmp)) name = (string)tmp; + } + } + if (!string.IsNullOrEmpty(name)) Name = name; + if (implicitMode != ImplicitFields.None) + { + family &= AttributeFamily.ProtoBuf; // with implicit fields, **only** proto attributes are important + } + MethodInfo[] callbacks = null; + + BasicList members = new BasicList(); + +#if PROFILE259 + IEnumerable foundList; + if(isEnum) { + foundList = type.GetRuntimeFields(); + } + else + { + List list = new List(); + foreach(PropertyInfo prop in type.GetRuntimeProperties()) { + MethodInfo getter = Helpers.GetGetMethod(prop, false, false); + if(getter != null && !getter.IsStatic) list.Add(prop); + } + foreach(FieldInfo fld in type.GetRuntimeFields()) if(fld.IsPublic && !fld.IsStatic) list.Add(fld); + foreach(MethodInfo mthd in type.GetRuntimeMethods()) if(mthd.IsPublic && !mthd.IsStatic) list.Add(mthd); + foundList = list; + } +#else + MemberInfo[] foundList = type.GetMembers(isEnum ? BindingFlags.Public | BindingFlags.Static + : BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); +#endif + bool hasConflictingEnumValue = false; + foreach (MemberInfo member in foundList) + { + if (member.DeclaringType != type) continue; + if (member.IsDefined(model.MapType(typeof(ProtoIgnoreAttribute)), true)) continue; + if (partialIgnores != null && partialIgnores.Contains(member.Name)) continue; + + bool forced = false, isPublic, isField; + Type effectiveType; + + if (member is PropertyInfo property) + { + if (isEnum) continue; // wasn't expecting any props! + MemberInfo backingField = null; + if (!property.CanWrite) + { + // roslyn automatically implemented properties, in particular for get-only properties: <{Name}>k__BackingField; + var backingFieldName = $"<{property.Name}>k__BackingField"; + foreach (var fieldMemeber in foundList) + { + if ((fieldMemeber as FieldInfo != null) && fieldMemeber.Name == backingFieldName) + { + backingField = fieldMemeber; + break; + } + } + } + effectiveType = property.PropertyType; + isPublic = Helpers.GetGetMethod(property, false, false) != null; + isField = false; + ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue, backingField); + } + else if (member is FieldInfo field) + { + effectiveType = field.FieldType; + isPublic = field.IsPublic; + isField = true; + if (isEnum && !field.IsStatic) + { // only care about static things on enums; WinRT has a __value instance field! + continue; + } + ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue); + } + else if (member is MethodInfo method) + { + if (isEnum) continue; + AttributeMap[] memberAttribs = AttributeMap.Create(model, method, false); + if (memberAttribs != null && memberAttribs.Length > 0) + { + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeSerializationAttribute", ref callbacks, 0); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterSerializationAttribute", ref callbacks, 1); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeDeserializationAttribute", ref callbacks, 2); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterDeserializationAttribute", ref callbacks, 3); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializingAttribute", ref callbacks, 4); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializedAttribute", ref callbacks, 5); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializingAttribute", ref callbacks, 6); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializedAttribute", ref callbacks, 7); + } + } + } + + if (isEnum && enumShouldUseImplicitPassThru && !hasConflictingEnumValue) + { + EnumPassthru = true; + // but leave isEnum alone + } + var arr = new ProtoMemberAttribute[members.Count]; + members.CopyTo(arr, 0); + + if (inferTagByName || implicitMode != ImplicitFields.None) + { + Array.Sort(arr); + int nextTag = implicitFirstTag; + foreach (ProtoMemberAttribute normalizedAttribute in arr) + { + if (!normalizedAttribute.TagIsPinned) // if ProtoMember etc sets a tag, we'll trust it + { + normalizedAttribute.Rebase(nextTag++); + } + } + } + + foreach (ProtoMemberAttribute normalizedAttribute in arr) + { + ValueMember vm = ApplyDefaultBehaviour(isEnum, normalizedAttribute); + if (vm != null) + { + Add(vm); + } + } + + if (callbacks != null) + { + SetCallbacks(Coalesce(callbacks, 0, 4), Coalesce(callbacks, 1, 5), + Coalesce(callbacks, 2, 6), Coalesce(callbacks, 3, 7)); + } + } + + private static void ApplyDefaultBehaviour_AddMembers(TypeModel model, AttributeFamily family, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferTagByName, ImplicitFields implicitMode, BasicList members, MemberInfo member, ref bool forced, bool isPublic, bool isField, ref Type effectiveType, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + switch (implicitMode) + { + case ImplicitFields.AllFields: + if (isField) forced = true; + break; + case ImplicitFields.AllPublic: + if (isPublic) forced = true; + break; + } + + // we just don't like delegate types ;p +#if COREFX || PROFILE259 + if (effectiveType.GetTypeInfo().IsSubclassOf(typeof(Delegate))) effectiveType = null; +#else + if (effectiveType.IsSubclassOf(model.MapType(typeof(Delegate)))) effectiveType = null; +#endif + if (effectiveType != null) + { + ProtoMemberAttribute normalizedAttribute = NormalizeProtoMember(model, member, family, forced, isEnum, partialMembers, dataMemberOffset, inferTagByName, ref hasConflictingEnumValue, backingMember); + if (normalizedAttribute != null) members.Add(normalizedAttribute); + } + } + + static MethodInfo Coalesce(MethodInfo[] arr, int x, int y) + { + MethodInfo mi = arr[x]; + if (mi == null) mi = arr[y]; + return mi; + } + + internal static AttributeFamily GetContractFamily(RuntimeTypeModel model, Type type, AttributeMap[] attributes) + { + AttributeFamily family = AttributeFamily.None; + + if (attributes == null) attributes = AttributeMap.Create(model, type, false); + + for (int i = 0; i < attributes.Length; i++) + { + switch (attributes[i].AttributeType.FullName) + { + case "ProtoBuf.ProtoContractAttribute": + bool tmp = false; + GetFieldBoolean(ref tmp, attributes[i], "UseProtoMembersOnly"); + if (tmp) return AttributeFamily.ProtoBuf; + family |= AttributeFamily.ProtoBuf; + break; + case "System.Xml.Serialization.XmlTypeAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + family |= AttributeFamily.XmlSerializer; + } + break; + case "System.Runtime.Serialization.DataContractAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + family |= AttributeFamily.DataContractSerialier; + } + break; + } + } + if (family == AttributeFamily.None) + { // check for obvious tuples + if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null) + { + family |= AttributeFamily.AutoTuple; + } + } + return family; + } + internal static ConstructorInfo ResolveTupleConstructor(Type type, out MemberInfo[] mappedMembers) + { + mappedMembers = null; + if (type == null) throw new ArgumentNullException(nameof(type)); +#if COREFX || PROFILE259 + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsAbstract) return null; // as if! + ConstructorInfo[] ctors = Helpers.GetConstructors(typeInfo, false); +#else + if (type.IsAbstract) return null; // as if! + ConstructorInfo[] ctors = Helpers.GetConstructors(type, false); +#endif + // need to have an interesting constructor to bother even checking this stuff + if (ctors.Length == 0 || (ctors.Length == 1 && ctors[0].GetParameters().Length == 0)) return null; + + MemberInfo[] fieldsPropsUnfiltered = Helpers.GetInstanceFieldsAndProperties(type, true); + BasicList memberList = new BasicList(); + // for most types we'll enforce that you need readonly, because that is what protobuf-net + // always did historically; but: if you smell so much like a Tuple that it is *in your name*, + // we'll let you past that + bool demandReadOnly = type.Name.IndexOf("Tuple", StringComparison.OrdinalIgnoreCase) < 0; + for (int i = 0; i < fieldsPropsUnfiltered.Length; i++) + { + if (fieldsPropsUnfiltered[i] is PropertyInfo prop) + { + if (!prop.CanRead) return null; // no use if can't read + if (demandReadOnly && prop.CanWrite && Helpers.GetSetMethod(prop, false, false) != null) return null; // don't allow a public set (need to allow non-public to handle Mono's KeyValuePair<,>) + memberList.Add(prop); + } + else + { + if (fieldsPropsUnfiltered[i] is FieldInfo field) + { + if (demandReadOnly && !field.IsInitOnly) return null; // all public fields must be readonly to be counted a tuple + memberList.Add(field); + } + } + } + if (memberList.Count == 0) + { + return null; + } + + MemberInfo[] members = new MemberInfo[memberList.Count]; + memberList.CopyTo(members, 0); + + int[] mapping = new int[members.Length]; + int found = 0; + ConstructorInfo result = null; + mappedMembers = new MemberInfo[mapping.Length]; + for (int i = 0; i < ctors.Length; i++) + { + ParameterInfo[] parameters = ctors[i].GetParameters(); + + if (parameters.Length != members.Length) continue; + + // reset the mappings to test + for (int j = 0; j < mapping.Length; j++) mapping[j] = -1; + + for (int j = 0; j < parameters.Length; j++) + { + for (int k = 0; k < members.Length; k++) + { + if (string.Compare(parameters[j].Name, members[k].Name, StringComparison.OrdinalIgnoreCase) != 0) continue; + Type memberType = Helpers.GetMemberType(members[k]); + if (memberType != parameters[j].ParameterType) continue; + + mapping[j] = k; + } + } + // did we map all? + bool notMapped = false; + for (int j = 0; j < mapping.Length; j++) + { + if (mapping[j] < 0) + { + notMapped = true; + break; + } + mappedMembers[j] = members[mapping[j]]; + } + + if (notMapped) continue; + found++; + result = ctors[i]; + + } + return found == 1 ? result : null; + } + + private static void CheckForCallback(MethodInfo method, AttributeMap[] attributes, string callbackTypeName, ref MethodInfo[] callbacks, int index) + { + for (int i = 0; i < attributes.Length; i++) + { + if (attributes[i].AttributeType.FullName == callbackTypeName) + { + if (callbacks == null) { callbacks = new MethodInfo[8]; } + else if (callbacks[index] != null) + { +#if COREFX || PROFILE259 + Type reflected = method.DeclaringType; +#else + Type reflected = method.ReflectedType; +#endif + throw new ProtoException("Duplicate " + callbackTypeName + " callbacks on " + reflected.FullName); + } + callbacks[index] = method; + } + } + } + private static bool HasFamily(AttributeFamily value, AttributeFamily required) + { + return (value & required) == required; + } + + private static ProtoMemberAttribute NormalizeProtoMember(TypeModel model, MemberInfo member, AttributeFamily family, bool forced, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferByTagName, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + if (member == null || (family == AttributeFamily.None && !isEnum)) return null; // nix + int fieldNumber = int.MinValue, minAcceptFieldNumber = inferByTagName ? -1 : 1; + string name = null; + bool isPacked = false, ignore = false, done = false, isRequired = false, asReference = false, asReferenceHasValue = false, dynamicType = false, tagIsPinned = false, overwriteList = false; + DataFormat dataFormat = DataFormat.Default; + if (isEnum) forced = true; + AttributeMap[] attribs = AttributeMap.Create(model, member, true); + AttributeMap attrib; + + if (isEnum) + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoIgnoreAttribute"); + if (attrib != null) + { + ignore = true; + } + else + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoEnumAttribute"); +#if PORTABLE || CF || COREFX || PROFILE259 + fieldNumber = Convert.ToInt32(((FieldInfo)member).GetValue(null)); +#else + fieldNumber = Convert.ToInt32(((FieldInfo)member).GetRawConstantValue()); +#endif + if (attrib != null) + { + GetFieldName(ref name, attrib, nameof(ProtoEnumAttribute.Name)); + + if ((bool)Helpers.GetInstanceMethod(attrib.AttributeType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + , nameof(ProtoEnumAttribute.HasValue)).Invoke(attrib.Target, null)) + { + if (attrib.TryGet(nameof(ProtoEnumAttribute.Value), out object tmp)) + { + if (fieldNumber != (int)tmp) + { + hasConflictingEnumValue = true; + } + fieldNumber = (int)tmp; + } + } + } + + } + done = true; + } + + if (!ignore && !done) // always consider ProtoMember + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoMemberAttribute"); + GetIgnore(ref ignore, attrib, attribs, "ProtoBuf.ProtoIgnoreAttribute"); + + if (!ignore && attrib != null) + { + GetFieldNumber(ref fieldNumber, attrib, "Tag"); + GetFieldName(ref name, attrib, "Name"); + GetFieldBoolean(ref isRequired, attrib, "IsRequired"); + GetFieldBoolean(ref isPacked, attrib, "IsPacked"); + GetFieldBoolean(ref overwriteList, attrib, "OverwriteList"); + GetDataFormat(ref dataFormat, attrib, "DataFormat"); + GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false); + + if (asReferenceHasValue) + { + asReferenceHasValue = GetFieldBoolean(ref asReference, attrib, "AsReference", true); + } + GetFieldBoolean(ref dynamicType, attrib, "DynamicType"); + done = tagIsPinned = fieldNumber > 0; // note minAcceptFieldNumber only applies to non-proto + } + + if (!done && partialMembers != null) + { + foreach (AttributeMap ppma in partialMembers) + { + if (ppma.TryGet("MemberName", out object tmp) && (string)tmp == member.Name) + { + GetFieldNumber(ref fieldNumber, ppma, "Tag"); + GetFieldName(ref name, ppma, "Name"); + GetFieldBoolean(ref isRequired, ppma, "IsRequired"); + GetFieldBoolean(ref isPacked, ppma, "IsPacked"); + GetFieldBoolean(ref overwriteList, attrib, "OverwriteList"); + GetDataFormat(ref dataFormat, ppma, "DataFormat"); + GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false); + + if (asReferenceHasValue) + { + asReferenceHasValue = GetFieldBoolean(ref asReference, ppma, "AsReference", true); + } + GetFieldBoolean(ref dynamicType, ppma, "DynamicType"); + if (done = tagIsPinned = fieldNumber > 0) break; // note minAcceptFieldNumber only applies to non-proto + } + } + } + } + + if (!ignore && !done && HasFamily(family, AttributeFamily.DataContractSerialier)) + { + attrib = GetAttribute(attribs, "System.Runtime.Serialization.DataMemberAttribute"); + if (attrib != null) + { + GetFieldNumber(ref fieldNumber, attrib, "Order"); + GetFieldName(ref name, attrib, "Name"); + GetFieldBoolean(ref isRequired, attrib, "IsRequired"); + done = fieldNumber >= minAcceptFieldNumber; + if (done) fieldNumber += dataMemberOffset; // dataMemberOffset only applies to DCS flags, to allow us to "bump" WCF by a notch + } + } + if (!ignore && !done && HasFamily(family, AttributeFamily.XmlSerializer)) + { + attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlElementAttribute"); + if (attrib == null) attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlArrayAttribute"); + GetIgnore(ref ignore, attrib, attribs, "System.Xml.Serialization.XmlIgnoreAttribute"); + if (attrib != null && !ignore) + { + GetFieldNumber(ref fieldNumber, attrib, "Order"); + GetFieldName(ref name, attrib, "ElementName"); + done = fieldNumber >= minAcceptFieldNumber; + } + } + if (!ignore && !done) + { + if (GetAttribute(attribs, "System.NonSerializedAttribute") != null) ignore = true; + } + if (ignore || (fieldNumber < minAcceptFieldNumber && !forced)) return null; + ProtoMemberAttribute result = new ProtoMemberAttribute(fieldNumber, forced || inferByTagName) + { + AsReference = asReference, + AsReferenceHasValue = asReferenceHasValue, + DataFormat = dataFormat, + DynamicType = dynamicType, + IsPacked = isPacked, + OverwriteList = overwriteList, + IsRequired = isRequired, + Name = string.IsNullOrEmpty(name) ? member.Name : name, + Member = member, + BackingMember = backingMember, + TagIsPinned = tagIsPinned + }; + return result; + } + + private ValueMember ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute) + { + MemberInfo member; + if (normalizedAttribute == null || (member = normalizedAttribute.Member) == null) return null; // nix + + Type effectiveType = Helpers.GetMemberType(member); + + + Type itemType = null; + Type defaultType = null; + + // check for list types + ResolveListTypes(model, effectiveType, ref itemType, ref defaultType); + bool ignoreListHandling = false; + // but take it back if it is explicitly excluded + if (itemType != null) + { // looks like a list, but double check for IgnoreListHandling + int idx = model.FindOrAddAuto(effectiveType, false, true, false); + if (idx >= 0 && (ignoreListHandling = model[effectiveType].IgnoreListHandling)) + { + itemType = null; + defaultType = null; + } + } + AttributeMap[] attribs = AttributeMap.Create(model, member, true); + AttributeMap attrib; + + object defaultValue = null; + // implicit zero default + if (model.UseImplicitZeroDefaults) + { + switch (Helpers.GetTypeCode(effectiveType)) + { + case ProtoTypeCode.Boolean: defaultValue = false; break; + case ProtoTypeCode.Decimal: defaultValue = (decimal)0; break; + case ProtoTypeCode.Single: defaultValue = (float)0; break; + case ProtoTypeCode.Double: defaultValue = (double)0; break; + case ProtoTypeCode.Byte: defaultValue = (byte)0; break; + case ProtoTypeCode.Char: defaultValue = (char)0; break; + case ProtoTypeCode.Int16: defaultValue = (short)0; break; + case ProtoTypeCode.Int32: defaultValue = (int)0; break; + case ProtoTypeCode.Int64: defaultValue = (long)0; break; + case ProtoTypeCode.SByte: defaultValue = (sbyte)0; break; + case ProtoTypeCode.UInt16: defaultValue = (ushort)0; break; + case ProtoTypeCode.UInt32: defaultValue = (uint)0; break; + case ProtoTypeCode.UInt64: defaultValue = (ulong)0; break; + case ProtoTypeCode.TimeSpan: defaultValue = TimeSpan.Zero; break; + case ProtoTypeCode.Guid: defaultValue = Guid.Empty; break; + } + } + if ((attrib = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null) + { + if (attrib.TryGet("Value", out object tmp)) defaultValue = tmp; + } + ValueMember vm = ((isEnum || normalizedAttribute.Tag > 0)) + ? new ValueMember(model, type, normalizedAttribute.Tag, member, effectiveType, itemType, defaultType, normalizedAttribute.DataFormat, defaultValue) + : null; + if (vm != null) + { + vm.BackingMember = normalizedAttribute.BackingMember; +#if COREFX || PROFILE259 + TypeInfo finalType = typeInfo; +#else + Type finalType = type; +#endif + PropertyInfo prop = Helpers.GetProperty(finalType, member.Name + "Specified", true); + MethodInfo getMethod = Helpers.GetGetMethod(prop, true, true); + if (getMethod == null || getMethod.IsStatic) prop = null; + if (prop != null) + { + vm.SetSpecified(getMethod, Helpers.GetSetMethod(prop, true, true)); + } + else + { + MethodInfo method = Helpers.GetInstanceMethod(finalType, "ShouldSerialize" + member.Name, Helpers.EmptyTypes); + if (method != null && method.ReturnType == model.MapType(typeof(bool))) + { + vm.SetSpecified(method, null); + } + } + if (!string.IsNullOrEmpty(normalizedAttribute.Name)) vm.SetName(normalizedAttribute.Name); + vm.IsPacked = normalizedAttribute.IsPacked; + vm.IsRequired = normalizedAttribute.IsRequired; + vm.OverwriteList = normalizedAttribute.OverwriteList; + if (normalizedAttribute.AsReferenceHasValue) + { + vm.AsReference = normalizedAttribute.AsReference; + } + vm.DynamicType = normalizedAttribute.DynamicType; + + vm.IsMap = ignoreListHandling ? false : vm.ResolveMapTypes(out var _, out var _, out var _); + if (vm.IsMap) // is it even *allowed* to be a map? + { + if ((attrib = GetAttribute(attribs, "ProtoBuf.ProtoMapAttribute")) != null) + { + if (attrib.TryGet(nameof(ProtoMapAttribute.DisableMap), out object tmp) && (bool)tmp) + { + vm.IsMap = false; + } + else + { + if (attrib.TryGet(nameof(ProtoMapAttribute.KeyFormat), out tmp)) vm.MapKeyFormat = (DataFormat)tmp; + if (attrib.TryGet(nameof(ProtoMapAttribute.ValueFormat), out tmp)) vm.MapValueFormat = (DataFormat)tmp; + } + } + } + + } + return vm; + } + + private static void GetDataFormat(ref DataFormat value, AttributeMap attrib, string memberName) + { + if ((attrib == null) || (value != DataFormat.Default)) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) value = (DataFormat)obj; + } + + private static void GetIgnore(ref bool ignore, AttributeMap attrib, AttributeMap[] attribs, string fullName) + { + if (ignore || attrib == null) return; + ignore = GetAttribute(attribs, fullName) != null; + return; + } + + private static void GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName) + { + GetFieldBoolean(ref value, attrib, memberName, true); + } + private static bool GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName, bool publicOnly) + { + if (attrib == null) return false; + if (value) return true; + if (attrib.TryGet(memberName, publicOnly, out object obj) && obj != null) + { + value = (bool)obj; + return true; + } + return false; + } + + private static void GetFieldNumber(ref int value, AttributeMap attrib, string memberName) + { + if (attrib == null || value > 0) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) value = (int)obj; + } + + private static void GetFieldName(ref string name, AttributeMap attrib, string memberName) + { + if (attrib == null || !string.IsNullOrEmpty(name)) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) name = (string)obj; + } + + private static AttributeMap GetAttribute(AttributeMap[] attribs, string fullName) + { + for (int i = 0; i < attribs.Length; i++) + { + AttributeMap attrib = attribs[i]; + if (attrib != null && attrib.AttributeType.FullName == fullName) return attrib; + } + return null; + } + + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(int fieldNumber, string memberName) + { + AddField(fieldNumber, memberName, null, null, null); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, returning the ValueMember rather than the fluent API. + /// This is otherwise identical to Add. + /// + public ValueMember AddField(int fieldNumber, string memberName) + { + return AddField(fieldNumber, memberName, null, null, null); + } + + /// + /// Gets or sets whether the type should use a parameterless constructor (the default), + /// or whether the type should skip the constructor completely. This option is not supported + /// on compact-framework. + /// + public bool UseConstructor + { // negated to have defaults as flat zero + get { return !HasFlag(OPTIONS_SkipConstructor); } + set { SetFlag(OPTIONS_SkipConstructor, !value, true); } + } + + /// + /// The concrete type to create when a new instance of this type is needed; this may be useful when dealing + /// with dynamic proxies, or with interface-based APIs + /// + public Type ConstructType + { + get { return constructType; } + set + { + ThrowIfFrozen(); + constructType = value; + } + } + + private Type constructType; + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(string memberName) + { + Add(GetNextFieldNumber(), memberName); + return this; + } + + Type surrogate; + /// + /// Performs serialization of this type via a surrogate; all + /// other serialization options are ignored and handled + /// by the surrogate's configuration. + /// + public void SetSurrogate(Type surrogateType) + { + if (surrogateType == type) surrogateType = null; + if (surrogateType != null) + { + // note that BuildSerializer checks the **CURRENT TYPE** is OK to be surrogated + if (surrogateType != null && Helpers.IsAssignableFrom(model.MapType(typeof(IEnumerable)), surrogateType)) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a surrogate"); + } + } + ThrowIfFrozen(); + this.surrogate = surrogateType; + // no point in offering chaining; no options are respected + } + + internal MetaType GetSurrogateOrSelf() + { + if (surrogate != null) return model[surrogate]; + return this; + } + + internal MetaType GetSurrogateOrBaseOrSelf(bool deep) + { + if (surrogate != null) return model[surrogate]; + MetaType snapshot = this.baseType; + if (snapshot != null) + { + if (deep) + { + MetaType tmp; + do + { + tmp = snapshot; + snapshot = snapshot.baseType; + } while (snapshot != null); + return tmp; + } + return snapshot; + } + return this; + } + + private int GetNextFieldNumber() + { + int maxField = 0; + foreach (ValueMember member in fields) + { + if (member.FieldNumber > maxField) maxField = member.FieldNumber; + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + { + if (subType.FieldNumber > maxField) maxField = subType.FieldNumber; + } + } + return maxField + 1; + } + + /// + /// Adds a set of members (by name) to the MetaType + /// + public MetaType Add(params string[] memberNames) + { + if (memberNames == null) throw new ArgumentNullException("memberNames"); + int next = GetNextFieldNumber(); + for (int i = 0; i < memberNames.Length; i++) + { + Add(next++, memberNames[i]); + } + return this; + } + + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(int fieldNumber, string memberName, object defaultValue) + { + AddField(fieldNumber, memberName, null, null, defaultValue); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists + /// + public MetaType Add(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + AddField(fieldNumber, memberName, itemType, defaultType, null); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists, returning the ValueMember rather than the fluent API. + /// This is otherwise identical to Add. + /// + public ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + return AddField(fieldNumber, memberName, itemType, defaultType, null); + } + + private ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType, object defaultValue) + { + MemberInfo mi = null; +#if PROFILE259 + mi = Helpers.IsEnum(type) ? type.GetTypeInfo().GetDeclaredField(memberName) : Helpers.GetInstanceMember(type.GetTypeInfo(), memberName); + +#else + MemberInfo[] members = type.GetMember(memberName, Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (members != null && members.Length == 1) mi = members[0]; +#endif + if (mi == null) throw new ArgumentException("Unable to determine member: " + memberName, "memberName"); + + Type miType; + PropertyInfo pi = null; + FieldInfo fi = null; +#if PORTABLE || COREFX || PROFILE259 + pi = mi as PropertyInfo; + if (pi == null) + { + fi = mi as FieldInfo; + if (fi == null) + { + throw new NotSupportedException(mi.GetType().Name); + } + else + { + miType = fi.FieldType; + } + } + else + { + miType = pi.PropertyType; + } +#else + switch (mi.MemberType) + { + case MemberTypes.Field: + fi = (FieldInfo)mi; + miType = fi.FieldType; break; + case MemberTypes.Property: + pi = (PropertyInfo)mi; + miType = pi.PropertyType; break; + default: + throw new NotSupportedException(mi.MemberType.ToString()); + } +#endif + ResolveListTypes(model, miType, ref itemType, ref defaultType); + + MemberInfo backingField = null; + if (pi?.CanWrite == false) + { + string name = $"<{((PropertyInfo)mi).Name}>k__BackingField"; +#if PROFILE259 + var backingMembers = type.GetTypeInfo().DeclaredMembers; + var memberInfos = backingMembers as MemberInfo[] ?? backingMembers.ToArray(); + if (memberInfos.Count() == 1) + { + MemberInfo first = memberInfos.FirstOrDefault(); + if (first is FieldInfo) + { + backingField = first; + } + } +#else + var backingMembers = type.GetMember($"<{((PropertyInfo)mi).Name}>k__BackingField", Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (backingMembers != null && backingMembers.Length == 1 && (backingMembers[0] as FieldInfo) != null) + backingField = backingMembers[0]; +#endif + } + ValueMember newField = new ValueMember(model, type, fieldNumber, backingField ?? mi, miType, itemType, defaultType, DataFormat.Default, defaultValue); + if (backingField != null) + newField.SetName(mi.Name); + Add(newField); + return newField; + } + + internal static void ResolveListTypes(TypeModel model, Type type, ref Type itemType, ref Type defaultType) + { + if (type == null) return; + // handle arrays + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimensional arrays are not supported"); + } + itemType = type.GetElementType(); + if (itemType == model.MapType(typeof(byte))) + { + defaultType = itemType = null; + } + else + { + defaultType = type; + } + } + // handle lists + if (itemType == null) { itemType = TypeModel.GetListItemType(model, type); } + + // check for nested data (not allowed) + if (itemType != null) + { + Type nestedItemType = null, nestedDefaultType = null; + ResolveListTypes(model, itemType, ref nestedItemType, ref nestedDefaultType); + if (nestedItemType != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + + if (itemType != null && defaultType == null) + { +#if COREFX || PROFILE259 + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null) +#else + if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null) +#endif + { + defaultType = type; + } + if (defaultType == null) + { +#if COREFX || PROFILE259 + if (typeInfo.IsInterface) +#else + if (type.IsInterface) +#endif + { + + Type[] genArgs; +#if COREFX || PROFILE259 + if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) + && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments)) +#else + if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IDictionary<,>)) + && itemType == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments())) +#endif + { + defaultType = model.MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs); + } + else + { + defaultType = model.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + } + } + } + // verify that the default type is appropriate + if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; } + } + } + + private void Add(ValueMember member) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + fields.Add(member); + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + /// + /// Returns the ValueMember that matchs a given field number, or null if not found + /// + public ValueMember this[int fieldNumber] + { + get + { + foreach (ValueMember member in fields) + { + if (member.FieldNumber == fieldNumber) return member; + } + return null; + } + } + /// + /// Returns the ValueMember that matchs a given member (property/field), or null if not found + /// + public ValueMember this[MemberInfo member] + { + get + { + if (member == null) return null; + foreach (ValueMember x in fields) + { + if (x.Member == member || x.BackingMember == member) return x; + } + return null; + } + } + private readonly BasicList fields = new BasicList(); + + /// + /// Returns the ValueMember instances associated with this type + /// + public ValueMember[] GetFields() + { + ValueMember[] arr = new ValueMember[fields.Count]; + fields.CopyTo(arr, 0); + Array.Sort(arr, ValueMember.Comparer.Default); + return arr; + } + + /// + /// Returns the SubType instances associated with this type + /// + public SubType[] GetSubtypes() + { + if (subTypes == null || subTypes.Count == 0) return new SubType[0]; + SubType[] arr = new SubType[subTypes.Count]; + subTypes.CopyTo(arr, 0); + Array.Sort(arr, SubType.Comparer.Default); + return arr; + } + + internal IEnumerable GetAllGenericArguments() + { + return GetAllGenericArguments(type); + } + + private static IEnumerable GetAllGenericArguments(Type type) + { + +#if PROFILE259 + var genericArguments = type.GetGenericTypeDefinition().GenericTypeArguments; +#else + var genericArguments = type.GetGenericArguments(); +#endif + foreach (var arg in genericArguments) + { + yield return arg; + foreach (var inner in GetAllGenericArguments(arg)) + { + yield return inner; + } + } + } + +#if FEAT_COMPILER + /// + /// Compiles the serializer for this type; this is *not* a full + /// standalone compile, but can significantly boost performance + /// while allowing additional types to be added. + /// + /// An in-place compile can access non-public types / members + public void CompileInPlace() + { + serializer = CompiledSerializer.Wrap(Serializer, model); + } +#endif + + internal bool IsDefined(int fieldNumber) + { + foreach (ValueMember field in fields) + { + if (field.FieldNumber == fieldNumber) return true; + } + return false; + } + + internal int GetKey(bool demand, bool getBaseKey) + { + return model.GetKey(type, demand, getBaseKey); + } + + internal EnumSerializer.EnumPair[] GetEnumMap() + { + if (HasFlag(OPTIONS_EnumPassThru)) return null; + EnumSerializer.EnumPair[] result = new EnumSerializer.EnumPair[fields.Count]; + for (int i = 0; i < result.Length; i++) + { + ValueMember member = (ValueMember)fields[i]; + int wireValue = member.FieldNumber; + object value = member.GetRawEnumValue(); + result[i] = new EnumSerializer.EnumPair(wireValue, value, member.MemberType); + } + return result; + } + + /// + /// Gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather + /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums. + /// + public bool EnumPassthru + { + get { return HasFlag(OPTIONS_EnumPassThru); } + set { SetFlag(OPTIONS_EnumPassThru, value, true); } + } + + /// + /// Gets or sets a value indicating that this type should NOT be treated as a list, even if it has + /// familiar list-like characteristics (enumerable, add, etc) + /// + public bool IgnoreListHandling + { + get { return HasFlag(OPTIONS_IgnoreListHandling); } + set { SetFlag(OPTIONS_IgnoreListHandling, value, true); } + } + + internal bool Pending + { + get { return HasFlag(OPTIONS_Pending); } + set { SetFlag(OPTIONS_Pending, value, false); } + } + + private const ushort + OPTIONS_Pending = 1, + OPTIONS_EnumPassThru = 2, + OPTIONS_Frozen = 4, + OPTIONS_PrivateOnApi = 8, + OPTIONS_SkipConstructor = 16, + OPTIONS_AsReferenceDefault = 32, + OPTIONS_AutoTuple = 64, + OPTIONS_IgnoreListHandling = 128, + OPTIONS_IsGroup = 256; + + private volatile ushort flags; + private bool HasFlag(ushort flag) { return (flags & flag) == flag; } + private void SetFlag(ushort flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + flags |= flag; + else + flags = (ushort)(flags & ~flag); + } + + internal static MetaType GetRootType(MetaType source) + { + while (source.serializer != null) + { + MetaType tmp = source.baseType; + if (tmp == null) return source; + source = tmp; // else loop until we reach something that isn't generated, or is the root + } + + // now we get into uncertain territory + RuntimeTypeModel model = source.model; + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + + MetaType tmp; + while ((tmp = source.baseType) != null) source = tmp; + return source; + + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + internal bool IsPrepared() + { +#if FEAT_COMPILER + return serializer is CompiledSerializer; +#else + return false; +#endif + } + + internal IEnumerable Fields => this.fields; + + internal static StringBuilder NewLine(StringBuilder builder, int indent) + { + return Helpers.AppendLine(builder).Append(' ', indent * 3); + } + + internal bool IsAutoTuple => HasFlag(OPTIONS_AutoTuple); + + /// + /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message) + /// + public bool IsGroup + { + get { return HasFlag(OPTIONS_IsGroup); } + set { SetFlag(OPTIONS_IsGroup, value, true); } + } + + internal void WriteSchema(StringBuilder builder, int indent, ref RuntimeTypeModel.CommonImports imports, ProtoSyntax syntax) + { + if (surrogate != null) return; // nothing to write + + ValueMember[] fieldsArr = new ValueMember[fields.Count]; + fields.CopyTo(fieldsArr, 0); + Array.Sort(fieldsArr, ValueMember.Comparer.Default); + + if (IsList) + { + string itemTypeName = model.GetSchemaTypeName(TypeModel.GetListItemType(model, type), DataFormat.Default, false, false, ref imports); + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + NewLine(builder, indent + 1).Append("repeated ").Append(itemTypeName).Append(" items = 1;"); + NewLine(builder, indent).Append('}'); + } + else if (IsAutoTuple) + { // key-value-pair etc + + if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null) + { + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + for (int i = 0; i < mapping.Length; i++) + { + Type effectiveType; + if (mapping[i] is PropertyInfo property) + { + effectiveType = property.PropertyType; + } + else if (mapping[i] is FieldInfo field) + { + effectiveType = field.FieldType; + } + else + { + throw new NotSupportedException("Unknown member type: " + mapping[i].GetType().Name); + } + NewLine(builder, indent + 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(model.GetSchemaTypeName(effectiveType, DataFormat.Default, false, false, ref imports).Replace('.', '_')) + .Append(' ').Append(mapping[i].Name).Append(" = ").Append(i + 1).Append(';'); + } + NewLine(builder, indent).Append('}'); + } + } + else if (Helpers.IsEnum(type)) + { + NewLine(builder, indent).Append("enum ").Append(GetSchemaTypeName()).Append(" {"); + if (fieldsArr.Length == 0 && EnumPassthru) + { + if (type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif +.IsDefined(model.MapType(typeof(FlagsAttribute)), false)) + { + NewLine(builder, indent + 1).Append("// this is a composite/flags enumeration"); + } + else + { + NewLine(builder, indent + 1).Append("// this enumeration will be passed as a raw value"); + } + foreach (FieldInfo field in +#if PROFILE259 + type.GetRuntimeFields() +#else + type.GetFields() +#endif + + ) + { + if (field.IsStatic && field.IsLiteral) + { + object enumVal; +#if PORTABLE || CF || NETSTANDARD1_3 || NETSTANDARD1_4 || PROFILE259 || UAP + enumVal = Convert.ChangeType(field.GetValue(null), Enum.GetUnderlyingType(field.FieldType), System.Globalization.CultureInfo.InvariantCulture); +#else + enumVal = field.GetRawConstantValue(); +#endif + NewLine(builder, indent + 1).Append(field.Name).Append(" = ").Append(enumVal).Append(";"); + } + } + + } + else + { + Dictionary countByField = new Dictionary(fieldsArr.Length); + bool needsAlias = false; + foreach (var field in fieldsArr) + { + if (countByField.ContainsKey(field.FieldNumber)) + { // no point actually counting; that's enough to know we have a problem + needsAlias = true; + break; + } + countByField.Add(field.FieldNumber, 1); + } + if (needsAlias) + { // duplicated value requires allow_alias + NewLine(builder, indent + 1).Append("option allow_alias = true;"); + } + + bool haveWrittenZero = false; + // write zero values **first** + foreach (ValueMember member in fieldsArr) + { + if (member.FieldNumber == 0) + { + NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';'); + haveWrittenZero = true; + } + } + if (syntax == ProtoSyntax.Proto3 && !haveWrittenZero) + { + NewLine(builder, indent + 1).Append("ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)"); + } + // note array is already sorted, so zero would already be first + foreach (ValueMember member in fieldsArr) + { + if (member.FieldNumber == 0) continue; + NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';'); + } + } + NewLine(builder, indent).Append('}'); + } + else + { + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + foreach (ValueMember member in fieldsArr) + { + string schemaTypeName; + bool hasOption = false; + if (member.IsMap) + { + member.ResolveMapTypes(out var _, out var keyType, out var valueType); + + var keyTypeName = model.GetSchemaTypeName(keyType, member.MapKeyFormat, false, false, ref imports); + schemaTypeName = model.GetSchemaTypeName(valueType, member.MapKeyFormat, member.AsReference, member.DynamicType, ref imports); + NewLine(builder, indent + 1).Append("map<").Append(keyTypeName).Append(",").Append(schemaTypeName).Append("> ") + .Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(";"); + } + else + { + string ordinality = member.ItemType != null ? "repeated " : (syntax == ProtoSyntax.Proto2 ? (member.IsRequired ? "required " : "optional ") : ""); + NewLine(builder, indent + 1).Append(ordinality); + if (member.DataFormat == DataFormat.Group) builder.Append("group "); + schemaTypeName = member.GetSchemaTypeName(true, ref imports); + builder.Append(schemaTypeName).Append(" ") + .Append(member.Name).Append(" = ").Append(member.FieldNumber); + + if (syntax == ProtoSyntax.Proto2 && member.DefaultValue != null && member.IsRequired == false) + { + if (member.DefaultValue is string) + { + AddOption(builder, ref hasOption).Append("default = \"").Append(member.DefaultValue).Append("\""); + } + else if (member.DefaultValue is TimeSpan) + { + // ignore + } + else if (member.DefaultValue is bool) + { // need to be lower case (issue 304) + AddOption(builder, ref hasOption).Append((bool)member.DefaultValue ? "default = true" : "default = false"); + } + else + { + AddOption(builder, ref hasOption).Append("default = ").Append(member.DefaultValue); + } + } + if (CanPack(member.ItemType)) + { + if (syntax == ProtoSyntax.Proto2) + { + if (member.IsPacked) AddOption(builder, ref hasOption).Append("packed = true"); // disabled by default + } + else + { + if (!member.IsPacked) AddOption(builder, ref hasOption).Append("packed = false"); // enabled by default + } + } + if (member.AsReference) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).asRef = true"); + } + if (member.DynamicType) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).dynamicType = true"); + } + CloseOption(builder, ref hasOption).Append(';'); + if (syntax != ProtoSyntax.Proto2 && member.DefaultValue != null && !member.IsRequired) + { + if (IsImplicitDefault(member.DefaultValue)) + { + // don't emit; we're good + } + else + { + builder.Append(" // default value could not be applied: ").Append(member.DefaultValue); + } + } + } + if (schemaTypeName == ".bcl.NetObjectProxy" && member.AsReference && !member.DynamicType) // we know what it is; tell the user + { + builder.Append(" // reference-tracked ").Append(member.GetSchemaTypeName(false, ref imports)); + } + } + if (subTypes != null && subTypes.Count != 0) + { + SubType[] subTypeArr = new SubType[subTypes.Count]; + subTypes.CopyTo(subTypeArr, 0); + Array.Sort(subTypeArr, SubType.Comparer.Default); + string[] fieldNames = new string[subTypeArr.Length]; + for(int i = 0; i < subTypeArr.Length;i++) + fieldNames[i] = subTypeArr[i].DerivedType.GetSchemaTypeName(); + + string fieldName = "subtype"; + while (Array.IndexOf(fieldNames, fieldName) >= 0) + fieldName = "_" + fieldName; + + NewLine(builder, indent + 1).Append("oneof ").Append(fieldName).Append(" {"); + for(int i = 0; i < subTypeArr.Length; i++) + { + var subTypeName = fieldNames[i]; + NewLine(builder, indent + 2).Append(subTypeName) + .Append(" ").Append(subTypeName).Append(" = ").Append(subTypeArr[i].FieldNumber).Append(';'); + } + NewLine(builder, indent + 1).Append("}"); + } + NewLine(builder, indent).Append('}'); + } + } + + private static StringBuilder AddOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + return builder.Append(", "); + hasOption = true; + return builder.Append(" ["); + } + + private static StringBuilder CloseOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + { + hasOption = false; + return builder.Append("]"); + } + return builder; + } + + private static bool IsImplicitDefault(object value) + { + try + { + if (value == null) return false; + switch (Helpers.GetTypeCode(value.GetType())) + { + case ProtoTypeCode.Boolean: return ((bool)value) == false; + case ProtoTypeCode.Byte: return ((byte)value) == (byte)0; + case ProtoTypeCode.Char: return ((char)value) == (char)0; + case ProtoTypeCode.DateTime: return ((DateTime)value) == default; + case ProtoTypeCode.Decimal: return ((decimal)value) == 0M; + case ProtoTypeCode.Double: return ((double)value) == (double)0; + case ProtoTypeCode.Int16: return ((short)value) == (short)0; + case ProtoTypeCode.Int32: return ((int)value) == (int)0; + case ProtoTypeCode.Int64: return ((long)value) == (long)0; + case ProtoTypeCode.SByte: return ((sbyte)value) == (sbyte)0; + case ProtoTypeCode.Single: return ((float)value) == (float)0; + case ProtoTypeCode.String: return ((string)value) == ""; + case ProtoTypeCode.TimeSpan: return ((TimeSpan)value) == TimeSpan.Zero; + case ProtoTypeCode.UInt16: return ((ushort)value) == (ushort)0; + case ProtoTypeCode.UInt32: return ((uint)value) == (uint)0; + case ProtoTypeCode.UInt64: return ((ulong)value) == (ulong)0; + } + } + catch { } + return false; + } + + private static bool CanPack(Type type) + { + if (type == null) return false; + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Double: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Single: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + return true; + } + return false; + } + + /// + /// Apply a shift to all fields (and sub-types) on this type + /// + /// The change in field number to apply + /// The resultant field numbers must still all be considered valid +#if !(NETSTANDARD1_0 || NETSTANDARD1_3 || UAP) + [System.ComponentModel.Browsable(false)] +#endif + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public void ApplyFieldOffset(int offset) + { + if (Helpers.IsEnum(type)) throw new InvalidOperationException("Cannot apply field-offset to an enum"); + if (offset == 0) return; // nothing to do + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + + if (fields != null) + { + foreach(ValueMember field in fields) + AssertValidFieldNumber(field.FieldNumber + offset); + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + AssertValidFieldNumber(subType.FieldNumber + offset); + } + + // we've checked the ranges are all OK; since we're moving everything, we can't overlap ourselves + // so: we can just move + if (fields != null) + { + foreach (ValueMember field in fields) + field.FieldNumber += offset; + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + subType.FieldNumber += offset; + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + internal static void AssertValidFieldNumber(int fieldNumber) + { + if (fieldNumber < 1) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs.meta new file mode 100644 index 0000000..877943e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/MetaType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d95bfc540d2f67148ba9650839b838d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs new file mode 100644 index 0000000..ab90d5b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs @@ -0,0 +1,17 @@ +namespace ProtoBuf.Meta +{ + /// + /// Indiate the variant of the protobuf .proto DSL syntax to use + /// + public enum ProtoSyntax + { + /// + /// https://developers.google.com/protocol-buffers/docs/proto + /// + Proto2 = 0, + /// + /// https://developers.google.com/protocol-buffers/docs/proto3 + /// + Proto3 = 1, + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta new file mode 100644 index 0000000..5891135 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2bb17e5358dc5c14db480b2b72bce014 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs new file mode 100644 index 0000000..05dfcf1 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs @@ -0,0 +1,2036 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Text; +using System.Reflection; +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +using ProtoBuf.Serializers; +using System.Threading; +using System.IO; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace ProtoBuf.Meta +{ + /// + /// Provides protobuf serialization support for a number of types that can be defined at runtime + /// + public sealed class RuntimeTypeModel : TypeModel + { + private ushort options; + private const ushort + OPTIONS_InferTagFromNameDefault = 1, + OPTIONS_IsDefaultModel = 2, + OPTIONS_Frozen = 4, + OPTIONS_AutoAddMissingTypes = 8, +#if FEAT_COMPILER + OPTIONS_AutoCompile = 16, +#endif + OPTIONS_UseImplicitZeroDefaults = 32, + OPTIONS_AllowParseableTypes = 64, + OPTIONS_AutoAddProtoContractTypesOnly = 128, + OPTIONS_IncludeDateTimeKind = 256, + OPTIONS_DoNotInternStrings = 512; + + private bool GetOption(ushort option) + { + return (options & option) == option; + } + + private void SetOption(ushort option, bool value) + { + if (value) options |= option; + else options &= (ushort)~option; + } + + /// + /// Global default that + /// enables/disables automatic tag generation based on the existing name / order + /// of the defined members. See + /// for usage and important warning / explanation. + /// You must set the global default before attempting to serialize/deserialize any + /// impacted type. + /// + public bool InferTagFromNameDefault + { + get { return GetOption(OPTIONS_InferTagFromNameDefault); } + set { SetOption(OPTIONS_InferTagFromNameDefault, value); } + } + + /// + /// Global default that determines whether types are considered serializable + /// if they have [DataContract] / [XmlType]. With this enabled, ONLY + /// types marked as [ProtoContract] are added automatically. + /// + public bool AutoAddProtoContractTypesOnly + { + get { return GetOption(OPTIONS_AutoAddProtoContractTypesOnly); } + set { SetOption(OPTIONS_AutoAddProtoContractTypesOnly, value); } + } + + /// + /// Global switch that enables or disables the implicit + /// handling of "zero defaults"; meanning: if no other default is specified, + /// it assumes bools always default to false, integers to zero, etc. + /// + /// If this is disabled, no such assumptions are made and only *explicit* + /// default values are processed. This is enabled by default to + /// preserve similar logic to v1. + /// + public bool UseImplicitZeroDefaults + { + get { return GetOption(OPTIONS_UseImplicitZeroDefaults); } + set + { + if (!value && GetOption(OPTIONS_IsDefaultModel)) + { + throw new InvalidOperationException("UseImplicitZeroDefaults cannot be disabled on the default model"); + } + SetOption(OPTIONS_UseImplicitZeroDefaults, value); + } + } + + /// + /// Global switch that determines whether types with a .ToString() and a Parse(string) + /// should be serialized as strings. + /// + public bool AllowParseableTypes + { + get { return GetOption(OPTIONS_AllowParseableTypes); } + set { SetOption(OPTIONS_AllowParseableTypes, value); } + } + + /// + /// Global switch that determines whether DateTime serialization should include the Kind of the date/time. + /// + public bool IncludeDateTimeKind + { + get { return GetOption(OPTIONS_IncludeDateTimeKind); } + set { SetOption(OPTIONS_IncludeDateTimeKind, value); } + } + + /// + /// Global switch that determines whether a single instance of the same string should be used during deserialization. + /// + /// Note this does not use the global .NET string interner + public bool InternStrings + { + get { return !GetOption(OPTIONS_DoNotInternStrings); } + set { SetOption(OPTIONS_DoNotInternStrings, !value); } + } + + /// + /// Should the Kind be included on date/time values? + /// + protected internal override bool SerializeDateTimeKind() + { + return GetOption(OPTIONS_IncludeDateTimeKind); + } + + private sealed class Singleton + { + private Singleton() { } + internal static readonly RuntimeTypeModel Value = new RuntimeTypeModel(true); + } + + /// + /// The default model, used to support ProtoBuf.Serializer + /// + public static RuntimeTypeModel Default => Singleton.Value; + + /// + /// Returns a sequence of the Type instances that can be + /// processed by this model. + /// + public IEnumerable GetTypes() => types; + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + /// The .proto syntax to use + public override string GetSchema(Type type, ProtoSyntax syntax) + { + BasicList requiredTypes = new BasicList(); + MetaType primaryType = null; + bool isInbuiltType = false; + if (type == null) + { // generate for the entire model + foreach (MetaType meta in types) + { + MetaType tmp = meta.GetSurrogateOrBaseOrSelf(false); + if (!requiredTypes.Contains(tmp)) + { // ^^^ note that the type might have been added as a descendent + requiredTypes.Add(tmp); + CascadeDependents(requiredTypes, tmp); + } + } + } + else + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + + WireType defaultWireType; + isInbuiltType = (ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out defaultWireType, false, false, false, false) != null); + if (!isInbuiltType) + { + //Agenerate just relative to the supplied type + int index = FindOrAddAuto(type, false, false, false); + if (index < 0) throw new ArgumentException("The type specified is not a contract-type", "type"); + + // get the required types + primaryType = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false); + requiredTypes.Add(primaryType); + CascadeDependents(requiredTypes, primaryType); + } + } + + // use the provided type's namespace for the "package" + StringBuilder headerBuilder = new StringBuilder(); + string package = null; + + if (!isInbuiltType) + { + IEnumerable typesForNamespace = primaryType == null ? types : requiredTypes; + foreach (MetaType meta in typesForNamespace) + { + if (meta.IsList) continue; + string tmp = meta.Type.Namespace; + if (!string.IsNullOrEmpty(tmp)) + { + if (tmp.StartsWith("System.")) continue; + if (package == null) + { // haven't seen any suggestions yet + package = tmp; + } + else if (package == tmp) + { // that's fine; a repeat of the one we already saw + } + else + { // something else; have confliucting suggestions; abort + package = null; + break; + } + } + } + } + switch (syntax) + { + case ProtoSyntax.Proto2: + headerBuilder.AppendLine(@"syntax = ""proto2"";"); + break; + case ProtoSyntax.Proto3: + headerBuilder.AppendLine(@"syntax = ""proto3"";"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(syntax)); + } + + if (!string.IsNullOrEmpty(package)) + { + headerBuilder.Append("package ").Append(package).Append(';'); + Helpers.AppendLine(headerBuilder); + } + + var imports = CommonImports.None; + StringBuilder bodyBuilder = new StringBuilder(); + // sort them by schema-name + MetaType[] metaTypesArr = new MetaType[requiredTypes.Count]; + requiredTypes.CopyTo(metaTypesArr, 0); + Array.Sort(metaTypesArr, MetaType.Comparer.Default); + + // write the messages + if (isInbuiltType) + { + Helpers.AppendLine(bodyBuilder).Append("message ").Append(type.Name).Append(" {"); + MetaType.NewLine(bodyBuilder, 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(GetSchemaTypeName(type, DataFormat.Default, false, false, ref imports)) + .Append(" value = 1;"); + Helpers.AppendLine(bodyBuilder).Append('}'); + } + else + { + for (int i = 0; i < metaTypesArr.Length; i++) + { + MetaType tmp = metaTypesArr[i]; + if (tmp.IsList && tmp != primaryType) continue; + tmp.WriteSchema(bodyBuilder, 0, ref imports, syntax); + } + } + if ((imports & CommonImports.Bcl) != 0) + { + headerBuilder.Append("import \"protobuf-net/bcl.proto\"; // schema for protobuf-net's handling of core .NET types"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Protogen) != 0) + { + headerBuilder.Append("import \"protobuf-net/protogen.proto\"; // custom protobuf-net options"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Timestamp) != 0) + { + headerBuilder.Append("import \"google/protobuf/timestamp.proto\";"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Duration) != 0) + { + headerBuilder.Append("import \"google/protobuf/duration.proto\";"); + Helpers.AppendLine(headerBuilder); + } + return Helpers.AppendLine(headerBuilder.Append(bodyBuilder)).ToString(); + } + [Flags] + internal enum CommonImports + { + None = 0, + Bcl = 1, + Timestamp = 2, + Duration = 4, + Protogen = 8 + } + private void CascadeDependents(BasicList list, MetaType metaType) + { + MetaType tmp; + if (metaType.IsList) + { + Type itemType = TypeModel.GetListItemType(this, metaType.Type); + TryGetCoreSerializer(list, itemType); + } + else + { + if (metaType.IsAutoTuple) + { + MemberInfo[] mapping; + if (MetaType.ResolveTupleConstructor(metaType.Type, out mapping) != null) + { + for (int i = 0; i < mapping.Length; i++) + { + Type type = null; + if (mapping[i] is PropertyInfo) type = ((PropertyInfo)mapping[i]).PropertyType; + else if (mapping[i] is FieldInfo) type = ((FieldInfo)mapping[i]).FieldType; + TryGetCoreSerializer(list, type); + } + } + } + else + { + foreach (ValueMember member in metaType.Fields) + { + Type type = member.ItemType; + if (member.IsMap) + { + member.ResolveMapTypes(out _, out _, out type); // don't need key-type + } + if (type == null) type = member.MemberType; + TryGetCoreSerializer(list, type); + } + } + foreach (var genericArgument in metaType.GetAllGenericArguments()) + { + TryGetCoreSerializer(list, genericArgument); + } + if (metaType.HasSubtypes) + { + foreach (SubType subType in metaType.GetSubtypes()) + { + tmp = subType.DerivedType.GetSurrogateOrSelf(); // note: exclude base-types! + if (!list.Contains(tmp)) + { + list.Add(tmp); + CascadeDependents(list, tmp); + } + } + } + tmp = metaType.BaseType; + if (tmp != null) tmp = tmp.GetSurrogateOrSelf(); // note: already walking base-types; exclude base + if (tmp != null && !list.Contains(tmp)) + { + list.Add(tmp); + CascadeDependents(list, tmp); + } + } + } + + private void TryGetCoreSerializer(BasicList list, Type itemType) + { + var coreSerializer = ValueMember.TryGetCoreSerializer(this, DataFormat.Default, itemType, out _, false, false, false, false); + if (coreSerializer != null) + { + return; + } + int index = FindOrAddAuto(itemType, false, false, false); + if (index < 0) + { + return; + } + var temp = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false); + if (list.Contains(temp)) + { + return; + } + // could perhaps also implement as a queue, but this should work OK for sane models + list.Add(temp); + CascadeDependents(list, temp); + } + +#if !NO_RUNTIME + /// + /// Creates a new runtime model, to which the caller + /// can add support for a range of types. A model + /// can be used "as is", or can be compiled for + /// optimal performance. + /// + /// not used currently; this is for compatibility with v3 +#pragma warning disable IDE0060 // Remove unused parameter + public static RuntimeTypeModel Create(string name = null) +#pragma warning restore IDE0060 // Remove unused parameter + { + return new RuntimeTypeModel(false); + } +#endif + + private RuntimeTypeModel(bool isDefault) + { + AutoAddMissingTypes = true; + UseImplicitZeroDefaults = true; + SetOption(OPTIONS_IsDefaultModel, isDefault); +#if FEAT_COMPILER && !DEBUG + try + { + AutoCompile = EnableAutoCompile(); + } + catch { } // this is all kinds of brittle on things like UWP +#endif + } + +#if FEAT_COMPILER + [MethodImpl(MethodImplOptions.NoInlining)] + internal static bool EnableAutoCompile() + { + try + { + var dm = new DynamicMethod("CheckCompilerAvailable", typeof(bool), new Type[] { typeof(int) }); + var il = dm.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, 42); + il.Emit(OpCodes.Ceq); + il.Emit(OpCodes.Ret); + var func = (Predicate)dm.CreateDelegate(typeof(Predicate)); + return func(42); + } + catch (Exception ex) + { + Debug.WriteLine(ex); + return false; + } + } +#endif + + /// + /// Obtains the MetaType associated with a given Type for the current model, + /// allowing additional configuration. + /// + public MetaType this[Type type] { get { return (MetaType)types[FindOrAddAuto(type, true, false, false)]; } } + + internal MetaType FindWithoutAdd(Type type) + { + // this list is thread-safe for reading + foreach (MetaType metaType in types) + { + if (metaType.Type == type) + { + if (metaType.Pending) WaitOnLock(metaType); + return metaType; + } + } + // if that failed, check for a proxy + Type underlyingType = ResolveProxies(type); + return underlyingType == null ? null : FindWithoutAdd(underlyingType); + } + + static readonly BasicList.MatchPredicate + MetaTypeFinder = new BasicList.MatchPredicate(MetaTypeFinderImpl), + BasicTypeFinder = new BasicList.MatchPredicate(BasicTypeFinderImpl); + + static bool MetaTypeFinderImpl(object value, object ctx) + { + return ((MetaType)value).Type == (Type)ctx; + } + + static bool BasicTypeFinderImpl(object value, object ctx) + { + return ((BasicType)value).Type == (Type)ctx; + } + + private void WaitOnLock(MetaType type) + { + int opaqueToken = 0; + try + { + TakeLock(ref opaqueToken); + } + finally + { + ReleaseLock(opaqueToken); + } + } + + BasicList basicTypes = new BasicList(); + + sealed class BasicType + { + private readonly Type type; + public Type Type => type; + private readonly IProtoSerializer serializer; + public IProtoSerializer Serializer => serializer; + + public BasicType(Type type, IProtoSerializer serializer) + { + this.type = type; + this.serializer = serializer; + } + } + internal IProtoSerializer TryGetBasicTypeSerializer(Type type) + { + int idx = basicTypes.IndexOf(BasicTypeFinder, type); + + if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer; + + lock (basicTypes) + { // don't need a full model lock for this + + // double-checked + idx = basicTypes.IndexOf(BasicTypeFinder, type); + if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer; + + MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null); + IProtoSerializer ser = family == MetaType.AttributeFamily.None + ? ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out WireType defaultWireType, false, false, false, false) + : null; + + if (ser != null) basicTypes.Add(new BasicType(type, ser)); + return ser; + } + } + + internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled) + { + int key = types.IndexOf(MetaTypeFinder, type); + MetaType metaType; + + // the fast happy path: meta-types we've already seen + if (key >= 0) + { + metaType = (MetaType)types[key]; + if (metaType.Pending) + { + WaitOnLock(metaType); + } + return key; + } + + // the fast fail path: types that will never have a meta-type + bool shouldAdd = AutoAddMissingTypes || addEvenIfAutoDisabled; + + if (!Helpers.IsEnum(type) && TryGetBasicTypeSerializer(type) != null) + { + if (shouldAdd && !addWithContractOnly) throw MetaType.InbuiltType(type); + return -1; // this will never be a meta-type + } + + // otherwise: we don't yet know + + // check for proxy types + Type underlyingType = ResolveProxies(type); + if (underlyingType != null && underlyingType != type) + { + key = types.IndexOf(MetaTypeFinder, underlyingType); + type = underlyingType; // if new added, make it reflect the underlying type + } + + if (key < 0) + { + int opaqueToken = 0; + Type origType = type; + bool weAdded = false; + try + { + TakeLock(ref opaqueToken); + // try to recognise a few familiar patterns... + if ((metaType = RecogniseCommonTypes(type)) == null) + { // otherwise, check if it is a contract + MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null); + if (family == MetaType.AttributeFamily.AutoTuple) + { + shouldAdd = addEvenIfAutoDisabled = true; // always add basic tuples, such as KeyValuePair + } + + if (!shouldAdd || ( + !Helpers.IsEnum(type) && addWithContractOnly && family == MetaType.AttributeFamily.None) + ) + { + if (demand) ThrowUnexpectedType(type); + return key; + } + metaType = Create(type); + } + + metaType.Pending = true; + + // double-checked + int winner = types.IndexOf(MetaTypeFinder, type); + if (winner < 0) + { + ThrowIfFrozen(); + key = types.Add(metaType); + weAdded = true; + } + else + { + key = winner; + } + if (weAdded) + { + metaType.ApplyDefaultBehaviour(); + metaType.Pending = false; + } + } + finally + { + ReleaseLock(opaqueToken); + if (weAdded) + { + ResetKeyCache(); + } + } + } + return key; + } + + private MetaType RecogniseCommonTypes(Type type) + { + // if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) + // { + // MetaType mt = new MetaType(this, type); + + // Type surrogate = typeof (KeyValuePairSurrogate<,>).MakeGenericType(type.GetGenericArguments()); + + // mt.SetSurrogate(surrogate); + // mt.IncludeSerializerMethod = false; + // mt.Freeze(); + + // MetaType surrogateMeta = (MetaType)types[FindOrAddAuto(surrogate, true, true, true)]; // this forcibly adds it if needed + // if(surrogateMeta.IncludeSerializerMethod) + // { // don't blindly set - it might be frozen + // surrogateMeta.IncludeSerializerMethod = false; + // } + // surrogateMeta.Freeze(); + // return mt; + // } + return null; + } + private MetaType Create(Type type) + { + ThrowIfFrozen(); + return new MetaType(this, type, defaultFactory); + } + + /// + /// Adds support for an additional type in this model, optionally + /// applying inbuilt patterns. If the type is already known to the + /// model, the existing type is returned **without** applying + /// any additional behaviour. + /// + /// Inbuilt patterns include: + /// [ProtoContract]/[ProtoMember(n)] + /// [DataContract]/[DataMember(Order=n)] + /// [XmlType]/[XmlElement(Order=n)] + /// [On{Des|S}erializ{ing|ed}] + /// ShouldSerialize*/*Specified + /// + /// The type to be supported + /// Whether to apply the inbuilt configuration patterns (via attributes etc), or + /// just add the type with no additional configuration (the type must then be manually configured). + /// The MetaType representing this type, allowing + /// further configuration. + public MetaType Add(Type type, bool applyDefaultBehaviour) + { + if (type == null) throw new ArgumentNullException("type"); + MetaType newType = FindWithoutAdd(type); + if (newType != null) return newType; // return existing + int opaqueToken = 0; + +#if COREFX || PROFILE259 + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + if (typeInfo.IsInterface && MetaType.ienumerable.IsAssignableFrom(typeInfo) +#else + if (type.IsInterface && MapType(MetaType.ienumerable).IsAssignableFrom(type) +#endif + && GetListItemType(this, type) == null) + { + throw new ArgumentException("IEnumerable[] data cannot be used as a meta-type unless an Add method can be resolved"); + } + try + { + newType = RecogniseCommonTypes(type); + if (newType != null) + { + if (!applyDefaultBehaviour) + { + throw new ArgumentException( + "Default behaviour must be observed for certain types with special handling; " + type.FullName, + "applyDefaultBehaviour"); + } + // we should assume that type is fully configured, though; no need to re-run: + applyDefaultBehaviour = false; + } + if (newType == null) newType = Create(type); + newType.Pending = true; + TakeLock(ref opaqueToken); + // double checked + if (FindWithoutAdd(type) != null) throw new ArgumentException("Duplicate type", "type"); + ThrowIfFrozen(); + types.Add(newType); + if (applyDefaultBehaviour) { newType.ApplyDefaultBehaviour(); } + newType.Pending = false; + } + finally + { + ReleaseLock(opaqueToken); + ResetKeyCache(); + } + + return newType; + } + +#if FEAT_COMPILER + /// + /// Should serializers be compiled on demand? It may be useful + /// to disable this for debugging purposes. + /// + public bool AutoCompile + { + get { return GetOption(OPTIONS_AutoCompile); } + set { SetOption(OPTIONS_AutoCompile, value); } + } +#endif + /// + /// Should support for unexpected types be added automatically? + /// If false, an exception is thrown when unexpected types + /// are encountered. + /// + public bool AutoAddMissingTypes + { + get { return GetOption(OPTIONS_AutoAddMissingTypes); } + set + { + if (!value && GetOption(OPTIONS_IsDefaultModel)) + { + throw new InvalidOperationException("The default model must allow missing types"); + } + ThrowIfFrozen(); + SetOption(OPTIONS_AutoAddMissingTypes, value); + } + } + /// + /// Verifies that the model is still open to changes; if not, an exception is thrown + /// + private void ThrowIfFrozen() + { + if (GetOption(OPTIONS_Frozen)) throw new InvalidOperationException("The model cannot be changed once frozen"); + } + + /// + /// Prevents further changes to this model + /// + public void Freeze() + { + if (GetOption(OPTIONS_IsDefaultModel)) throw new InvalidOperationException("The default model cannot be frozen"); + SetOption(OPTIONS_Frozen, true); + } + + private readonly BasicList types = new BasicList(); + + /// + /// Provides the key that represents a given type in the current model. + /// + protected override int GetKeyImpl(Type type) + { + return GetKey(type, false, true); + } + + internal int GetKey(Type type, bool demand, bool getBaseKey) + { + Helpers.DebugAssert(type != null); + try + { + int typeIndex = FindOrAddAuto(type, demand, true, false); + if (typeIndex >= 0) + { + MetaType mt = (MetaType)types[typeIndex]; + if (getBaseKey) + { + mt = MetaType.GetRootType(mt); + typeIndex = FindOrAddAuto(mt.Type, true, true, false); + } + } + return typeIndex; + } + catch (NotSupportedException) + { + throw; // re-surface "as-is" + } + catch (Exception ex) + { + if (ex.Message.IndexOf(type.FullName) >= 0) throw; // already enough info + throw new ProtoException(ex.Message + " (" + type.FullName + ")", ex); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + protected internal override void Serialize(int key, object value, ProtoWriter dest) + { + //Helpers.DebugWriteLine("Serialize", value); + ((MetaType)types[key]).Serializer.Write(value, dest); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + protected internal override object Deserialize(int key, object value, ProtoReader source) + { + //Helpers.DebugWriteLine("Deserialize", value); + IProtoSerializer ser = ((MetaType)types[key]).Serializer; + if (value == null && Helpers.IsValueType(ser.ExpectedType)) + { + if (ser.RequiresOldValue) value = Activator.CreateInstance(ser.ExpectedType); + return ser.Read(value, source); + } + else + { + return ser.Read(value, source); + } + } + +#if FEAT_COMPILER + // this is used by some unit-tests; do not remove + internal Compiler.ProtoSerializer GetSerializer(IProtoSerializer serializer, bool compiled) + { + if (serializer == null) throw new ArgumentNullException("serializer"); +#if FEAT_COMPILER + if (compiled) return Compiler.CompilerContext.BuildSerializer(serializer, this); +#endif + return new Compiler.ProtoSerializer(serializer.Write); + } + + /// + /// Compiles the serializers individually; this is *not* a full + /// standalone compile, but can significantly boost performance + /// while allowing additional types to be added. + /// + /// An in-place compile can access non-public types / members + public void CompileInPlace() + { + foreach (MetaType type in types) + { + type.CompileInPlace(); + } + } + +#endif + //internal override IProtoSerializer GetTypeSerializer(Type type) + //{ // this list is thread-safe for reading + // .Serializer; + //} + //internal override IProtoSerializer GetTypeSerializer(int key) + //{ // this list is thread-safe for reading + // MetaType type = (MetaType)types.TryGet(key); + // if (type != null) return type.Serializer; + // throw new KeyNotFoundException(); + + //} + +#if FEAT_COMPILER + private void BuildAllSerializers() + { + // note that types.Count may increase during this operation, as some serializers + // bring other types into play + for (int i = 0; i < types.Count; i++) + { + // the primary purpose of this is to force the creation of the Serializer + MetaType mt = (MetaType)types[i]; + if (mt.Serializer == null) + throw new InvalidOperationException("No serializer available for " + mt.Type.Name); + } + } + + internal sealed class SerializerPair : IComparable + { + int IComparable.CompareTo(object obj) + { + if (obj == null) throw new ArgumentException("obj"); + SerializerPair other = (SerializerPair)obj; + + // we want to bunch all the items with the same base-type together, but we need the items with a + // different base **first**. + if (this.BaseKey == this.MetaKey) + { + if (other.BaseKey == other.MetaKey) + { // neither is a subclass + return this.MetaKey.CompareTo(other.MetaKey); + } + else + { // "other" (only) is involved in inheritance; "other" should be first + return 1; + } + } + else + { + if (other.BaseKey == other.MetaKey) + { // "this" (only) is involved in inheritance; "this" should be first + return -1; + } + else + { // both are involved in inheritance + int result = this.BaseKey.CompareTo(other.BaseKey); + if (result == 0) result = this.MetaKey.CompareTo(other.MetaKey); + return result; + } + } + } + public readonly int MetaKey, BaseKey; + public readonly MetaType Type; + public readonly MethodBuilder Serialize, Deserialize; + public readonly ILGenerator SerializeBody, DeserializeBody; + public SerializerPair(int metaKey, int baseKey, MetaType type, MethodBuilder serialize, MethodBuilder deserialize, + ILGenerator serializeBody, ILGenerator deserializeBody) + { + this.MetaKey = metaKey; + this.BaseKey = baseKey; + this.Serialize = serialize; + this.Deserialize = deserialize; + this.SerializeBody = serializeBody; + this.DeserializeBody = deserializeBody; + this.Type = type; + } + } + + /// + /// Fully compiles the current model into a static-compiled model instance + /// + /// A full compilation is restricted to accessing public types / members + /// An instance of the newly created compiled type-model + public TypeModel Compile() + { + CompilerOptions options = new CompilerOptions(); + return Compile(options); + } + + static ILGenerator Override(TypeBuilder type, string name) + { + MethodInfo baseMethod = type.BaseType.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance); + + ParameterInfo[] parameters = baseMethod.GetParameters(); + Type[] paramTypes = new Type[parameters.Length]; + for (int i = 0; i < paramTypes.Length; i++) + { + paramTypes[i] = parameters[i].ParameterType; + } + MethodBuilder newMethod = type.DefineMethod(baseMethod.Name, + (baseMethod.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Final, baseMethod.CallingConvention, baseMethod.ReturnType, paramTypes); + ILGenerator il = newMethod.GetILGenerator(); + type.DefineMethodOverride(newMethod, baseMethod); + return il; + } + + /// + /// Represents configuration options for compiling a model to + /// a standalone assembly. + /// + public sealed class CompilerOptions + { + /// + /// Import framework options from an existing type + /// + public void SetFrameworkOptions(MetaType from) + { + if (from == null) throw new ArgumentNullException("from"); + AttributeMap[] attribs = AttributeMap.Create(from.Model, Helpers.GetAssembly(from.Type)); + foreach (AttributeMap attrib in attribs) + { + if (attrib.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute") + { + object tmp; + if (attrib.TryGet("FrameworkName", out tmp)) TargetFrameworkName = (string)tmp; + if (attrib.TryGet("FrameworkDisplayName", out tmp)) TargetFrameworkDisplayName = (string)tmp; + break; + } + } + } + + private string targetFrameworkName, targetFrameworkDisplayName, typeName, outputPath, imageRuntimeVersion; + private int metaDataVersion; + /// + /// The TargetFrameworkAttribute FrameworkName value to burn into the generated assembly + /// + public string TargetFrameworkName { get { return targetFrameworkName; } set { targetFrameworkName = value; } } + + /// + /// The TargetFrameworkAttribute FrameworkDisplayName value to burn into the generated assembly + /// + public string TargetFrameworkDisplayName { get { return targetFrameworkDisplayName; } set { targetFrameworkDisplayName = value; } } + /// + /// The name of the TypeModel class to create + /// + public string TypeName { get { return typeName; } set { typeName = value; } } + +#if COREFX + internal const string NoPersistence = "Assembly persistence not supported on this runtime"; +#endif + /// + /// The path for the new dll + /// +#if COREFX + [Obsolete(NoPersistence)] +#endif + public string OutputPath { get { return outputPath; } set { outputPath = value; } } + /// + /// The runtime version for the generated assembly + /// + public string ImageRuntimeVersion { get { return imageRuntimeVersion; } set { imageRuntimeVersion = value; } } + /// + /// The runtime version for the generated assembly + /// + public int MetaDataVersion { get { return metaDataVersion; } set { metaDataVersion = value; } } + + + private Accessibility accessibility = Accessibility.Public; + /// + /// The acecssibility of the generated serializer + /// + public Accessibility Accessibility { get { return accessibility; } set { accessibility = value; } } + } + + /// + /// Type accessibility + /// + public enum Accessibility + { + /// + /// Available to all callers + /// + Public, + /// + /// Available to all callers in the same assembly, or assemblies specified via [InternalsVisibleTo(...)] + /// + Internal + } + +#if !COREFX + /// + /// Fully compiles the current model into a static-compiled serialization dll + /// (the serialization dll still requires protobuf-net for support services). + /// + /// A full compilation is restricted to accessing public types / members + /// The name of the TypeModel class to create + /// The path for the new dll + /// An instance of the newly created compiled type-model + public TypeModel Compile(string name, string path) + { + CompilerOptions options = new CompilerOptions(); + options.TypeName = name; + options.OutputPath = path; + return Compile(options); + } +#endif + /// + /// Fully compiles the current model into a static-compiled serialization dll + /// (the serialization dll still requires protobuf-net for support services). + /// + /// A full compilation is restricted to accessing public types / members + /// An instance of the newly created compiled type-model + public TypeModel Compile(CompilerOptions options) + { + if (options == null) throw new ArgumentNullException("options"); + string typeName = options.TypeName; +#pragma warning disable 0618 + string path = options.OutputPath; +#pragma warning restore 0618 + BuildAllSerializers(); + Freeze(); + bool save = !string.IsNullOrEmpty(path); + if (string.IsNullOrEmpty(typeName)) + { + if (save) throw new ArgumentNullException("typeName"); + typeName = Guid.NewGuid().ToString(); + } + + + string assemblyName, moduleName; + if (path == null) + { + assemblyName = typeName; + moduleName = assemblyName + ".dll"; + } + else + { + assemblyName = new System.IO.FileInfo(System.IO.Path.GetFileNameWithoutExtension(path)).Name; + moduleName = assemblyName + System.IO.Path.GetExtension(path); + } + +#if COREFX + AssemblyName an = new AssemblyName(); + an.Name = assemblyName; + AssemblyBuilder asm = AssemblyBuilder.DefineDynamicAssembly(an, + AssemblyBuilderAccess.Run); + ModuleBuilder module = asm.DefineDynamicModule(moduleName); +#else + AssemblyName an = new AssemblyName(); + an.Name = assemblyName; + AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(an, + (save ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run) + ); + ModuleBuilder module = save ? asm.DefineDynamicModule(moduleName, path) + : asm.DefineDynamicModule(moduleName); +#endif + + WriteAssemblyAttributes(options, assemblyName, asm); + + TypeBuilder type = WriteBasicTypeModel(options, typeName, module); + + int index; + bool hasInheritance; + SerializerPair[] methodPairs; + Compiler.CompilerContext.ILVersion ilVersion; + WriteSerializers(options, assemblyName, type, out index, out hasInheritance, out methodPairs, out ilVersion); + + ILGenerator il; + int knownTypesCategory; + FieldBuilder knownTypes; + Type knownTypesLookupType; + WriteGetKeyImpl(type, hasInheritance, methodPairs, ilVersion, assemblyName, out il, out knownTypesCategory, out knownTypes, out knownTypesLookupType); + + // trivial flags + il = Override(type, "SerializeDateTimeKind"); + il.Emit(IncludeDateTimeKind ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Ret); + // end: trivial flags + + Compiler.CompilerContext ctx = WriteSerializeDeserialize(assemblyName, type, methodPairs, ilVersion, ref il); + + WriteConstructors(type, ref index, methodPairs, ref il, knownTypesCategory, knownTypes, knownTypesLookupType, ctx); + + +#if COREFX + Type finalType = type.CreateTypeInfo().AsType(); +#else + Type finalType = type.CreateType(); +#endif + if (!string.IsNullOrEmpty(path)) + { +#if COREFX + throw new NotSupportedException(CompilerOptions.NoPersistence); +#else + try + { + asm.Save(path); + } + catch (IOException ex) + { + // advertise the file info + throw new IOException(path + ", " + ex.Message, ex); + } + Helpers.DebugWriteLine("Wrote dll:" + path); +#endif + } + return (TypeModel)Activator.CreateInstance(finalType); + } + + private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, Compiler.CompilerContext ctx) + { + type.DefineDefaultConstructor(MethodAttributes.Public); + il = type.DefineTypeInitializer().GetILGenerator(); + switch (knownTypesCategory) + { + case KnownTypes_Array: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newarr, ctx.MapType(typeof(System.Type))); + index = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Dup); + Compiler.CompilerContext.LoadValue(il, index); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + il.Emit(OpCodes.Stelem_Ref); + index++; + } + il.Emit(OpCodes.Stsfld, knownTypes); + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Dictionary: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + //LocalBuilder loc = il.DeclareLocal(knownTypesLookupType); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int typeIndex = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + int keyIndex = typeIndex++, lastKey = pair.BaseKey; + if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type + { + keyIndex = -1; // assume epic fail + for (int j = 0; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + } + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(System.Type)), MapType(typeof(int)) }), null); + } + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Hashtable: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int typeIndex = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + int keyIndex = typeIndex++, lastKey = pair.BaseKey; + if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type + { + keyIndex = -1; // assume epic fail + for (int j = 0; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + } + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.Emit(OpCodes.Box, MapType(typeof(int))); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(object)), MapType(typeof(object)) }), null); + } + il.Emit(OpCodes.Ret); + } + break; + default: + throw new InvalidOperationException(); + } + } + + private Compiler.CompilerContext WriteSerializeDeserialize(string assemblyName, TypeBuilder type, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, ref ILGenerator il) + { + il = Override(type, "Serialize"); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, true, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Serialize " + type.Name); + // arg0 = this, arg1 = key, arg2=obj, arg3=dest + Compiler.CodeLabel[] jumpTable = new Compiler.CodeLabel[types.Count]; + for (int i = 0; i < jumpTable.Length; i++) + { + jumpTable[i] = ctx.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + ctx.Switch(jumpTable); + ctx.Return(); + for (int i = 0; i < jumpTable.Length; i++) + { + SerializerPair pair = methodPairs[i]; + ctx.MarkLabel(jumpTable[i]); + il.Emit(OpCodes.Ldarg_2); + ctx.CastFromObject(pair.Type.Type); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, pair.Serialize, null); + ctx.Return(); + } + + il = Override(type, "Deserialize"); + ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Deserialize " + type.Name); + // arg0 = this, arg1 = key, arg2=obj, arg3=source + for (int i = 0; i < jumpTable.Length; i++) + { + jumpTable[i] = ctx.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + ctx.Switch(jumpTable); + ctx.LoadNullRef(); + ctx.Return(); + for (int i = 0; i < jumpTable.Length; i++) + { + SerializerPair pair = methodPairs[i]; + ctx.MarkLabel(jumpTable[i]); + Type keyType = pair.Type.Type; + if (Helpers.IsValueType(keyType)) + { + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, EmitBoxedSerializer(type, i, keyType, methodPairs, this, ilVersion, assemblyName), null); + ctx.Return(); + } + else + { + il.Emit(OpCodes.Ldarg_2); + ctx.CastFromObject(keyType); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, pair.Deserialize, null); + ctx.Return(); + } + } + return ctx; + } + + private const int KnownTypes_Array = 1, KnownTypes_Dictionary = 2, KnownTypes_Hashtable = 3, KnownTypes_ArrayCutoff = 20; + private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType) + { + + il = Override(type, "GetKeyImpl"); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(System.Type), true), "GetKeyImpl"); + + + if (types.Count <= KnownTypes_ArrayCutoff) + { + knownTypesCategory = KnownTypes_Array; + knownTypesLookupType = MapType(typeof(System.Type[]), true); + } + else + { + knownTypesLookupType = MapType(typeof(System.Collections.Generic.Dictionary), false); + +#if !COREFX + if (knownTypesLookupType == null) + { + knownTypesLookupType = MapType(typeof(Hashtable), true); + knownTypesCategory = KnownTypes_Hashtable; + } + else +#endif + { + knownTypesCategory = KnownTypes_Dictionary; + } + } + knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static); + + switch (knownTypesCategory) + { + case KnownTypes_Array: + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + // note that Array.IndexOf is not supported under CF + il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod( + "IndexOf", new Type[] { MapType(typeof(object)) }), null); + if (hasInheritance) + { + il.DeclareLocal(MapType(typeof(int))); // loc-0 + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Stloc_0); + + BasicList getKeyLabels = new BasicList(); + int lastKey = -1; + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == methodPairs[i].BaseKey) break; + if (lastKey == methodPairs[i].BaseKey) + { // add the last label again + getKeyLabels.Add(getKeyLabels[getKeyLabels.Count - 1]); + } + else + { // add a new unique label + getKeyLabels.Add(ctx.DefineLabel()); + lastKey = methodPairs[i].BaseKey; + } + } + Compiler.CodeLabel[] subtypeLabels = new Compiler.CodeLabel[getKeyLabels.Count]; + getKeyLabels.CopyTo(subtypeLabels, 0); + + ctx.Switch(subtypeLabels); + il.Emit(OpCodes.Ldloc_0); // not a sub-type; use the original value + il.Emit(OpCodes.Ret); + + lastKey = -1; + // now output the different branches per sub-type (not derived type) + for (int i = subtypeLabels.Length - 1; i >= 0; i--) + { + if (lastKey != methodPairs[i].BaseKey) + { + lastKey = methodPairs[i].BaseKey; + // find the actual base-index for this base-key (i.e. the index of + // the base-type) + int keyIndex = -1; + for (int j = subtypeLabels.Length; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + ctx.MarkLabel(subtypeLabels[i]); + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.Emit(OpCodes.Ret); + } + } + } + else + { + il.Emit(OpCodes.Ret); + } + } + break; + case KnownTypes_Dictionary: + { + LocalBuilder result = il.DeclareLocal(MapType(typeof(int))); + Label otherwise = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldloca_S, result); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public), null); + il.Emit(OpCodes.Brfalse_S, otherwise); + il.Emit(OpCodes.Ldloc_S, result); + il.Emit(OpCodes.Ret); + il.MarkLabel(otherwise); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Hashtable: + { + Label otherwise = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetProperty("Item").GetGetMethod(), null); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Brfalse_S, otherwise); + if (ilVersion == Compiler.CompilerContext.ILVersion.Net1) + { + il.Emit(OpCodes.Unbox, MapType(typeof(int))); + il.Emit(OpCodes.Ldobj, MapType(typeof(int))); + } + else + { + il.Emit(OpCodes.Unbox_Any, MapType(typeof(int))); + } + il.Emit(OpCodes.Ret); + il.MarkLabel(otherwise); + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + } + break; + default: + throw new InvalidOperationException(); + } + } + + private void WriteSerializers(CompilerOptions options, string assemblyName, TypeBuilder type, out int index, out bool hasInheritance, out SerializerPair[] methodPairs, out Compiler.CompilerContext.ILVersion ilVersion) + { + Compiler.CompilerContext ctx; + + index = 0; + hasInheritance = false; + methodPairs = new SerializerPair[types.Count]; + foreach (MetaType metaType in types) + { + MethodBuilder writeMethod = type.DefineMethod("Write" +#if DEBUG + + metaType.Type.Name +#endif +, + MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, + MapType(typeof(void)), new Type[] { metaType.Type, MapType(typeof(ProtoWriter)) }); + + MethodBuilder readMethod = type.DefineMethod("Read" +#if DEBUG + + metaType.Type.Name +#endif +, + MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, + metaType.Type, new Type[] { metaType.Type, MapType(typeof(ProtoReader)) }); + + SerializerPair pair = new SerializerPair( + GetKey(metaType.Type, true, false), GetKey(metaType.Type, true, true), metaType, + writeMethod, readMethod, writeMethod.GetILGenerator(), readMethod.GetILGenerator()); + methodPairs[index++] = pair; + if (pair.MetaKey != pair.BaseKey) hasInheritance = true; + } + + if (hasInheritance) + { + Array.Sort(methodPairs); + } + + ilVersion = Compiler.CompilerContext.ILVersion.Net2; + if (options.MetaDataVersion == 0x10000) + { + ilVersion = Compiler.CompilerContext.ILVersion.Net1; // old-school! + } + for (index = 0; index < methodPairs.Length; index++) + { + SerializerPair pair = methodPairs[index]; + ctx = new Compiler.CompilerContext(pair.SerializeBody, true, true, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "SerializeImpl " + pair.Type.Type.Name); + MemberInfo returnType = pair.Deserialize.ReturnType +#if COREFX + .GetTypeInfo() +#endif + ; + ctx.CheckAccessibility(ref returnType); + pair.Type.Serializer.EmitWrite(ctx, ctx.InputValue); + ctx.Return(); + + ctx = new Compiler.CompilerContext(pair.DeserializeBody, true, false, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "DeserializeImpl " + pair.Type.Type.Name); + pair.Type.Serializer.EmitRead(ctx, ctx.InputValue); + if (!pair.Type.Serializer.ReturnsValue) + { + ctx.LoadValue(ctx.InputValue); + } + ctx.Return(); + } + } + + private TypeBuilder WriteBasicTypeModel(CompilerOptions options, string typeName, ModuleBuilder module) + { + Type baseType = MapType(typeof(TypeModel)); +#if COREFX + TypeAttributes typeAttributes = (baseType.GetTypeInfo().Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed; +#else + TypeAttributes typeAttributes = (baseType.Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed; +#endif + if (options.Accessibility == Accessibility.Internal) + { + typeAttributes &= ~TypeAttributes.Public; + } + + TypeBuilder type = module.DefineType(typeName, typeAttributes, baseType); + return type; + } + + private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm) + { + if (!string.IsNullOrEmpty(options.TargetFrameworkName)) + { + // get [TargetFramework] from mscorlib/equivalent and burn into the new assembly + Type versionAttribType = null; + try + { // this is best-endeavours only + versionAttribType = GetType("System.Runtime.Versioning.TargetFrameworkAttribute", Helpers.GetAssembly(MapType(typeof(string)))); + } + catch { /* don't stress */ } + if (versionAttribType != null) + { + PropertyInfo[] props; + object[] propValues; + if (string.IsNullOrEmpty(options.TargetFrameworkDisplayName)) + { + props = new PropertyInfo[0]; + propValues = new object[0]; + } + else + { + props = new PropertyInfo[1] { versionAttribType.GetProperty("FrameworkDisplayName") }; + propValues = new object[1] { options.TargetFrameworkDisplayName }; + } + CustomAttributeBuilder builder = new CustomAttributeBuilder( + versionAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }), + new object[] { options.TargetFrameworkName }, + props, + propValues); + asm.SetCustomAttribute(builder); + } + } + + // copy assembly:InternalsVisibleTo + Type internalsVisibleToAttribType = null; + + try + { + internalsVisibleToAttribType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute)); + } + catch { /* best endeavors only */ } + + if (internalsVisibleToAttribType != null) + { + BasicList internalAssemblies = new BasicList(), consideredAssemblies = new BasicList(); + foreach (MetaType metaType in types) + { + Assembly assembly = Helpers.GetAssembly(metaType.Type); + if (consideredAssemblies.IndexOfReference(assembly) >= 0) continue; + consideredAssemblies.Add(assembly); + + AttributeMap[] assemblyAttribsMap = AttributeMap.Create(this, assembly); + for (int i = 0; i < assemblyAttribsMap.Length; i++) + { + + if (assemblyAttribsMap[i].AttributeType != internalsVisibleToAttribType) continue; + + object privelegedAssemblyObj; + assemblyAttribsMap[i].TryGet("AssemblyName", out privelegedAssemblyObj); + string privelegedAssemblyName = privelegedAssemblyObj as string; + if (privelegedAssemblyName == assemblyName || string.IsNullOrEmpty(privelegedAssemblyName)) continue; // ignore + + if (internalAssemblies.IndexOfString(privelegedAssemblyName) >= 0) continue; // seen it before + internalAssemblies.Add(privelegedAssemblyName); + + CustomAttributeBuilder builder = new CustomAttributeBuilder( + internalsVisibleToAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }), + new object[] { privelegedAssemblyName }); + asm.SetCustomAttribute(builder); + } + } + } + } + + private static MethodBuilder EmitBoxedSerializer(TypeBuilder type, int i, Type valueType, SerializerPair[] methodPairs, TypeModel model, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName) + { + MethodInfo dedicated = methodPairs[i].Deserialize; + MethodBuilder boxedSerializer = type.DefineMethod("_" + i.ToString(), MethodAttributes.Static, CallingConventions.Standard, + model.MapType(typeof(object)), new Type[] { model.MapType(typeof(object)), model.MapType(typeof(ProtoReader)) }); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(boxedSerializer.GetILGenerator(), true, false, methodPairs, model, ilVersion, assemblyName, model.MapType(typeof(object)), "BoxedSerializer " + valueType.Name); + ctx.LoadValue(ctx.InputValue); + Compiler.CodeLabel @null = ctx.DefineLabel(); + ctx.BranchIfFalse(@null, true); + + Type mappedValueType = valueType; + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(mappedValueType); + ctx.LoadReaderWriter(); + ctx.EmitCall(dedicated); + ctx.CastToObject(mappedValueType); + ctx.Return(); + + ctx.MarkLabel(@null); + using (Compiler.Local typedVal = new Compiler.Local(ctx, mappedValueType)) + { + // create a new valueType + ctx.LoadAddress(typedVal, mappedValueType); + ctx.EmitCtor(mappedValueType); + ctx.LoadValue(typedVal); + ctx.LoadReaderWriter(); + ctx.EmitCall(dedicated); + ctx.CastToObject(mappedValueType); + ctx.Return(); + } + return boxedSerializer; + } + +#endif + //internal bool IsDefined(Type type, int fieldNumber) + //{ + // return FindWithoutAdd(type).IsDefined(fieldNumber); + //} + + // note that this is used by some of the unit tests + internal bool IsPrepared(Type type) + { + MetaType meta = FindWithoutAdd(type); + return meta != null && meta.IsPrepared(); + } + + internal EnumSerializer.EnumPair[] GetEnumMap(Type type) + { + int index = FindOrAddAuto(type, false, false, false); + return index < 0 ? null : ((MetaType)types[index]).GetEnumMap(); + } + + private int metadataTimeoutMilliseconds = 5000; + /// + /// The amount of time to wait if there are concurrent metadata access operations + /// + public int MetadataTimeoutMilliseconds + { + get { return metadataTimeoutMilliseconds; } + set + { + if (value <= 0) throw new ArgumentOutOfRangeException("MetadataTimeoutMilliseconds"); + metadataTimeoutMilliseconds = value; + } + } + +#if DEBUG + int lockCount; + /// + /// Gets how many times a model lock was taken + /// + public int LockCount { get { return lockCount; } } +#endif + internal void TakeLock(ref int opaqueToken) + { + const string message = "Timeout while inspecting metadata; this may indicate a deadlock. This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection; please also see the LockContended event"; + opaqueToken = 0; +#if PORTABLE + if(!Monitor.TryEnter(types, metadataTimeoutMilliseconds)) throw new TimeoutException(message); + opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1) +#elif CF2 || CF35 + int remaining = metadataTimeoutMilliseconds; + bool lockTaken; + do { + lockTaken = Monitor.TryEnter(types); + if(!lockTaken) + { + if(remaining <= 0) throw new TimeoutException(message); + remaining -= 50; + Thread.Sleep(50); + } + } while(!lockTaken); + opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1) +#else + if (Monitor.TryEnter(types, metadataTimeoutMilliseconds)) + { + opaqueToken = GetContention(); // just fetch current value (starts at 1) + } + else + { + AddContention(); + + throw new TimeoutException(message); + } +#endif + +#if DEBUG // note that here, through all code-paths: we have the lock + lockCount++; +#endif + } + + private int contentionCounter = 1; +#if PLAT_NO_INTERLOCKED + private readonly object contentionLock = new object(); +#endif + private int GetContention() + { +#if PLAT_NO_INTERLOCKED + lock(contentionLock) + { + return contentionCounter; + } +#else + return Interlocked.CompareExchange(ref contentionCounter, 0, 0); +#endif + } + private void AddContention() + { +#if PLAT_NO_INTERLOCKED + lock(contentionLock) + { + contentionCounter++; + } +#else + Interlocked.Increment(ref contentionCounter); +#endif + } + + internal void ReleaseLock(int opaqueToken) + { + if (opaqueToken != 0) + { + Monitor.Exit(types); + if (opaqueToken != GetContention()) // contention-count changes since we looked! + { + LockContentedEventHandler handler = LockContended; + if (handler != null) + { + // not hugely elegant, but this is such a far-corner-case that it doesn't need to be slick - I'll settle for cross-platform + string stackTrace; + try + { + throw new ProtoException(); + } + catch (Exception ex) + { + stackTrace = ex.StackTrace; + } + + handler(this, new LockContentedEventArgs(stackTrace)); + } + } + } + } + /// + /// If a lock-contention is detected, this event signals the *owner* of the lock responsible for the blockage, indicating + /// what caused the problem; this is only raised if the lock-owning code successfully completes. + /// + public event LockContentedEventHandler LockContended; + + internal void ResolveListTypes(Type type, ref Type itemType, ref Type defaultType) + { + if (type == null) return; + if (Helpers.GetTypeCode(type) != ProtoTypeCode.Unknown) return; // don't try this[type] for inbuilts + + // handle arrays + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimension arrays are supported"); + } + itemType = type.GetElementType(); + if (itemType == MapType(typeof(byte))) + { + defaultType = itemType = null; + } + else + { + defaultType = type; + } + } + else + { + // if not an array, first check it isn't explicitly opted out + if (this[type].IgnoreListHandling) return; + } + + // handle lists + if (itemType == null) { itemType = TypeModel.GetListItemType(this, type); } + + // check for nested data (not allowed) + if (itemType != null) + { + Type nestedItemType = null, nestedDefaultType = null; + ResolveListTypes(itemType, ref nestedItemType, ref nestedDefaultType); + if (nestedItemType != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + + if (itemType != null && defaultType == null) + { +#if COREFX || PROFILE259 + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null) +#else + if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null) +#endif + { + defaultType = type; + } + if (defaultType == null) + { +#if COREFX || PROFILE259 + if (typeInfo.IsInterface) +#else + if (type.IsInterface) +#endif + { + + Type[] genArgs; +#if COREFX || PROFILE259 + if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) + && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments)) +#else + if (type.IsGenericType && type.GetGenericTypeDefinition() == MapType(typeof(System.Collections.Generic.IDictionary<,>)) + && itemType == MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments())) +#endif + { + defaultType = MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs); + } + else + { + defaultType = MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + } + } + } + // verify that the default type is appropriate + if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; } + } + } + + internal string GetSchemaTypeName(Type effectiveType, DataFormat dataFormat, bool asReference, bool dynamicType, ref CommonImports imports) + { + Type tmp = Helpers.GetUnderlyingType(effectiveType); + if (tmp != null) effectiveType = tmp; + + if (effectiveType == this.MapType(typeof(byte[]))) return "bytes"; + + WireType wireType; + IProtoSerializer ser = ValueMember.TryGetCoreSerializer(this, dataFormat, effectiveType, out wireType, false, false, false, false); + if (ser == null) + { // model type + if (asReference || dynamicType) + { + imports |= CommonImports.Bcl; + return ".bcl.NetObjectProxy"; + } + return this[effectiveType].GetSurrogateOrBaseOrSelf(true).GetSchemaTypeName(); + } + else + { + if (ser is ParseableSerializer) + { + if (asReference) imports |= CommonImports.Bcl; + return asReference ? ".bcl.NetObjectProxy" : "string"; + } + + switch (Helpers.GetTypeCode(effectiveType)) + { + case ProtoTypeCode.Boolean: return "bool"; + case ProtoTypeCode.Single: return "float"; + case ProtoTypeCode.Double: return "double"; + case ProtoTypeCode.String: + if (asReference) imports |= CommonImports.Bcl; + return asReference ? ".bcl.NetObjectProxy" : "string"; + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + switch (dataFormat) + { + case DataFormat.FixedSize: return "fixed32"; + default: return "uint32"; + } + case ProtoTypeCode.SByte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + switch (dataFormat) + { + case DataFormat.ZigZag: return "sint32"; + case DataFormat.FixedSize: return "sfixed32"; + default: return "int32"; + } + case ProtoTypeCode.UInt64: + switch (dataFormat) + { + case DataFormat.FixedSize: return "fixed64"; + default: return "uint64"; + } + case ProtoTypeCode.Int64: + switch (dataFormat) + { + case DataFormat.ZigZag: return "sint64"; + case DataFormat.FixedSize: return "sfixed64"; + default: return "int64"; + } + case ProtoTypeCode.DateTime: + switch (dataFormat) + { + case DataFormat.FixedSize: return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Timestamp; + return ".google.protobuf.Timestamp"; + default: + imports |= CommonImports.Bcl; + return ".bcl.DateTime"; + } + case ProtoTypeCode.TimeSpan: + switch (dataFormat) + { + case DataFormat.FixedSize: return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Duration; + return ".google.protobuf.Duration"; + default: + imports |= CommonImports.Bcl; + return ".bcl.TimeSpan"; + } + case ProtoTypeCode.Decimal: imports |= CommonImports.Bcl; return ".bcl.Decimal"; + case ProtoTypeCode.Guid: imports |= CommonImports.Bcl; return ".bcl.Guid"; + case ProtoTypeCode.Type: return "string"; + default: throw new NotSupportedException("No .proto map found for: " + effectiveType.FullName); + } + } + + } + + /// + /// Designate a factory-method to use to create instances of any type; note that this only affect types seen by the serializer *after* setting the factory. + /// + public void SetDefaultFactory(MethodInfo methodInfo) + { + VerifyFactory(methodInfo, null); + defaultFactory = methodInfo; + } + private MethodInfo defaultFactory; + + internal void VerifyFactory(MethodInfo factory, Type type) + { + if (factory != null) + { + if (type != null && Helpers.IsValueType(type)) throw new InvalidOperationException(); + if (!factory.IsStatic) throw new ArgumentException("A factory-method must be static", "factory"); + if ((type != null && factory.ReturnType != type) && factory.ReturnType != MapType(typeof(object))) throw new ArgumentException("The factory-method must return object" + (type == null ? "" : (" or " + type.FullName)), "factory"); + + if (!CallbackSet.CheckCallbackParameters(this, factory)) throw new ArgumentException("Invalid factory signature in " + factory.DeclaringType.FullName + "." + factory.Name, "factory"); + } + } + + /// + /// Raised before a type is auto-configured; this allows the auto-configuration to be electively suppressed + /// + /// This callback should be fast and not involve complex external calls, as it may block the model + public event EventHandler BeforeApplyDefaultBehaviour; + + /// + /// Raised after a type is auto-configured; this allows additional external customizations + /// + /// This callback should be fast and not involve complex external calls, as it may block the model + public event EventHandler AfterApplyDefaultBehaviour; + + internal static void OnBeforeApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + => OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.BeforeApplyDefaultBehaviour, metaType, ref args); + + internal static void OnAfterApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + => OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.AfterApplyDefaultBehaviour, metaType, ref args); + + private static void OnApplyDefaultBehaviour( + EventHandler handler, MetaType metaType, ref TypeAddedEventArgs args) + { + if (handler != null) + { + if (args == null) args = new TypeAddedEventArgs(metaType); + handler(metaType.Model, args); + } + } + } + + /// + /// Contains the stack-trace of the owning code when a lock-contention scenario is detected + /// + public sealed class LockContentedEventArgs : EventArgs + { + private readonly string ownerStackTrace; + internal LockContentedEventArgs(string ownerStackTrace) + { + this.ownerStackTrace = ownerStackTrace; + } + + /// + /// The stack-trace of the code that owned the lock when a lock-contention scenario occurred + /// + public string OwnerStackTrace => ownerStackTrace; + } + /// + /// Event-type that is raised when a lock-contention scenario is detected + /// + public delegate void LockContentedEventHandler(object sender, LockContentedEventArgs args); +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta new file mode 100644 index 0000000..57c38a0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22f35ae6eb80e954d89b5223187abac8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs new file mode 100644 index 0000000..72c8126 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs @@ -0,0 +1,97 @@ +#if !NO_RUNTIME +using System; +using System.Collections.Generic; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta +{ + /// + /// Represents an inherited type in a type hierarchy. + /// + public sealed class SubType + { + internal sealed class Comparer : System.Collections.IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as SubType, y as SubType); + } + + public int Compare(SubType x, SubType y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + + private int _fieldNumber; + + /// + /// The field-number that is used to encapsulate the data (as a nested + /// message) for the derived dype. + /// + public int FieldNumber + { + get => _fieldNumber; + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + private void ThrowIfFrozen() + { + if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + + + /// + /// The sub-type to be considered. + /// + public MetaType DerivedType => derivedType; + private readonly MetaType derivedType; + + /// + /// Creates a new SubType instance. + /// + /// The field-number that is used to encapsulate the data (as a nested + /// message) for the derived dype. + /// The sub-type to be considered. + /// Specific encoding style to use; in particular, Grouped can be used to avoid buffering, but is not the default. + public SubType(int fieldNumber, MetaType derivedType, DataFormat format) + { + if (derivedType == null) throw new ArgumentNullException(nameof(derivedType)); + if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + _fieldNumber = fieldNumber; + this.derivedType = derivedType; + this.dataFormat = format; + } + + private readonly DataFormat dataFormat; + + private IProtoSerializer serializer; + + internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer()); + + private IProtoSerializer BuildSerializer() + { + // note the caller here is MetaType.BuildSerializer, which already has the sync-lock + WireType wireType = WireType.String; + if(dataFormat == DataFormat.Group) wireType = WireType.StartGroup; // only one exception + + IProtoSerializer ser = new SubItemSerializer(derivedType.Type, derivedType.GetKey(false, false), derivedType, false); + return new TagDecorator(_fieldNumber, wireType, false, ser); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs.meta new file mode 100644 index 0000000..1c40acd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/SubType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4722b71e8633aa24298084c5730fb601 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs new file mode 100644 index 0000000..399c638 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs @@ -0,0 +1,33 @@ +using System; + +namespace ProtoBuf.Meta +{ + /// + /// Event data associated with new types being added to a model + /// + public sealed class TypeAddedEventArgs : EventArgs + { + internal TypeAddedEventArgs(MetaType metaType) + { + MetaType = metaType; + ApplyDefaultBehaviour = true; + } + + /// + /// Whether or not to apply the default mapping behavior + /// + public bool ApplyDefaultBehaviour { get; set; } + /// + /// The configuration of the type being added + /// + public MetaType MetaType { get; } + /// + /// The type that was added to the model + /// + public Type Type => MetaType.Type; + /// + /// The model that is being changed + /// + public RuntimeTypeModel Model => MetaType.Model as RuntimeTypeModel; + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta new file mode 100644 index 0000000..07579b7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b45ccb4bc5f92a498d78c14b8248557 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs new file mode 100644 index 0000000..3db0999 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs @@ -0,0 +1,64 @@ +using System; + +namespace ProtoBuf.Meta +{ + /// + /// Event arguments needed to perform type-formatting functions; this could be resolving a Type to a string suitable for serialization, or could + /// be requesting a Type from a string. If no changes are made, a default implementation will be used (from the assembly-qualified names). + /// + public class TypeFormatEventArgs : EventArgs + { + private Type type; + private string formattedName; + private readonly bool typeFixed; + /// + /// The type involved in this map; if this is initially null, a Type is expected to be provided for the string in FormattedName. + /// + public Type Type + { + get { return type; } + set + { + if (type != value) + { + if (typeFixed) throw new InvalidOperationException("The type is fixed and cannot be changed"); + type = value; + } + } + } + + /// + /// The formatted-name involved in this map; if this is initially null, a formatted-name is expected from the type in Type. + /// + public string FormattedName + { + get { return formattedName; } + set + { + if (formattedName != value) + { + if (!typeFixed) throw new InvalidOperationException("The formatted-name is fixed and cannot be changed"); + formattedName = value; + } + } + } + + internal TypeFormatEventArgs(string formattedName) + { + if (string.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName"); + this.formattedName = formattedName; + // typeFixed = false; <== implicit + } + + internal TypeFormatEventArgs(Type type) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + typeFixed = true; + } + } + + /// + /// Delegate type used to perform type-formatting functions; the sender originates as the type-model. + /// + public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args); +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta new file mode 100644 index 0000000..0910a59 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d50849b745c14644a2c815a932c0579 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs new file mode 100644 index 0000000..9b023a6 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; + +namespace ProtoBuf.Meta +{ + partial class TypeModel : + IProtoInput, + IProtoInput>, + IProtoInput, + IProtoOutput + { + static SerializationContext CreateContext(object userState) + { + if (userState == null) + return SerializationContext.Default; + if (userState is SerializationContext ctx) + return ctx; + + var obj = new SerializationContext { Context = userState }; + obj.Freeze(); + return obj; + } + T IProtoInput.Deserialize(Stream source, T value, object userState) + => (T)Deserialize(source, value, typeof(T), CreateContext(userState)); + + T IProtoInput>.Deserialize(ArraySegment source, T value, object userState) + { + using (var ms = new MemoryStream(source.Array, source.Offset, source.Count)) + { + return (T)Deserialize(ms, value, typeof(T), CreateContext(userState)); + } + } + + T IProtoInput.Deserialize(byte[] source, T value, object userState) + { + using (var ms = new MemoryStream(source)) + { + return (T)Deserialize(ms, value, typeof(T), CreateContext(userState)); + } + } + + void IProtoOutput.Serialize(Stream destination, T value, object userState) + => Serialize(destination, value, CreateContext(userState)); + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta new file mode 100644 index 0000000..6903930 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e0fb6c6872f245e44bf4e23d6f16c597 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs new file mode 100644 index 0000000..1867cf2 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs @@ -0,0 +1,1696 @@ +using System; +using System.IO; + +using System.Collections; +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf.Meta +{ + /// + /// Provides protobuf serialization support for a number of types + /// + public abstract partial class TypeModel + { +#if COREFX + internal TypeInfo MapType(TypeInfo type) + { + return type; + } +#endif + + /// + /// Should the Kind be included on date/time values? + /// + protected internal virtual bool SerializeDateTimeKind() { return false; } + + /// + /// Resolve a System.Type to the compiler-specific type + /// + protected internal Type MapType(Type type) + { + return MapType(type, true); + } + /// + /// Resolve a System.Type to the compiler-specific type + /// + protected internal virtual Type MapType(Type type, bool demand) + { + return type; + } + + private WireType GetWireType(ProtoTypeCode code, DataFormat format, ref Type type, out int modelKey) + { + modelKey = -1; + if (Helpers.IsEnum(type)) + { + modelKey = GetKey(ref type); + return WireType.Variant; + } + switch (code) + { + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + return format == DataFormat.FixedSize ? WireType.Fixed64 : WireType.Variant; + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.Boolean: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + return format == DataFormat.FixedSize ? WireType.Fixed32 : WireType.Variant; + case ProtoTypeCode.Double: + return WireType.Fixed64; + case ProtoTypeCode.Single: + return WireType.Fixed32; + case ProtoTypeCode.String: + case ProtoTypeCode.DateTime: + case ProtoTypeCode.Decimal: + case ProtoTypeCode.ByteArray: + case ProtoTypeCode.TimeSpan: + case ProtoTypeCode.Guid: + case ProtoTypeCode.Uri: + return WireType.String; + } + + if ((modelKey = GetKey(ref type)) >= 0) + { + return WireType.String; + } + return WireType.None; + } + + + /// + /// This is the more "complete" version of Serialize, which handles single instances of mapped types. + /// The value is written as a complete field, including field-header and (for sub-objects) a + /// length-prefix + /// In addition to that, this provides support for: + /// - basic values; individual int / string / Guid / etc + /// - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType + /// + /// + internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList, object parentList) + { + if (type == null) { type = value.GetType(); } + + ProtoTypeCode typecode = Helpers.GetTypeCode(type); + // note the "ref type" here normalizes against proxies + WireType wireType = GetWireType(typecode, format, ref type, out int modelKey); + + + if (modelKey >= 0) + { // write the header, but defer to the model + if (Helpers.IsEnum(type)) + { // no header + Serialize(modelKey, value, writer); + return true; + } + else + { + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + switch (wireType) + { + case WireType.None: + throw ProtoWriter.CreateException(writer); + case WireType.StartGroup: + case WireType.String: + // needs a wrapping length etc + SubItemToken token = ProtoWriter.StartSubItem(value, writer); + Serialize(modelKey, value, writer); + ProtoWriter.EndSubItem(token, writer); + return true; + default: + Serialize(modelKey, value, writer); + return true; + } + } + } + + if (wireType != WireType.None) + { + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + } + switch (typecode) + { + case ProtoTypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return true; + case ProtoTypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return true; + case ProtoTypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return true; + case ProtoTypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return true; + case ProtoTypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return true; + case ProtoTypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return true; + case ProtoTypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return true; + case ProtoTypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return true; + case ProtoTypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return true; + case ProtoTypeCode.Char: ProtoWriter.WriteUInt16((ushort)(char)value, writer); return true; + case ProtoTypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return true; + case ProtoTypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return true; + case ProtoTypeCode.DateTime: + if (SerializeDateTimeKind()) + BclHelpers.WriteDateTimeWithKind((DateTime)value, writer); + else + BclHelpers.WriteDateTime((DateTime)value, writer); + return true; + case ProtoTypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return true; + case ProtoTypeCode.String: ProtoWriter.WriteString((string)value, writer); return true; + case ProtoTypeCode.ByteArray: ProtoWriter.WriteBytes((byte[])value, writer); return true; + case ProtoTypeCode.TimeSpan: BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return true; + case ProtoTypeCode.Guid: BclHelpers.WriteGuid((Guid)value, writer); return true; + case ProtoTypeCode.Uri: ProtoWriter.WriteString(((Uri)value).OriginalString, writer); return true; + } + + // by now, we should have covered all the simple cases; if we wrote a field-header, we have + // forgotten something! + Helpers.DebugAssert(wireType == WireType.None); + + // now attempt to handle sequences (including arrays and lists) + if (value is IEnumerable sequence) + { + if (isInsideList) throw CreateNestedListsNotSupported(parentList?.GetType()); + foreach (object item in sequence) + { + if (item == null) { throw new NullReferenceException(); } + if (!TrySerializeAuxiliaryType(writer, null, format, tag, item, true, sequence)) + { + ThrowUnexpectedType(item.GetType()); + } + } + return true; + } + return false; + } + + private void SerializeCore(ProtoWriter writer, object value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + Type type = value.GetType(); + int key = GetKey(ref type); + if (key >= 0) + { + Serialize(key, value, writer); + } + else if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + ThrowUnexpectedType(type); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public void Serialize(Stream dest, object value) + { + Serialize(dest, value, null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + /// Additional information about this serialization operation. + public void Serialize(Stream dest, object value, SerializationContext context) + { + using (ProtoWriter writer = ProtoWriter.Create(dest, this, context)) + { + writer.SetRootObject(value); + SerializeCore(writer, value); + writer.Close(); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied writer. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination writer to write to. + public void Serialize(ProtoWriter dest, object value) + { + if (dest == null) throw new ArgumentNullException(nameof(dest)); + dest.CheckDepthFlushlock(); + dest.SetRootObject(value); + SerializeCore(dest, value); + dest.CheckDepthFlushlock(); + ProtoWriter.Flush(dest); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber) + => DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, null, out long bytesRead); + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead); + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead) + { + object result = DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead64, out bool haveObject, null); + bytesRead = checked((int)bytesRead64); + return result; + } + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead) => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out bool haveObject, null); + + private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead, out bool haveObject, SerializationContext context) + { + haveObject = false; + bool skip; + long len; + bytesRead = 0; + if (type == null && (style != PrefixStyle.Base128 || resolver == null)) + { + throw new InvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver"); + } + do + { + + bool expectPrefix = expectedField > 0 || resolver != null; + len = ProtoReader.ReadLongLengthPrefix(source, expectPrefix, style, out int actualField, out int tmpBytesRead); + if (tmpBytesRead == 0) return value; + bytesRead += tmpBytesRead; + if (len < 0) return value; + + switch (style) + { + case PrefixStyle.Base128: + if (expectPrefix && expectedField == 0 && type == null && resolver != null) + { + type = resolver(actualField); + skip = type == null; + } + else { skip = expectedField != actualField; } + break; + default: + skip = false; + break; + } + + if (skip) + { + if (len == long.MaxValue) throw new InvalidOperationException(); + ProtoReader.Seek(source, len, null); + bytesRead += len; + } + } while (skip); + + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, len); + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + value = Deserialize(key, value, reader); + } + else + { + if (!(TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null) || len == 0)) + { + TypeModel.ThrowUnexpectedType(type); // throws + } + } + bytesRead += reader.LongPosition; + haveObject = true; + return value; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). + /// The type of object to deserialize (can be null if "resolver" is specified). + /// The sequence of deserialized objects. + public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + { + return DeserializeItems(source, type, style, expectedField, resolver, null); + } + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). + /// The type of object to deserialize (can be null if "resolver" is specified). + /// The sequence of deserialized objects. + /// Additional information about this serialization operation. + public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context); + } + + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField) + { + return DeserializeItems(source, style, expectedField, null); + } + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + /// Additional information about this serialization operation. + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, style, expectedField, context); + } + + private sealed class DeserializeItemsIterator : DeserializeItemsIterator, + IEnumerator, + IEnumerable + { + IEnumerator IEnumerable.GetEnumerator() { return this; } + public new T Current { get { return (T)base.Current; } } + void IDisposable.Dispose() { } + public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context) + : base(model, source, model.MapType(typeof(T)), style, expectedField, null, context) { } + } + + private class DeserializeItemsIterator : IEnumerator, IEnumerable + { + IEnumerator IEnumerable.GetEnumerator() { return this; } + private bool haveObject; + private object current; + public bool MoveNext() + { + if (haveObject) + { + current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out long bytesRead, out haveObject, context); + } + return haveObject; + } + void IEnumerator.Reset() { throw new NotSupportedException(); } + public object Current { get { return current; } } + private readonly Stream source; + private readonly Type type; + private readonly PrefixStyle style; + private readonly int expectedField; + private readonly Serializer.TypeResolver resolver; + private readonly TypeModel model; + private readonly SerializationContext context; + public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + haveObject = true; + this.source = source; + this.type = type; + this.style = style; + this.expectedField = expectedField; + this.resolver = resolver; + this.model = model; + this.context = context; + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) + { + SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Additional information about this serialization operation. + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context) + { + if (type == null) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + type = MapType(value.GetType()); + } + int key = GetKey(ref type); + using (ProtoWriter writer = ProtoWriter.Create(dest, this, context)) + { + switch (style) + { + case PrefixStyle.None: + Serialize(key, value, writer); + break; + case PrefixStyle.Base128: + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + ProtoWriter.WriteObject(value, key, writer, style, fieldNumber); + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + writer.Close(); + } + } + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, Type type) + { + return Deserialize(source, value, type, null); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, Type type, SerializationContext context) + { + bool autoCreate = PrepareDeserialize(value, ref type); + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, ProtoReader.TO_EOF); + if (value != null) reader.SetRootObject(value); + object obj = DeserializeCore(reader, type, value, autoCreate); + reader.CheckFullyConsumed(); + return obj; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + private bool PrepareDeserialize(object value, ref Type type) + { + if (type == null) + { + if (value == null) + { + throw new ArgumentNullException(nameof(type)); + } + else + { + type = MapType(value.GetType()); + } + } + + bool autoCreate = true; + Type underlyingType = Helpers.GetUnderlyingType(type); + if (underlyingType != null) + { + type = underlyingType; + autoCreate = false; + } + return autoCreate; + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, System.Type type, int length) + => Deserialize(source, value, type, length, null); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, System.Type type, long length) + => Deserialize(source, value, type, length, null); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume (or -1 to read to the end of the stream). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, System.Type type, int length, SerializationContext context) + => Deserialize(source, value, type, length == int.MaxValue ? long.MaxValue : (long)length, context); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume (or -1 to read to the end of the stream). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, System.Type type, long length, SerializationContext context) + { + bool autoCreate = PrepareDeserialize(value, ref type); + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, length); + if (value != null) reader.SetRootObject(value); + object obj = DeserializeCore(reader, type, value, autoCreate); + reader.CheckFullyConsumed(); + return obj; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + /// + /// Applies a protocol-buffer reader to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The reader to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(ProtoReader source, object value, System.Type type) + { + if (source == null) throw new ArgumentNullException("source"); + bool autoCreate = PrepareDeserialize(value, ref type); + if (value != null) source.SetRootObject(value); + object obj = DeserializeCore(source, type, value, autoCreate); + source.CheckFullyConsumed(); + return obj; + } + + private object DeserializeCore(ProtoReader reader, Type type, object value, bool noAutoCreate) + { + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + return Deserialize(key, value, reader); + } + // this returns true to say we actively found something, but a value is assigned either way (or throws) + TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, noAutoCreate, false, null); + return value; + } + +#if COREFX + private static readonly System.Reflection.TypeInfo ilist = typeof(IList).GetTypeInfo(); +#else + private static readonly System.Type ilist = typeof(IList); +#endif + internal static MethodInfo ResolveListAdd(TypeModel model, Type listType, Type itemType, out bool isList) + { +#if COREFX || PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); +#else + Type listTypeInfo = listType; +#endif +#if PROFILE259 + isList = model.MapType(ilist).GetTypeInfo().IsAssignableFrom(listTypeInfo); +#else + isList = model.MapType(ilist).IsAssignableFrom(listTypeInfo); +#endif + Type[] types = { itemType }; + MethodInfo add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types); + +#if !NO_GENERICS + if (add == null) + { // fallback: look for ICollection's Add(typedObject) method + + bool forceList = listTypeInfo.IsInterface && + model.MapType(typeof(System.Collections.Generic.IEnumerable<>)).MakeGenericType(types) +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsAssignableFrom(listTypeInfo); + +#if COREFX || PROFILE259 + TypeInfo constuctedListType = typeof(System.Collections.Generic.ICollection<>).MakeGenericType(types).GetTypeInfo(); +#else + Type constuctedListType = model.MapType(typeof(System.Collections.Generic.ICollection<>)).MakeGenericType(types); +#endif + if (forceList || constuctedListType.IsAssignableFrom(listTypeInfo)) + { + add = Helpers.GetInstanceMethod(constuctedListType, "Add", types); + } + } + + if (add == null) + { + +#if COREFX || PROFILE259 + foreach (Type tmpType in listTypeInfo.ImplementedInterfaces) +#else + foreach (Type interfaceType in listTypeInfo.GetInterfaces()) +#endif + { +#if COREFX || PROFILE259 + TypeInfo interfaceType = tmpType.GetTypeInfo(); +#endif + if (interfaceType.Name == "IProducerConsumerCollection`1" && interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + add = Helpers.GetInstanceMethod(interfaceType, "TryAdd", types); + if (add != null) break; + } + } + } +#endif + + if (add == null) + { // fallback: look for a public list.Add(object) method + types[0] = model.MapType(typeof(object)); + add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types); + } + if (add == null && isList) + { // fallback: look for IList's Add(object) method + add = Helpers.GetInstanceMethod(model.MapType(ilist), "Add", types); + } + return add; + } + internal static Type GetListItemType(TypeModel model, Type listType) + { + Helpers.DebugAssert(listType != null); + +#if PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); + if (listType == typeof(string) || listType.IsArray + || !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(listTypeInfo)) return null; +#else + if (listType == model.MapType(typeof(string)) || listType.IsArray + || !model.MapType(typeof(IEnumerable)).IsAssignableFrom(listType)) return null; +#endif + + BasicList candidates = new BasicList(); +#if PROFILE259 + foreach (MethodInfo method in listType.GetRuntimeMethods()) +#else + foreach (MethodInfo method in listType.GetMethods()) +#endif + { + if (method.IsStatic || method.Name != "Add") continue; + ParameterInfo[] parameters = method.GetParameters(); + Type paramType; + if (parameters.Length == 1 && !candidates.Contains(paramType = parameters[0].ParameterType)) + { + candidates.Add(paramType); + } + } + + string name = listType.Name; + bool isQueueStack = name != null && (name.IndexOf("Queue") >= 0 || name.IndexOf("Stack") >= 0); + + if (!isQueueStack) + { + TestEnumerableListPatterns(model, candidates, listType); +#if PROFILE259 + foreach (Type iType in listTypeInfo.ImplementedInterfaces) + { + TestEnumerableListPatterns(model, candidates, iType); + } +#else + foreach (Type iType in listType.GetInterfaces()) + { + TestEnumerableListPatterns(model, candidates, iType); + } +#endif + } + +#if PROFILE259 + // more convenient GetProperty overload not supported on all platforms + foreach (PropertyInfo indexer in listType.GetRuntimeProperties()) + { + if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue; + ParameterInfo[] args = indexer.GetIndexParameters(); + if (args.Length != 1 || args[0].ParameterType != typeof(int)) continue; + MethodInfo getter = indexer.GetMethod; + if (getter == null || getter.IsStatic) continue; + candidates.Add(indexer.PropertyType); + } +#else + // more convenient GetProperty overload not supported on all platforms + foreach (PropertyInfo indexer in listType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue; + ParameterInfo[] args = indexer.GetIndexParameters(); + if (args.Length != 1 || args[0].ParameterType != model.MapType(typeof(int))) continue; + candidates.Add(indexer.PropertyType); + } +#endif + + switch (candidates.Count) + { + case 0: + return null; + case 1: + if ((Type)candidates[0] == listType) return null; // recursive + return (Type)candidates[0]; + case 2: + if ((Type)candidates[0] != listType && CheckDictionaryAccessors(model, (Type)candidates[0], (Type)candidates[1])) return (Type)candidates[0]; + if ((Type)candidates[1] != listType && CheckDictionaryAccessors(model, (Type)candidates[1], (Type)candidates[0])) return (Type)candidates[1]; + break; + } + + return null; + } + + private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType) + { + +#if COREFX || PROFILE259 + TypeInfo iTypeInfo = iType.GetTypeInfo(); + if (iTypeInfo.IsGenericType) + { + Type typeDef = iTypeInfo.GetGenericTypeDefinition(); + if( + typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>)) + || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>)) + || typeDef.GetTypeInfo().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + + Type[] iTypeArgs = iTypeInfo.GenericTypeArguments; + if (!candidates.Contains(iTypeArgs[0])) + { + candidates.Add(iTypeArgs[0]); + } + } + } +#else + if (iType.IsGenericType) + { + Type typeDef = iType.GetGenericTypeDefinition(); + if (typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>)) + || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>)) + || typeDef.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + Type[] iTypeArgs = iType.GetGenericArguments(); + if (!candidates.Contains(iTypeArgs[0])) + { + candidates.Add(iTypeArgs[0]); + } + } + } +#endif + } + + private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value) + { +#if COREFX || PROFILE259 + TypeInfo finalType = pair.GetTypeInfo(); + return finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>) + && finalType.GenericTypeArguments[1] == value; +#else + return pair.IsGenericType && pair.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)) + && pair.GetGenericArguments()[1] == value; +#endif + } + + private bool TryDeserializeList(TypeModel model, ProtoReader reader, DataFormat format, int tag, Type listType, Type itemType, ref object value) + { + MethodInfo addMethod = TypeModel.ResolveListAdd(model, listType, itemType, out bool isList); + if (addMethod == null) throw new NotSupportedException("Unknown list variant: " + listType.FullName); + bool found = false; + object nextItem = null; + IList list = value as IList; + object[] args = isList ? null : new object[1]; + BasicList arraySurrogate = listType.IsArray ? new BasicList() : null; + + while (TryDeserializeAuxiliaryType(reader, format, tag, itemType, ref nextItem, true, true, true, true, value ?? listType)) + { + found = true; + if (value == null && arraySurrogate == null) + { + value = CreateListInstance(listType, itemType); + list = value as IList; + } + if (list != null) + { + list.Add(nextItem); + } + else if (arraySurrogate != null) + { + arraySurrogate.Add(nextItem); + } + else + { + args[0] = nextItem; + addMethod.Invoke(value, args); + } + nextItem = null; + } + if (arraySurrogate != null) + { + Array newArray; + if (value != null) + { + if (arraySurrogate.Count == 0) + { // we'll stay with what we had, thanks + } + else + { + Array existing = (Array)value; + newArray = Array.CreateInstance(itemType, existing.Length + arraySurrogate.Count); + Array.Copy(existing, newArray, existing.Length); + arraySurrogate.CopyTo(newArray, existing.Length); + value = newArray; + } + } + else + { + newArray = Array.CreateInstance(itemType, arraySurrogate.Count); + arraySurrogate.CopyTo(newArray, 0); + value = newArray; + } + } + return found; + } + + private static object CreateListInstance(Type listType, Type itemType) + { + Type concreteListType = listType; + + if (listType.IsArray) + { + return Array.CreateInstance(itemType, 0); + } + +#if COREFX || PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); + if (!listTypeInfo.IsClass || listTypeInfo.IsAbstract || + Helpers.GetConstructor(listTypeInfo, Helpers.EmptyTypes, true) == null) +#else + if (!listType.IsClass || listType.IsAbstract || + Helpers.GetConstructor(listType, Helpers.EmptyTypes, true) == null) +#endif + { + string fullName; + bool handled = false; +#if COREFX || PROFILE259 + if (listTypeInfo.IsInterface && +#else + if (listType.IsInterface && +#endif + (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) // have to try to be frugal here... + { +#if COREFX || PROFILE259 + TypeInfo finalType = listType.GetTypeInfo(); + if (finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)) + { + Type[] genericTypes = listType.GenericTypeArguments; + concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes); + handled = true; + } +#else + if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)) + { + Type[] genericTypes = listType.GetGenericArguments(); + concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes); + handled = true; + } +#endif + +#if !PORTABLE && !COREFX && !PROFILE259 + if (!handled && listType == typeof(IDictionary)) + { + concreteListType = typeof(Hashtable); + handled = true; + } +#endif + } + + if (!handled) + { + concreteListType = typeof(System.Collections.Generic.List<>).MakeGenericType(itemType); + handled = true; + } + +#if !PORTABLE && !COREFX && !PROFILE259 + if (!handled) + { + concreteListType = typeof(ArrayList); + handled = true; + } +#endif + } + return Activator.CreateInstance(concreteListType); + } + + /// + /// This is the more "complete" version of Deserialize, which handles single instances of mapped types. + /// The value is read as a complete field, including field-header and (for sub-objects) a + /// length-prefix..kmc + /// + /// In addition to that, this provides support for: + /// - basic values; individual int / string / Guid / etc + /// - IList sets of any type handled by TryDeserializeAuxiliaryType + /// + internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + Type itemType = null; + ProtoTypeCode typecode = Helpers.GetTypeCode(type); + WireType wiretype = GetWireType(typecode, format, ref type, out int modelKey); + + bool found = false; + if (wiretype == WireType.None) + { + itemType = GetListItemType(this, type); + if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[])) + { + itemType = type.GetElementType(); + } + if (itemType != null) + { + if (insideList) throw TypeModel.CreateNestedListsNotSupported((parentListOrType as Type) ?? (parentListOrType?.GetType())); + found = TryDeserializeList(this, reader, format, tag, type, itemType, ref value); + if (!found && autoCreate) + { + value = CreateListInstance(type, itemType); + } + return found; + } + + // otherwise, not a happy bunny... + ThrowUnexpectedType(type); + } + + // to treat correctly, should read all values + + while (true) + { + // for convenience (re complex exit conditions), additional exit test here: + // if we've got the value, are only looking for one, and we aren't a list - then exit + if (found && asListItem) break; + + + // read the next item + int fieldNumber = reader.ReadFieldHeader(); + if (fieldNumber <= 0) break; + if (fieldNumber != tag) + { + if (skipOtherFields) + { + reader.SkipField(); + continue; + } + throw ProtoReader.AddErrorData(new InvalidOperationException( + "Expected field " + tag.ToString() + ", but found " + fieldNumber.ToString()), reader); + } + found = true; + reader.Hint(wiretype); // handle signed data etc + + if (modelKey >= 0) + { + switch (wiretype) + { + case WireType.String: + case WireType.StartGroup: + SubItemToken token = ProtoReader.StartSubItem(reader); + value = Deserialize(modelKey, value, reader); + ProtoReader.EndSubItem(token, reader); + continue; + default: + value = Deserialize(modelKey, value, reader); + continue; + } + } + switch (typecode) + { + case ProtoTypeCode.Int16: value = reader.ReadInt16(); continue; + case ProtoTypeCode.Int32: value = reader.ReadInt32(); continue; + case ProtoTypeCode.Int64: value = reader.ReadInt64(); continue; + case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); continue; + case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); continue; + case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); continue; + case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); continue; + case ProtoTypeCode.SByte: value = reader.ReadSByte(); continue; + case ProtoTypeCode.Byte: value = reader.ReadByte(); continue; + case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); continue; + case ProtoTypeCode.Double: value = reader.ReadDouble(); continue; + case ProtoTypeCode.Single: value = reader.ReadSingle(); continue; + case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue; + case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); continue; + case ProtoTypeCode.String: value = reader.ReadString(); continue; + case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); continue; + case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); continue; + case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); continue; + case ProtoTypeCode.Uri: value = new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); continue; + } + + } + if (!found && !asListItem && autoCreate) + { + if (type != typeof(string)) + { + value = Activator.CreateInstance(type); + } + } + return found; + } + +#if !NO_RUNTIME + /// + /// Creates a new runtime model, to which the caller + /// can add support for a range of types. A model + /// can be used "as is", or can be compiled for + /// optimal performance. + /// + [Obsolete("Please use RuntimeTypeModel.Create", false)] + public static RuntimeTypeModel Create() + { + return RuntimeTypeModel.Create(); + } +#endif + + /// + /// Applies common proxy scenarios, resolving the actual type to consider + /// + protected internal static Type ResolveProxies(Type type) + { + if (type == null) return null; +#if !NO_GENERICS + if (type.IsGenericParameter) return null; + // Nullable + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) return tmp; +#endif + +#if !CF + // EF POCO + string fullName = type.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Entity.DynamicProxies.")) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().BaseType; +#else + return type.BaseType; +#endif + } + + // NHibernate +#if PROFILE259 + IEnumerable interfaces = type.GetTypeInfo().ImplementedInterfaces; +#else + Type[] interfaces = type.GetInterfaces(); +#endif + foreach (Type t in interfaces) + { + switch (t.FullName) + { + case "NHibernate.Proxy.INHibernateProxy": + case "NHibernate.Proxy.DynamicProxy.IProxy": + case "NHibernate.Intercept.IFieldInterceptorAccessor": +#if COREFX || PROFILE259 + return type.GetTypeInfo().BaseType; +#else + return type.BaseType; +#endif + } + } +#endif + return null; + } + + /// + /// Indicates whether the supplied type is explicitly modelled by the model + /// + public bool IsDefined(Type type) => GetKey(ref type) >= 0; + + readonly Dictionary knownKeys = new Dictionary(); + + // essentially just a ValueTuple - I just don't want the extra dependency + private readonly struct KnownTypeKey + { + public KnownTypeKey(Type type, int key) + { + Type = type; + Key = key; + } + + public int Key { get; } + + public Type Type { get; } + } + + /// + /// Provides the key that represents a given type in the current model. + /// The type is also normalized for proxies at the same time. + /// + protected internal int GetKey(ref Type type) + { + if (type == null) return -1; + int key; + lock (knownKeys) + { + if (knownKeys.TryGetValue(type, out var tuple)) + { + // the type can be changed via ResolveProxies etc +#if DEBUG + var actualKey = GetKeyImpl(type); + if(actualKey != tuple.Key) + { + throw new InvalidOperationException( + $"Key cache failure; got {tuple.Key} instead of {actualKey} for '{type.Name}'"); + } +#endif + type = tuple.Type; + return tuple.Key; + } + } + key = GetKeyImpl(type); + Type originalType = type; + if (key < 0) + { + Type normalized = ResolveProxies(type); + if (normalized != null && normalized != type) + { + type = normalized; // hence ref + key = GetKeyImpl(type); + } + } + lock (knownKeys) + { + knownKeys[originalType] = new KnownTypeKey(type, key); + } + return key; + } + + /// + /// Advertise that a type's key can have changed + /// + internal void ResetKeyCache() + { + // clear *everything* (think: multi-level - can be many descendents) + lock(knownKeys) + { + knownKeys.Clear(); + } + } + + /// + /// Provides the key that represents a given type in the current model. + /// + protected abstract int GetKeyImpl(Type type); + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + protected internal abstract void Serialize(int key, object value, ProtoWriter dest); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + protected internal abstract object Deserialize(int key, object value, ProtoReader source); + + //internal ProtoSerializer Create(IProtoSerializer head) + //{ + // return new RuntimeSerializer(head, this); + //} + //internal ProtoSerializer Compile + + /// + /// Indicates the type of callback to be used + /// + protected internal enum CallbackType + { + /// + /// Invoked before an object is serialized + /// + BeforeSerialize, + /// + /// Invoked after an object is serialized + /// + AfterSerialize, + /// + /// Invoked before an object is deserialized (or when a new instance is created) + /// + BeforeDeserialize, + /// + /// Invoked after an object is deserialized + /// + AfterDeserialize + } + + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public object DeepClone(object value) + { + if (value == null) return null; + Type type = value.GetType(); + int key = GetKey(ref type); + + if (key >= 0 && !Helpers.IsEnum(type)) + { + using (MemoryStream ms = new MemoryStream()) + { + using (ProtoWriter writer = ProtoWriter.Create(ms, this, null)) + { + writer.SetRootObject(value); + Serialize(key, value, writer); + writer.Close(); + } + ms.Position = 0; + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF); + return Deserialize(key, null, reader); + } + finally + { + ProtoReader.Recycle(reader); + } + } + } + if (type == typeof(byte[])) + { + byte[] orig = (byte[])value, clone = new byte[orig.Length]; + Buffer.BlockCopy(orig, 0, clone, 0, orig.Length); + return clone; + } + else if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out int modelKey) != WireType.None && modelKey < 0) + { // immutable; just return the original value + return value; + } + using (MemoryStream ms = new MemoryStream()) + { + using (ProtoWriter writer = ProtoWriter.Create(ms, this, null)) + { + if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null)) ThrowUnexpectedType(type); + writer.Close(); + } + ms.Position = 0; + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF); + value = null; // start from scratch! + TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null); + return value; + } + finally + { + ProtoReader.Recycle(reader); + } + } + } + + /// + /// Indicates that while an inheritance tree exists, the exact type encountered was not + /// specified in that hierarchy and cannot be processed. + /// + protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual) + { + if (expected != TypeModel.ResolveProxies(actual)) + { + throw new InvalidOperationException("Unexpected sub-type: " + actual.FullName); + } + } + + /// + /// Indicates that the given type was not expected, and cannot be processed. + /// + protected internal static void ThrowUnexpectedType(Type type) + { + string fullName = type == null ? "(unknown)" : type.FullName; + + if (type != null) + { + Type baseType = type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .BaseType; + if (baseType != null && baseType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2") + { + throw new InvalidOperationException( + "Are you mixing protobuf-net and protobuf-csharp-port? See https://stackoverflow.com/q/11564914/23354; type: " + fullName); + } + } + + throw new InvalidOperationException("Type is not expected, and no contract can be inferred: " + fullName); + } + + internal static Exception CreateNestedListsNotSupported(Type type) + { + return new NotSupportedException("Nested or jagged lists and arrays are not supported: " + (type?.FullName ?? "(null)")); + } + + /// + /// Indicates that the given type cannot be constructed; it may still be possible to + /// deserialize into existing instances. + /// + public static void ThrowCannotCreateInstance(Type type) + { + throw new ProtoException("No parameterless constructor found for " + (type?.FullName ?? "(null)")); + } + + internal static string SerializeType(TypeModel model, System.Type type) + { + if (model != null) + { + TypeFormatEventHandler handler = model.DynamicTypeFormatting; + if (handler != null) + { + TypeFormatEventArgs args = new TypeFormatEventArgs(type); + handler(model, args); + if (!string.IsNullOrEmpty(args.FormattedName)) return args.FormattedName; + } + } + return type.AssemblyQualifiedName; + } + + internal static Type DeserializeType(TypeModel model, string value) + { + + if (model != null) + { + TypeFormatEventHandler handler = model.DynamicTypeFormatting; + if (handler != null) + { + TypeFormatEventArgs args = new TypeFormatEventArgs(value); + handler(model, args); + if (args.Type != null) return args.Type; + } + } + return Type.GetType(value); + } + + /// + /// Returns true if the type supplied is either a recognised contract type, + /// or a *list* of a recognised contract type. + /// + /// Note that primitives always return false, even though the engine + /// will, if forced, try to serialize such + /// True if this type is recognised as a serializable entity, else false + public bool CanSerializeContractType(Type type) => CanSerialize(type, false, true, true); + + /// + /// Returns true if the type supplied is a basic type with inbuilt handling, + /// a recognised contract type, or a *list* of a basic / contract type. + /// + public bool CanSerialize(Type type) => CanSerialize(type, true, true, true); + + /// + /// Returns true if the type supplied is a basic type with inbuilt handling, + /// or a *list* of a basic type with inbuilt handling + /// + public bool CanSerializeBasicType(Type type) => CanSerialize(type, true, false, true); + + private bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + + // is it a basic type? + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + switch (typeCode) + { + case ProtoTypeCode.Empty: + case ProtoTypeCode.Unknown: + break; + default: + return allowBasic; // well-known basic type + } + int modelKey = GetKey(ref type); + if (modelKey >= 0) return allowContract; // known contract type + + // is it a list? + if (allowLists) + { + Type itemType = null; + if (type.IsArray) + { // note we don't need to exclude byte[], as that is handled by GetTypeCode already + if (type.GetArrayRank() == 1) itemType = type.GetElementType(); + } + else + { + itemType = GetListItemType(this, type); + } + if (itemType != null) return CanSerialize(itemType, allowBasic, allowContract, false); + } + return false; + } + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + public virtual string GetSchema(Type type) => GetSchema(type, ProtoSyntax.Proto2); + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + /// The .proto syntax to use for the operation + public virtual string GetSchema(Type type, ProtoSyntax syntax) + { + throw new NotSupportedException(); + } + + /// + /// Used to provide custom services for writing and parsing type names when using dynamic types. Both parsing and formatting + /// are provided on a single API as it is essential that both are mapped identically at all times. + /// + public event TypeFormatEventHandler DynamicTypeFormatting; + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Creates a new IFormatter that uses protocol-buffer [de]serialization. + /// + /// A new IFormatter to be used during [de]serialization. + /// The type of object to be [de]deserialized by the formatter. + public System.Runtime.Serialization.IFormatter CreateFormatter(Type type) + { + return new Formatter(this, type); + } + + internal sealed class Formatter : System.Runtime.Serialization.IFormatter + { + private readonly TypeModel model; + private readonly Type type; + internal Formatter(TypeModel model, Type type) + { + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.type = type ?? throw new ArgumentNullException(nameof(type)); + } + private System.Runtime.Serialization.SerializationBinder binder; + public System.Runtime.Serialization.SerializationBinder Binder + { + get { return binder; } + set { binder = value; } + } + + private System.Runtime.Serialization.StreamingContext context; + public System.Runtime.Serialization.StreamingContext Context + { + get { return context; } + set { context = value; } + } + + public object Deserialize(Stream source) + { + return model.Deserialize(source, null, type, (long)-1, Context); + } + + public void Serialize(Stream destination, object graph) + { + model.Serialize(destination, graph, Context); + } + + private System.Runtime.Serialization.ISurrogateSelector surrogateSelector; + public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector + { + get { return surrogateSelector; } + set { surrogateSelector = value; } + } + } +#endif + +#if DEBUG // this is used by some unit tests only, to ensure no buffering when buffering is disabled + private bool forwardsOnly; + /// + /// If true, buffering of nested objects is disabled + /// + public bool ForwardsOnly + { + get { return forwardsOnly; } + set { forwardsOnly = value; } + } +#endif + + internal virtual Type GetType(string fullName, Assembly context) + { + return ResolveKnownType(fullName, this, context); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + internal static Type ResolveKnownType(string name, TypeModel model, Assembly assembly) + { + if (string.IsNullOrEmpty(name)) return null; + try + { + Type type = Type.GetType(name); + + if (type != null) return type; + } + catch { } + try + { + int i = name.IndexOf(','); + string fullName = (i > 0 ? name.Substring(0, i) : name).Trim(); +#if !(COREFX || PROFILE259) + if (assembly == null) assembly = Assembly.GetCallingAssembly(); +#endif + Type type = assembly?.GetType(fullName); + if (type != null) return type; + } + catch { } + return null; + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta new file mode 100644 index 0000000..48ca627 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d1954b0478fa0042a2fe4a505949bcd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs new file mode 100644 index 0000000..9566312 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs @@ -0,0 +1,855 @@ +#if !NO_RUNTIME +using System; + +using ProtoBuf.Serializers; +using System.Globalization; +using System.Collections.Generic; + +#if PROFILE259 +using System.Reflection; +using System.Linq; +#else +using System.Reflection; +#endif + +namespace ProtoBuf.Meta +{ + /// + /// Represents a member (property/field) that is mapped to a protobuf field + /// + public class ValueMember + { + private int _fieldNumber; + /// + /// The number that identifies this member in a protobuf stream + /// + public int FieldNumber + { + get => _fieldNumber; + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + private readonly MemberInfo originalMember; + private MemberInfo backingMember; + /// + /// Gets the member (field/property) which this member relates to. + /// + public MemberInfo Member { get { return originalMember; } } + /// + /// Gets the backing member (field/property) which this member relates to + /// + public MemberInfo BackingMember + { + get { return backingMember; } + set + { + if (backingMember != value) + { + ThrowIfFrozen(); + backingMember = value; + } + } + } + + private readonly Type parentType, itemType, defaultType, memberType; + private object defaultValue; + + /// + /// Within a list / array / etc, the type of object for each item in the list (especially useful with ArrayList) + /// + public Type ItemType => itemType; + + /// + /// The underlying type of the member + /// + public Type MemberType => memberType; + + /// + /// For abstract types (IList etc), the type of concrete object to create (if required) + /// + public Type DefaultType => defaultType; + + /// + /// The type the defines the member + /// + public Type ParentType => parentType; + + /// + /// The default value of the item (members with this value will not be serialized) + /// + public object DefaultValue + { + get { return defaultValue; } + set + { + if (defaultValue != value) + { + ThrowIfFrozen(); + defaultValue = value; + } + } + } + + private readonly RuntimeTypeModel model; + /// + /// Creates a new ValueMember instance + /// + public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) + : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat) + { + if (parentType == null) throw new ArgumentNullException("parentType"); + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber"); + + this.originalMember = member ?? throw new ArgumentNullException("member"); + this.parentType = parentType; + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber"); + //#if WINRT + if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType) + //#else + // if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue)) + //#endif + { + defaultValue = ParseDefaultValue(memberType, defaultValue); + } + this.defaultValue = defaultValue; + + MetaType type = model.FindWithoutAdd(memberType); + if (type != null) + { + AsReference = type.AsReferenceDefault; + } + else + { // we need to scan the hard way; can't risk recursion by fully walking it + AsReference = MetaType.GetAsReferenceDefault(model, memberType); + } + } + /// + /// Creates a new ValueMember instance + /// + internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat) + { + _fieldNumber = fieldNumber; + this.memberType = memberType ?? throw new ArgumentNullException(nameof(memberType)); + this.itemType = itemType; + this.defaultType = defaultType; + + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.dataFormat = dataFormat; + } + internal object GetRawEnumValue() + { +#if PORTABLE || CF || COREFX || PROFILE259 + object value = ((FieldInfo)originalMember).GetValue(null); + switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)originalMember).FieldType))) + { + case ProtoTypeCode.SByte: return (sbyte)value; + case ProtoTypeCode.Byte: return (byte)value; + case ProtoTypeCode.Int16: return (short)value; + case ProtoTypeCode.UInt16: return (ushort)value; + case ProtoTypeCode.Int32: return (int)value; + case ProtoTypeCode.UInt32: return (uint)value; + case ProtoTypeCode.Int64: return (long)value; + case ProtoTypeCode.UInt64: return (ulong)value; + default: + throw new InvalidOperationException(); + } +#else + return ((FieldInfo)originalMember).GetRawConstantValue(); +#endif + } + private static object ParseDefaultValue(Type type, object value) + { + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + } + if (value is string s) + { + if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s); + + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: return bool.Parse(s); + case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Char: // char.Parse missing on CF/phone7 + if (s.Length == 1) return s[0]; + throw new FormatException("Single character expected: \"" + s + "\""); + case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture); + case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.String: return s; + case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s); + case ProtoTypeCode.Uri: return s; // Uri is decorated as string + case ProtoTypeCode.Guid: return new Guid(s); + } + } + + if (Helpers.IsEnum(type)) return Enum.ToObject(type, value); + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + + } + + private IProtoSerializer serializer; + internal IProtoSerializer Serializer + { + get + { + return serializer ?? (serializer = BuildSerializer()); + } + } + + private DataFormat dataFormat; + /// + /// Specifies the rules used to process the field; this is used to determine the most appropriate + /// wite-type, but also to describe subtypes within that wire-type (such as SignedVariant) + /// + public DataFormat DataFormat + { + get { return dataFormat; } + set + { + if (value != dataFormat) + { + ThrowIfFrozen(); + this.dataFormat = value; + } + } + } + + /// + /// Indicates whether this field should follow strict encoding rules; this means (for example) that if a "fixed32" + /// is encountered when "variant" is defined, then it will fail (throw an exception) when parsing. Note that + /// when serializing the defined type is always used. + /// + public bool IsStrict + { + get { return HasFlag(OPTIONS_IsStrict); } + set { SetFlag(OPTIONS_IsStrict, value, true); } + } + + /// + /// Indicates whether this field should use packed encoding (which can save lots of space for repeated primitive values). + /// This option only applies to list/array data of primitive types (int, double, etc). + /// + public bool IsPacked + { + get { return HasFlag(OPTIONS_IsPacked); } + set { SetFlag(OPTIONS_IsPacked, value, true); } + } + + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + public bool OverwriteList + { + get { return HasFlag(OPTIONS_OverwriteList); } + set { SetFlag(OPTIONS_OverwriteList, value, true); } + } + + /// + /// Indicates whether this field is mandatory. + /// + public bool IsRequired + { + get { return HasFlag(OPTIONS_IsRequired); } + set { SetFlag(OPTIONS_IsRequired, value, true); } + } + + /// + /// Enables full object-tracking/full-graph support. + /// + public bool AsReference + { + get { return HasFlag(OPTIONS_AsReference); } + set { SetFlag(OPTIONS_AsReference, value, true); } + } + + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + public bool DynamicType + { + get { return HasFlag(OPTIONS_DynamicType); } + set { SetFlag(OPTIONS_DynamicType, value, true); } + } + + /// + /// Indicates that the member should be treated as a protobuf Map + /// + public bool IsMap + { + get { return HasFlag(OPTIONS_IsMap); } + set { SetFlag(OPTIONS_IsMap, value, true); } + } + + private DataFormat mapKeyFormat, mapValueFormat; + /// + /// Specifies the data-format that should be used for the key, when IsMap is enabled + /// + public DataFormat MapKeyFormat + { + get { return mapKeyFormat; } + set + { + if (mapKeyFormat != value) + { + ThrowIfFrozen(); + mapKeyFormat = value; + } + } + } + /// + /// Specifies the data-format that should be used for the value, when IsMap is enabled + /// + public DataFormat MapValueFormat + { + get { return mapValueFormat; } + set + { + if (mapValueFormat != value) + { + ThrowIfFrozen(); + mapValueFormat = value; + } + } + } + + private MethodInfo getSpecified, setSpecified; + /// + /// Specifies methods for working with optional data members. + /// + /// Provides a method (null for none) to query whether this member should + /// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the + /// method returns true. + /// Provides a method (null for none) to indicate that a member was + /// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true" + /// when data is found. + public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified) + { + if (this.getSpecified != getSpecified || this.setSpecified != setSpecified) + { + if (getSpecified != null) + { + if (getSpecified.ReturnType != model.MapType(typeof(bool)) + || getSpecified.IsStatic + || getSpecified.GetParameters().Length != 0) + { + throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified"); + } + } + if (setSpecified != null) + { + ParameterInfo[] args; + if (setSpecified.ReturnType != model.MapType(typeof(void)) + || setSpecified.IsStatic + || (args = setSpecified.GetParameters()).Length != 1 + || args[0].ParameterType != model.MapType(typeof(bool))) + { + throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified"); + } + } + + ThrowIfFrozen(); + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + } + + private void ThrowIfFrozen() + { + if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + + internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType) + { + dictionaryType = keyType = valueType = null; + try + { +#if COREFX || PROFILE259 + var info = memberType.GetTypeInfo(); +#else + var info = memberType; +#endif + if (ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out _, out _, out _, out _, out _, out _)) + { + return false; + } + if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { +#if PROFILE259 + var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments; +#else + var typeArgs = memberType.GetGenericArguments(); +#endif + if (IsValidMapKeyType(typeArgs[0])) + { + keyType = typeArgs[0]; + valueType = typeArgs[1]; + dictionaryType = memberType; + } + return false; + } +#if PROFILE259 + foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces) +#else + foreach (var iType in memberType.GetInterfaces()) +#endif + { +#if COREFX || PROFILE259 + info = iType.GetTypeInfo(); +#else + info = iType; +#endif + if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { + if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName); +#if PROFILE259 + var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments; +#else + var typeArgs = iType.GetGenericArguments(); +#endif + if (IsValidMapKeyType(typeArgs[0])) + { + keyType = typeArgs[0]; + valueType = typeArgs[1]; + dictionaryType = memberType; + } + } + } + if (dictionaryType == null) return false; + + // (note we checked the key type already) + // not a map if value is repeated + Type itemType = null, defaultType = null; + model.ResolveListTypes(valueType, ref itemType, ref defaultType); + if (itemType != null) return false; + + return dictionaryType != null; + } + catch + { + // if it isn't a good fit; don't use "map" + return false; + } + } + + static bool IsValidMapKeyType(Type type) + { + if (type == null || Helpers.IsEnum(type)) return false; + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.String: + + case ProtoTypeCode.SByte: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + return true; + } + return false; + } + private IProtoSerializer BuildSerializer() + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken);// check nobody is still adding this type + var member = backingMember ?? originalMember; + IProtoSerializer ser; + if (IsMap) + { + ResolveMapTypes(out var dictionaryType, out var keyType, out var valueType); + + if (dictionaryType == null) + { + throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName); + } + var concreteType = defaultType; + if (concreteType == null && Helpers.IsClass(memberType)) + { + concreteType = memberType; + } + var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out var keyWireType, false, false, false, false); + if (!AsReference) + { + AsReference = MetaType.GetAsReferenceDefault(model, valueType); + } + var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType, out var valueWireType, AsReference, DynamicType, false, true); +#if PROFILE259 + IEnumerable ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetTypeInfo().DeclaredConstructors; + if (ctors.Count() != 1) + { + throw new InvalidOperationException("Unable to resolve MapDecorator constructor"); + } + ser = (IProtoSerializer)ctors.First().Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber, + DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList }); +#else + var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors( + BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor"); + ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber, + DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList }); +#endif + } + else + { + Type finalType = itemType ?? memberType; + ser = TryGetCoreSerializer(model, dataFormat, finalType, out WireType wireType, AsReference, DynamicType, OverwriteList, true); + if (ser == null) + { + throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName); + } + + // apply tags + if (itemType != null && SupportNull) + { + if (IsPacked) + { + throw new NotSupportedException("Packed encodings cannot support null values"); + } + ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser); + ser = new NullDecorator(model, ser); + ser = new TagDecorator(_fieldNumber, WireType.StartGroup, false, ser); + } + else + { + ser = new TagDecorator(_fieldNumber, wireType, IsStrict, ser); + } + // apply lists if appropriate + if (itemType != null) + { + Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType; + + Helpers.DebugAssert(underlyingItemType == ser.ExpectedType + || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)) + , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType); + if (memberType.IsArray) + { + ser = new ArrayDecorator(model, ser, _fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull); + } + else + { + ser = ListDecorator.Create(model, memberType, defaultType, ser, _fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull); + } + } + else if (defaultValue != null && !IsRequired && getSpecified == null) + { // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue, + // as does "IsRequired" + ser = new DefaultValueDecorator(model, defaultValue, ser); + } + if (memberType == model.MapType(typeof(Uri))) + { + ser = new UriDecorator(model, ser); + } +#if PORTABLE + else if(memberType.FullName == typeof(Uri).FullName) + { + // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri) + ser = new ReflectedUriDecorator(memberType, model, ser); + } +#endif + } + if (member != null) + { + if (member is PropertyInfo prop) + { + ser = new PropertyDecorator(model, parentType, prop, ser); + } + else if (member is FieldInfo fld) + { + ser = new FieldDecorator(parentType, fld, ser); + } + else + { + throw new InvalidOperationException(); + } + + if (getSpecified != null || setSpecified != null) + { + ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser); + } + } + return ser; + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + private static WireType GetIntWireType(DataFormat format, int width) + { + switch (format) + { + case DataFormat.ZigZag: return WireType.SignedVariant; + case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64; + case DataFormat.TwosComplement: + case DataFormat.Default: return WireType.Variant; + default: throw new InvalidOperationException(); + } + } + private static WireType GetDateTimeWireType(DataFormat format) + { + switch (format) + { + + case DataFormat.Group: return WireType.StartGroup; + case DataFormat.FixedSize: return WireType.Fixed64; + case DataFormat.WellKnown: + case DataFormat.Default: + return WireType.String; + default: throw new InvalidOperationException(); + } + } + + internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, + bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) + { + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + } + if (Helpers.IsEnum(type)) + { + if (allowComplexTypes && model != null) + { + // need to do this before checking the typecode; an int enum will report Int32 etc + defaultWireType = WireType.Variant; + return new EnumSerializer(type, model.GetEnumMap(type)); + } + else + { // enum is fine for adding as a meta-type + defaultWireType = WireType.None; + return null; + } + } + ProtoTypeCode code = Helpers.GetTypeCode(type); + switch (code) + { + case ProtoTypeCode.Int32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int32Serializer(model); + case ProtoTypeCode.UInt32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt32Serializer(model); + case ProtoTypeCode.Int64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new Int64Serializer(model); + case ProtoTypeCode.UInt64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new UInt64Serializer(model); + case ProtoTypeCode.String: + defaultWireType = WireType.String; + if (asReference) + { + return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference); + } + return new StringSerializer(model); + case ProtoTypeCode.Single: + defaultWireType = WireType.Fixed32; + return new SingleSerializer(model); + case ProtoTypeCode.Double: + defaultWireType = WireType.Fixed64; + return new DoubleSerializer(model); + case ProtoTypeCode.Boolean: + defaultWireType = WireType.Variant; + return new BooleanSerializer(model); + case ProtoTypeCode.DateTime: + defaultWireType = GetDateTimeWireType(dataFormat); + return new DateTimeSerializer(dataFormat, model); + case ProtoTypeCode.Decimal: + defaultWireType = WireType.String; + return new DecimalSerializer(model); + case ProtoTypeCode.Byte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new ByteSerializer(model); + case ProtoTypeCode.SByte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new SByteSerializer(model); + case ProtoTypeCode.Char: + defaultWireType = WireType.Variant; + return new CharSerializer(model); + case ProtoTypeCode.Int16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int16Serializer(model); + case ProtoTypeCode.UInt16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt16Serializer(model); + case ProtoTypeCode.TimeSpan: + defaultWireType = GetDateTimeWireType(dataFormat); + return new TimeSpanSerializer(dataFormat, model); + case ProtoTypeCode.Guid: + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new GuidSerializer(model); + case ProtoTypeCode.Uri: + defaultWireType = WireType.String; + return new StringSerializer(model); + case ProtoTypeCode.ByteArray: + defaultWireType = WireType.String; + return new BlobSerializer(model, overwriteList); + case ProtoTypeCode.Type: + defaultWireType = WireType.String; + return new SystemTypeSerializer(model); + } + IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null; + if (parseable != null) + { + defaultWireType = WireType.String; + return parseable; + } + if (allowComplexTypes && model != null) + { + int key = model.GetKey(type, false, true); + MetaType meta = null; + if (key >= 0) + { + meta = model[type]; + if (dataFormat == DataFormat.Default && meta.IsGroup) + { + dataFormat = DataFormat.Group; + } + } + + if (asReference || dynamicType) + { + BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; + if (asReference) options |= BclHelpers.NetObjectOptions.AsReference; + if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType; + if (meta != null) + { // exists + if (asReference && Helpers.IsValueType(type)) + { + string message = "AsReference cannot be used with value-types"; + + if (type.Name == "KeyValuePair`2") + { + message += "; please see https://stackoverflow.com/q/14436606/23354"; + } + else + { + message += ": " + type.FullName; + } + throw new InvalidOperationException(message); + } + + if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet; + if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor; + } + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new NetObjectSerializer(model, type, key, options); + } + if (key >= 0) + { + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new SubItemSerializer(type, key, meta, true); + } + } + defaultWireType = WireType.None; + return null; + } + + + private string name; + internal void SetName(string name) + { + if (name != this.name) + { + ThrowIfFrozen(); + this.name = name; + } + } + /// + /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used + /// when inferring a schema). + /// + public string Name + { + get { return string.IsNullOrEmpty(name) ? originalMember.Name : name; } + set { SetName(value); } + } + + private const byte + OPTIONS_IsStrict = 1, + OPTIONS_IsPacked = 2, + OPTIONS_IsRequired = 4, + OPTIONS_OverwriteList = 8, + OPTIONS_SupportNull = 16, + OPTIONS_AsReference = 32, + OPTIONS_IsMap = 64, + OPTIONS_DynamicType = 128; + + private byte flags; + private bool HasFlag(byte flag) { return (flags & flag) == flag; } + private void SetFlag(byte flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + flags |= flag; + else + flags = (byte)(flags & ~flag); + } + + /// + /// Should lists have extended support for null values? Note this makes the serialization less efficient. + /// + public bool SupportNull + { + get { return HasFlag(OPTIONS_SupportNull); } + set { SetFlag(OPTIONS_SupportNull, value, true); } + } + + internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports) + { + Type effectiveType = ItemType; + if (effectiveType == null) effectiveType = MemberType; + return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports); + } + + + internal sealed class Comparer : System.Collections.IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as ValueMember, y as ValueMember); + } + + public int Compare(ValueMember x, ValueMember y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta new file mode 100644 index 0000000..19ebdd3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3080d8ea2db9215468efe3639ee81a7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs new file mode 100644 index 0000000..8e83549 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + internal sealed class NetObjectCache + { + internal const int Root = 0; + private MutableList underlyingList; + + private MutableList List => underlyingList ?? (underlyingList = new MutableList()); + + internal object GetKeyedObject(int key) + { + if (key-- == Root) + { + if (rootObject == null) throw new ProtoException("No root object assigned"); + return rootObject; + } + BasicList list = List; + + if (key < 0 || key >= list.Count) + { + Helpers.DebugWriteLine("Missing key: " + key); + throw new ProtoException("Internal error; a missing key occurred"); + } + + object tmp = list[key]; + if (tmp == null) + { + throw new ProtoException("A deferred key does not have a value yet"); + } + return tmp; + } + + internal void SetKeyedObject(int key, object value) + { + if (key-- == Root) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + if (rootObject != null && ((object)rootObject != (object)value)) throw new ProtoException("The root object cannot be reassigned"); + rootObject = value; + } + else + { + MutableList list = List; + if (key < list.Count) + { + object oldVal = list[key]; + if (oldVal == null) + { + list[key] = value; + } + else if (!ReferenceEquals(oldVal, value)) + { + throw new ProtoException("Reference-tracked objects cannot change reference"); + } // otherwise was the same; nothing to do + } + else if (key != list.Add(value)) + { + throw new ProtoException("Internal error; a key mismatch occurred"); + } + } + } + + private object rootObject; + internal int AddObjectKey(object value, out bool existing) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + + if ((object)value == (object)rootObject) // (object) here is no-op, but should be + { // preserved even if this was typed - needs ref-check + existing = true; + return Root; + } + + string s = value as string; + BasicList list = List; + int index; + + if (s == null) + { +#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way + index = list.IndexOfReference(value); +#else + if (objectKeys == null) + { + objectKeys = new Dictionary(ReferenceComparer.Default); + index = -1; + } + else + { + if (!objectKeys.TryGetValue(value, out index)) index = -1; + } +#endif + } + else + { + if (stringKeys == null) + { + stringKeys = new Dictionary(); + index = -1; + } + else + { + if (!stringKeys.TryGetValue(s, out index)) index = -1; + } + } + + if (!(existing = index >= 0)) + { + index = list.Add(value); + + if (s == null) + { +#if !CF && !PORTABLE // CF can't handle the object keys very well + objectKeys.Add(value, index); +#endif + } + else + { + stringKeys.Add(s, index); + } + } + return index + 1; + } + + private int trapStartIndex; // defaults to 0 - optimization for RegisterTrappedObject + // to make it faster at seeking to find deferred-objects + + internal void RegisterTrappedObject(object value) + { + if (rootObject == null) + { + rootObject = value; + } + else + { + if (underlyingList != null) + { + for (int i = trapStartIndex; i < underlyingList.Count; i++) + { + trapStartIndex = i + 1; // things never *become* null; whether or + // not the next item is null, it will never + // need to be checked again + + if (underlyingList[i] == null) + { + underlyingList[i] = value; + break; + } + } + } + } + } + + private Dictionary stringKeys; + +#if !CF && !PORTABLE // CF lacks the ability to get a robust reference-based hash-code, so we'll do it the harder way instead + private System.Collections.Generic.Dictionary objectKeys; + private sealed class ReferenceComparer : IEqualityComparer + { + public readonly static ReferenceComparer Default = new ReferenceComparer(); + private ReferenceComparer() { } + + bool IEqualityComparer.Equals(object x, object y) + { + return x == y; // ref equality + } + + int IEqualityComparer.GetHashCode(object obj) + { + return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); + } + } +#endif + + internal void Clear() + { + trapStartIndex = 0; + rootObject = null; + if (underlyingList != null) underlyingList.Clear(); + if (stringKeys != null) stringKeys.Clear(); +#if !CF && !PORTABLE + if (objectKeys != null) objectKeys.Clear(); +#endif + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs.meta new file mode 100644 index 0000000..422332b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/NetObjectCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a270f5bbdb4a634d8c0b37610358da2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs new file mode 100644 index 0000000..0ebef04 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs @@ -0,0 +1,26 @@ + +namespace ProtoBuf +{ + /// + /// Specifies the type of prefix that should be applied to messages. + /// + public enum PrefixStyle + { + /// + /// No length prefix is applied to the data; the data is terminated only be the end of the stream. + /// + None = 0, + /// + /// A base-128 ("varint", the default prefix format in protobuf) length prefix is applied to the data (efficient for short messages). + /// + Base128 = 1, + /// + /// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility). + /// + Fixed32 = 2, + /// + /// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility). + /// + Fixed32BigEndian = 3 + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs.meta new file mode 100644 index 0000000..c82e909 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/PrefixStyle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a290bed47536d714392c2106dff542b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs new file mode 100644 index 0000000..e2e8054 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs @@ -0,0 +1,175 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a type is defined for protocol-buffer serialization. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, + AllowMultiple = false, Inherited = false)] + public sealed class ProtoContractAttribute : Attribute + { + /// + /// Gets or sets the defined name of the type. + /// + public string Name { get; set; } + + /// + /// Gets or sets the fist offset to use with implicit field tags; + /// only uesd if ImplicitFields is set. + /// + public int ImplicitFirstTag + { + get { return implicitFirstTag; } + set + { + if (value < 1) throw new ArgumentOutOfRangeException("ImplicitFirstTag"); + implicitFirstTag = value; + } + } + private int implicitFirstTag; + + /// + /// If specified, alternative contract markers (such as markers for XmlSerailizer or DataContractSerializer) are ignored. + /// + public bool UseProtoMembersOnly + { + get { return HasFlag(OPTIONS_UseProtoMembersOnly); } + set { SetFlag(OPTIONS_UseProtoMembersOnly, value); } + } + + /// + /// If specified, do NOT treat this type as a list, even if it looks like one. + /// + public bool IgnoreListHandling + { + get { return HasFlag(OPTIONS_IgnoreListHandling); } + set { SetFlag(OPTIONS_IgnoreListHandling, value); } + } + + /// + /// Gets or sets the mechanism used to automatically infer field tags + /// for members. This option should be used in advanced scenarios only. + /// Please review the important notes against the ImplicitFields enumeration. + /// + public ImplicitFields ImplicitFields { get; set; } + + /// + /// Enables/disables automatic tag generation based on the existing name / order + /// of the defined members. This option is not used for members marked + /// with ProtoMemberAttribute, as intended to provide compatibility with + /// WCF serialization. WARNING: when adding new fields you must take + /// care to increase the Order for new elements, otherwise data corruption + /// may occur. + /// + /// If not explicitly specified, the default is assumed from Serializer.GlobalOptions.InferTagFromName. + public bool InferTagFromName + { + get { return HasFlag(OPTIONS_InferTagFromName); } + set + { + SetFlag(OPTIONS_InferTagFromName, value); + SetFlag(OPTIONS_InferTagFromNameHasValue, true); + } + } + + /// + /// Has a InferTagFromName value been explicitly set? if not, the default from the type-model is assumed. + /// + internal bool InferTagFromNameHasValue + { // note that this property is accessed via reflection and should not be removed + get { return HasFlag(OPTIONS_InferTagFromNameHasValue); } + } + + /// + /// Specifies an offset to apply to [DataMember(Order=...)] markers; + /// this is useful when working with mex-generated classes that have + /// a different origin (usually 1 vs 0) than the original data-contract. + /// + /// This value is added to the Order of each member. + /// + public int DataMemberOffset { get; set; } + + /// + /// If true, the constructor for the type is bypassed during deserialization, meaning any field initializers + /// or other initialization code is skipped. + /// + public bool SkipConstructor + { + get { return HasFlag(OPTIONS_SkipConstructor); } + set { SetFlag(OPTIONS_SkipConstructor, value); } + } + + /// + /// Should this type be treated as a reference by default? Please also see the implications of this, + /// as recorded on ProtoMemberAttribute.AsReference + /// + public bool AsReferenceDefault + { + get { return HasFlag(OPTIONS_AsReferenceDefault); } + set + { + SetFlag(OPTIONS_AsReferenceDefault, value); + } + } + + /// + /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message) + /// + public bool IsGroup + { + get { return HasFlag(OPTIONS_IsGroup); } + set + { + SetFlag(OPTIONS_IsGroup, value); + } + } + + private bool HasFlag(ushort flag) { return (flags & flag) == flag; } + private void SetFlag(ushort flag, bool value) + { + if (value) flags |= flag; + else flags = (ushort)(flags & ~flag); + } + + private ushort flags; + + private const ushort + OPTIONS_InferTagFromName = 1, + OPTIONS_InferTagFromNameHasValue = 2, + OPTIONS_UseProtoMembersOnly = 4, + OPTIONS_SkipConstructor = 8, + OPTIONS_IgnoreListHandling = 16, + OPTIONS_AsReferenceDefault = 32, + OPTIONS_EnumPassthru = 64, + OPTIONS_EnumPassthruHasValue = 128, + OPTIONS_IsGroup = 256; + + /// + /// Applies only to enums (not to DTO classes themselves); gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather + /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums. + /// + public bool EnumPassthru + { + get { return HasFlag(OPTIONS_EnumPassthru); } + set + { + SetFlag(OPTIONS_EnumPassthru, value); + SetFlag(OPTIONS_EnumPassthruHasValue, true); + } + } + + /// + /// Allows to define a surrogate type used for serialization/deserialization purpose. + /// + public Type Surrogate { get; set; } + + /// + /// Has a EnumPassthru value been explicitly set? + /// + internal bool EnumPassthruHasValue + { // note that this property is accessed via reflection and should not be removed + get { return HasFlag(OPTIONS_EnumPassthruHasValue); } + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta new file mode 100644 index 0000000..66b30f7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 44318d0e03cd0314db0e669e23907219 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs new file mode 100644 index 0000000..b75bb80 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs @@ -0,0 +1,13 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a static member should be considered the same as though + /// were an implicit / explicit conversion operator; in particular, this + /// is useful for conversions that operator syntax does not allow, such as + /// to/from interface types. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public class ProtoConverterAttribute : Attribute { } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta new file mode 100644 index 0000000..dd8902f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4dfe39d573d66374a9b2ff9d1d999f12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs new file mode 100644 index 0000000..1d82645 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs @@ -0,0 +1,36 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Used to define protocol-buffer specific behavior for + /// enumerated values. + /// + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + public sealed class ProtoEnumAttribute : Attribute + { + /// + /// Gets or sets the specific value to use for this enum during serialization. + /// + public int Value + { + get { return enumValue; } + set { this.enumValue = value; hasValue = true; } + } + + /// + /// Indicates whether this instance has a customised value mapping + /// + /// true if a specific value is set + public bool HasValue() => hasValue; + + private bool hasValue; + private int enumValue; + + /// + /// Gets or sets the defined name of the enum, as used in .proto + /// (this name is not used during serialization). + /// + public string Name { get; set; } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta new file mode 100644 index 0000000..7c0265b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3bf14bc2adcb93b4aa2db40f50d29c01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs new file mode 100644 index 0000000..f502527 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs @@ -0,0 +1,30 @@ +using System; + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) +using System.Runtime.Serialization; +#endif +namespace ProtoBuf +{ + /// + /// Indicates an error during serialization/deserialization of a proto stream. + /// +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + [Serializable] +#endif + public class ProtoException : Exception + { + /// Creates a new ProtoException instance. + public ProtoException() { } + + /// Creates a new ProtoException instance. + public ProtoException(string message) : base(message) { } + + /// Creates a new ProtoException instance. + public ProtoException(string message, Exception innerException) : base(message, innerException) { } + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// Creates a new ProtoException instance. + protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs.meta new file mode 100644 index 0000000..934a111 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: da068ead862618642a75042e1ac688ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs new file mode 100644 index 0000000..775674e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs @@ -0,0 +1,40 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a member should be excluded from serialization; this + /// is only normally used when using implict fields. + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = false, Inherited = true)] + public class ProtoIgnoreAttribute : Attribute { } + + /// + /// Indicates that a member should be excluded from serialization; this + /// is only normally used when using implict fields. This allows + /// ProtoIgnoreAttribute usage + /// even for partial classes where the individual members are not + /// under direct control. + /// + [AttributeUsage(AttributeTargets.Class, + AllowMultiple = true, Inherited = false)] + public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute + { + /// + /// Creates a new ProtoPartialIgnoreAttribute instance. + /// + /// Specifies the member to be ignored. + public ProtoPartialIgnoreAttribute(string memberName) + : base() + { + if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName)); + + MemberName = memberName; + } + /// + /// The name of the member to be ignored. + /// + public string MemberName { get; } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta new file mode 100644 index 0000000..78ec3d9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 330a624572944724baf0046bd8bb35c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs new file mode 100644 index 0000000..bb83ef7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs @@ -0,0 +1,60 @@ +using System; +using System.ComponentModel; + +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// Indicates the known-types to support for an individual + /// message. This serializes each level in the hierarchy as + /// a nested message to retain wire-compatibility with + /// other protocol-buffer implementations. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] + public sealed class ProtoIncludeAttribute : Attribute + { + /// + /// Creates a new instance of the ProtoIncludeAttribute. + /// + /// The unique index (within the type) that will identify this data. + /// The additional type to serialize/deserialize. + public ProtoIncludeAttribute(int tag, Type knownType) + : this(tag, knownType == null ? "" : knownType.AssemblyQualifiedName) { } + + /// + /// Creates a new instance of the ProtoIncludeAttribute. + /// + /// The unique index (within the type) that will identify this data. + /// The additional type to serialize/deserialize. + public ProtoIncludeAttribute(int tag, string knownTypeName) + { + if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag), "Tags must be positive integers"); + if (string.IsNullOrEmpty(knownTypeName)) throw new ArgumentNullException(nameof(knownTypeName), "Known type cannot be blank"); + Tag = tag; + KnownTypeName = knownTypeName; + } + + /// + /// Gets the unique index (within the type) that will identify this data. + /// + public int Tag { get; } + + /// + /// Gets the additional type to serialize/deserialize. + /// + public string KnownTypeName { get; } + + /// + /// Gets the additional type to serialize/deserialize. + /// + public Type KnownType => TypeModel.ResolveKnownType(KnownTypeName, null, null); + + /// + /// Specifies whether the inherited sype's sub-message should be + /// written with a length-prefix (default), or with group markers. + /// + [DefaultValue(DataFormat.Default)] + public DataFormat DataFormat { get; set; } = DataFormat.Default; + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta new file mode 100644 index 0000000..5bb0405 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 63df23c9d0b657e4bba0e579aed41281 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs new file mode 100644 index 0000000..e85441a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs @@ -0,0 +1,29 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Controls the formatting of elements in a dictionary, and indicates that + /// "map" rules should be used: duplicates *replace* earlier values, rather + /// than throwing an exception + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ProtoMapAttribute : Attribute + { + /// + /// Describes the data-format used to store the key + /// + public DataFormat KeyFormat { get; set; } + /// + /// Describes the data-format used to store the value + /// + public DataFormat ValueFormat { get; set; } + + /// + /// Disables "map" handling; dictionaries will use ".Add(key,value)" instead of "[key] = value", + /// which means duplicate keys will cause an exception (instead of retaining the final value); if + /// a proto schema is emitted, it will be produced using "repeated" instead of "map" + /// + public bool DisableMap { get; set; } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta new file mode 100644 index 0000000..17527d3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e8b2314bed356854192eb46db632ed06 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs new file mode 100644 index 0000000..e5ab896 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs @@ -0,0 +1,228 @@ +using System; +using System.Reflection; + +namespace ProtoBuf +{ + /// + /// Declares a member to be used in protocol-buffer serialization, using + /// the given Tag. A DataFormat may be used to optimise the serialization + /// format (for instance, using zigzag encoding for negative numbers, or + /// fixed-length encoding for large values. + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = false, Inherited = true)] + public class ProtoMemberAttribute : Attribute + , IComparable + , IComparable + + { + /// + /// Compare with another ProtoMemberAttribute for sorting purposes + /// + public int CompareTo(object other) => CompareTo(other as ProtoMemberAttribute); + /// + /// Compare with another ProtoMemberAttribute for sorting purposes + /// + public int CompareTo(ProtoMemberAttribute other) + { + if (other == null) return -1; + if ((object)this == (object)other) return 0; + int result = this.tag.CompareTo(other.tag); + if (result == 0) result = string.CompareOrdinal(this.name, other.name); + return result; + } + + /// + /// Creates a new ProtoMemberAttribute instance. + /// + /// Specifies the unique tag used to identify this member within the type. + public ProtoMemberAttribute(int tag) : this(tag, false) + { } + + internal ProtoMemberAttribute(int tag, bool forced) + { + if (tag <= 0 && !forced) throw new ArgumentOutOfRangeException(nameof(tag)); + this.tag = tag; + } + +#if !NO_RUNTIME + internal MemberInfo Member, BackingMember; + internal bool TagIsPinned; +#endif + /// + /// Gets or sets the original name defined in the .proto; not used + /// during serialization. + /// + public string Name { get { return name; } set { name = value; } } + private string name; + + /// + /// Gets or sets the data-format to be used when encoding this value. + /// + public DataFormat DataFormat { get { return dataFormat; } set { dataFormat = value; } } + private DataFormat dataFormat; + + /// + /// Gets the unique tag used to identify this member within the type. + /// + public int Tag { get { return tag; } } + private int tag; + internal void Rebase(int tag) { this.tag = tag; } + + /// + /// Gets or sets a value indicating whether this member is mandatory. + /// + public bool IsRequired + { + get { return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; } + set + { + if (value) options |= MemberSerializationOptions.Required; + else options &= ~MemberSerializationOptions.Required; + } + } + + /// + /// Gets a value indicating whether this member is packed. + /// This option only applies to list/array data of primitive types (int, double, etc). + /// + public bool IsPacked + { + get { return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; } + set + { + if (value) options |= MemberSerializationOptions.Packed; + else options &= ~MemberSerializationOptions.Packed; + } + } + + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + public bool OverwriteList + { + get { return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList; } + set + { + if (value) options |= MemberSerializationOptions.OverwriteList; + else options &= ~MemberSerializationOptions.OverwriteList; + } + } + + /// + /// Enables full object-tracking/full-graph support. + /// + public bool AsReference + { + get { return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; } + set + { + if (value) options |= MemberSerializationOptions.AsReference; + else options &= ~MemberSerializationOptions.AsReference; + + options |= MemberSerializationOptions.AsReferenceHasValue; + } + } + + internal bool AsReferenceHasValue + { + get { return (options & MemberSerializationOptions.AsReferenceHasValue) == MemberSerializationOptions.AsReferenceHasValue; } + set + { + if (value) options |= MemberSerializationOptions.AsReferenceHasValue; + else options &= ~MemberSerializationOptions.AsReferenceHasValue; + } + } + + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + public bool DynamicType + { + get { return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; } + set + { + if (value) options |= MemberSerializationOptions.DynamicType; + else options &= ~MemberSerializationOptions.DynamicType; + } + } + + /// + /// Gets or sets a value indicating whether this member is packed (lists/arrays). + /// + public MemberSerializationOptions Options { get { return options; } set { options = value; } } + private MemberSerializationOptions options; + + + } + + /// + /// Additional (optional) settings that control serialization of members + /// + [Flags] + public enum MemberSerializationOptions + { + /// + /// Default; no additional options + /// + None = 0, + /// + /// Indicates that repeated elements should use packed (length-prefixed) encoding + /// + Packed = 1, + /// + /// Indicates that the given item is required + /// + Required = 2, + /// + /// Enables full object-tracking/full-graph support + /// + AsReference = 4, + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance + /// + DynamicType = 8, + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + OverwriteList = 16, + /// + /// Determines whether the types AsReferenceDefault value is used, or whether this member's AsReference should be used + /// + AsReferenceHasValue = 32 + } + + /// + /// Declares a member to be used in protocol-buffer serialization, using + /// the given Tag and MemberName. This allows ProtoMemberAttribute usage + /// even for partial classes where the individual members are not + /// under direct control. + /// A DataFormat may be used to optimise the serialization + /// format (for instance, using zigzag encoding for negative numbers, or + /// fixed-length encoding for large values. + /// + [AttributeUsage(AttributeTargets.Class, + AllowMultiple = true, Inherited = false)] + public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute + { + /// + /// Creates a new ProtoMemberAttribute instance. + /// + /// Specifies the unique tag used to identify this member within the type. + /// Specifies the member to be serialized. + public ProtoPartialMemberAttribute(int tag, string memberName) + : base(tag) + { +#if !NO_RUNTIME + if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName)); +#endif + this.MemberName = memberName; + } + /// + /// The name of the member to be serialized. + /// + public string MemberName { get; private set; } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta new file mode 100644 index 0000000..2bcb69e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b29c776ccaebb674abb1cf87233198dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs new file mode 100644 index 0000000..3ea9bf9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs @@ -0,0 +1,1444 @@ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// A stateful reader, used to read a protobuf stream. Typical usage would be (sequentially) to call + /// ReadFieldHeader and (after matching the field) an appropriate Read* method. + /// + public sealed class ProtoReader : IDisposable + { + Stream source; + byte[] ioBuffer; + TypeModel model; + int fieldNumber, depth, ioIndex, available; + long position64, blockEnd64, dataRemaining64; + WireType wireType; + bool isFixedLength, internStrings; + private NetObjectCache netCache; + + // this is how many outstanding objects do not currently have + // values for the purposes of reference tracking; we'll default + // to just trapping the root object + // note: objects are trapped (the ref and key mapped) via NoteObject + uint trapCount; // uint is so we can use beq/bne more efficiently than bgt + + /// + /// Gets the number of the field being processed. + /// + public int FieldNumber => fieldNumber; + + /// + /// Indicates the underlying proto serialization format on the wire. + /// + public WireType WireType => wireType; + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context) + { + + Init(this, source, model, context, TO_EOF); + } + + internal const long TO_EOF = -1; + + /// + /// Gets / sets a flag indicating whether strings should be checked for repetition; if + /// true, any repeated UTF-8 byte sequence will result in the same String instance, rather + /// than a second instance of the same string. Enabled by default. Note that this uses + /// a custom interner - the system-wide string interner is not used. + /// + public bool InternStrings { get { return internStrings; } set { internStrings = value; } } + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length) + { + Init(this, source, model, context, length); + } + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, long length) + { + Init(this, source, model, context, length); + } + + private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, long length) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (!source.CanRead) throw new ArgumentException("Cannot read from stream", nameof(source)); + reader.source = source; + reader.ioBuffer = BufferPool.GetBuffer(); + reader.model = model; + bool isFixedLength = length >= 0; + reader.isFixedLength = isFixedLength; + reader.dataRemaining64 = isFixedLength ? length : 0; + + if (context == null) { context = SerializationContext.Default; } + else { context.Freeze(); } + reader.context = context; + reader.position64 = 0; + reader.available = reader.depth = reader.fieldNumber = reader.ioIndex = 0; + reader.blockEnd64 = long.MaxValue; + reader.internStrings = RuntimeTypeModel.Default.InternStrings; + reader.wireType = WireType.None; + reader.trapCount = 1; + if (reader.netCache == null) reader.netCache = new NetObjectCache(); + } + + private SerializationContext context; + + /// + /// Addition information about this deserialization operation. + /// + public SerializationContext Context => context; + + /// + /// Releases resources used by the reader, but importantly does not Dispose the + /// underlying stream; in many typical use-cases the stream is used for different + /// processes, so it is assumed that the consumer will Dispose their stream separately. + /// + public void Dispose() + { + // importantly, this does **not** own the stream, and does not dispose it + source = null; + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + if (stringInterner != null) + { + stringInterner.Clear(); + stringInterner = null; + } + if (netCache != null) netCache.Clear(); + } + internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value) + { + if (available < 10) Ensure(10, false); + if (available == 0) + { + value = 0; + return 0; + } + int readPos = ioIndex; + value = ioBuffer[readPos++]; + if ((value & 0x80) == 0) return 1; + value &= 0x7F; + if (available == 1) throw EoF(this); + + uint chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 7; + if ((chunk & 0x80) == 0) return 2; + if (available == 2) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 14; + if ((chunk & 0x80) == 0) return 3; + if (available == 3) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 21; + if ((chunk & 0x80) == 0) return 4; + if (available == 4) throw EoF(this); + + chunk = ioBuffer[readPos]; + value |= chunk << 28; // can only use 4 bits from this chunk + if ((chunk & 0xF0) == 0) return 5; + + if (trimNegative // allow for -ve values + && (chunk & 0xF0) == 0xF0 + && available >= 10 + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0x01) + { + return 10; + } + throw AddErrorData(new OverflowException(), this); + } + + private uint ReadUInt32Variant(bool trimNegative) + { + int read = TryReadUInt32VariantWithoutMoving(trimNegative, out uint value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return value; + } + throw EoF(this); + } + + private bool TryReadUInt32Variant(out uint value) + { + int read = TryReadUInt32VariantWithoutMoving(false, out value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return true; + } + return false; + } + + /// + /// Reads an unsigned 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public uint ReadUInt32() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt32Variant(false); + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + position64 += 4; + available -= 4; + return ((uint)ioBuffer[ioIndex++]) + | (((uint)ioBuffer[ioIndex++]) << 8) + | (((uint)ioBuffer[ioIndex++]) << 16) + | (((uint)ioBuffer[ioIndex++]) << 24); + case WireType.Fixed64: + ulong val = ReadUInt64(); + checked { return (uint)val; } + default: + throw CreateWireTypeException(); + } + } + + /// + /// Returns the position of the current reader (note that this is not necessarily the same as the position + /// in the underlying stream, if multiple readers are used on the same stream) + /// + public int Position { get { return checked((int)position64); } } + + /// + /// Returns the position of the current reader (note that this is not necessarily the same as the position + /// in the underlying stream, if multiple readers are used on the same stream) + /// + public long LongPosition { get { return position64; } } + internal void Ensure(int count, bool strict) + { + Helpers.DebugAssert(available <= count, "Asking for data without checking first"); + if (count > ioBuffer.Length) + { + BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available); + ioIndex = 0; + } + else if (ioIndex + count >= ioBuffer.Length) + { + // need to shift the buffer data to the left to make space + Buffer.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available); + ioIndex = 0; + } + count -= available; + int writePos = ioIndex + available, bytesRead; + int canRead = ioBuffer.Length - writePos; + if (isFixedLength) + { // throttle it if needed + if (dataRemaining64 < canRead) canRead = (int)dataRemaining64; + } + while (count > 0 && canRead > 0 && (bytesRead = source.Read(ioBuffer, writePos, canRead)) > 0) + { + available += bytesRead; + count -= bytesRead; + canRead -= bytesRead; + writePos += bytesRead; + if (isFixedLength) { dataRemaining64 -= bytesRead; } + } + if (strict && count > 0) + { + throw EoF(this); + } + + } + /// + /// Reads a signed 16-bit integer from the stream: Variant, Fixed32, Fixed64, SignedVariant + /// + public short ReadInt16() + { + checked { return (short)ReadInt32(); } + } + /// + /// Reads an unsigned 16-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public ushort ReadUInt16() + { + checked { return (ushort)ReadUInt32(); } + } + + /// + /// Reads an unsigned 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public byte ReadByte() + { + checked { return (byte)ReadUInt32(); } + } + + /// + /// Reads a signed 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public sbyte ReadSByte() + { + checked { return (sbyte)ReadInt32(); } + } + + /// + /// Reads a signed 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public int ReadInt32() + { + switch (wireType) + { + case WireType.Variant: + return (int)ReadUInt32Variant(true); + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + position64 += 4; + available -= 4; + return ((int)ioBuffer[ioIndex++]) + | (((int)ioBuffer[ioIndex++]) << 8) + | (((int)ioBuffer[ioIndex++]) << 16) + | (((int)ioBuffer[ioIndex++]) << 24); + case WireType.Fixed64: + long l = ReadInt64(); + checked { return (int)l; } + case WireType.SignedVariant: + return Zag(ReadUInt32Variant(true)); + default: + throw CreateWireTypeException(); + } + } + private const long Int64Msb = ((long)1) << 63; + private const int Int32Msb = ((int)1) << 31; + private static int Zag(uint ziggedValue) + { + int value = (int)ziggedValue; + return (-(value & 0x01)) ^ ((value >> 1) & ~ProtoReader.Int32Msb); + } + + private static long Zag(ulong ziggedValue) + { + long value = (long)ziggedValue; + return (-(value & 0x01L)) ^ ((value >> 1) & ~ProtoReader.Int64Msb); + } + /// + /// Reads a signed 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public long ReadInt64() + { + switch (wireType) + { + case WireType.Variant: + return (long)ReadUInt64Variant(); + case WireType.Fixed32: + return ReadInt32(); + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + position64 += 8; + available -= 8; + +#if NETCOREAPP2_1 + var result = System.Buffers.Binary.BinaryPrimitives.ReadInt64LittleEndian(ioBuffer.AsSpan(ioIndex, 8)); + + ioIndex+= 8; + + return result; +#else + return ((long)ioBuffer[ioIndex++]) + | (((long)ioBuffer[ioIndex++]) << 8) + | (((long)ioBuffer[ioIndex++]) << 16) + | (((long)ioBuffer[ioIndex++]) << 24) + | (((long)ioBuffer[ioIndex++]) << 32) + | (((long)ioBuffer[ioIndex++]) << 40) + | (((long)ioBuffer[ioIndex++]) << 48) + | (((long)ioBuffer[ioIndex++]) << 56); +#endif + case WireType.SignedVariant: + return Zag(ReadUInt64Variant()); + default: + throw CreateWireTypeException(); + } + } + + private int TryReadUInt64VariantWithoutMoving(out ulong value) + { + if (available < 10) Ensure(10, false); + if (available == 0) + { + value = 0; + return 0; + } + int readPos = ioIndex; + value = ioBuffer[readPos++]; + if ((value & 0x80) == 0) return 1; + value &= 0x7F; + if (available == 1) throw EoF(this); + + ulong chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 7; + if ((chunk & 0x80) == 0) return 2; + if (available == 2) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 14; + if ((chunk & 0x80) == 0) return 3; + if (available == 3) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 21; + if ((chunk & 0x80) == 0) return 4; + if (available == 4) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 28; + if ((chunk & 0x80) == 0) return 5; + if (available == 5) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 35; + if ((chunk & 0x80) == 0) return 6; + if (available == 6) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 42; + if ((chunk & 0x80) == 0) return 7; + if (available == 7) throw EoF(this); + + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 49; + if ((chunk & 0x80) == 0) return 8; + if (available == 8) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 56; + if ((chunk & 0x80) == 0) return 9; + if (available == 9) throw EoF(this); + + chunk = ioBuffer[readPos]; + value |= chunk << 63; // can only use 1 bit from this chunk + + if ((chunk & ~(ulong)0x01) != 0) throw AddErrorData(new OverflowException(), this); + return 10; + } + + private ulong ReadUInt64Variant() + { + int read = TryReadUInt64VariantWithoutMoving(out ulong value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return value; + } + throw EoF(this); + } + + private Dictionary stringInterner; + private string Intern(string value) + { + if (value == null) return null; + if (value.Length == 0) return ""; + if (stringInterner == null) + { + stringInterner = new Dictionary + { + { value, value } + }; + } + else if (stringInterner.TryGetValue(value, out string found)) + { + value = found; + } + else + { + stringInterner.Add(value, value); + } + return value; + } + +#if COREFX + static readonly Encoding encoding = Encoding.UTF8; +#else + static readonly UTF8Encoding encoding = new UTF8Encoding(); +#endif + /// + /// Reads a string from the stream (using UTF8); supported wire-types: String + /// + public string ReadString() + { + if (wireType == WireType.String) + { + int bytes = (int)ReadUInt32Variant(false); + if (bytes == 0) return ""; + if (bytes < 0) ThrowInvalidLength(bytes); + if (available < bytes) Ensure(bytes, true); + + string s = encoding.GetString(ioBuffer, ioIndex, bytes); + + if (internStrings) { s = Intern(s); } + available -= bytes; + position64 += bytes; + ioIndex += bytes; + return s; + } + throw CreateWireTypeException(); + } + /// + /// Throws an exception indication that the given value cannot be mapped to an enum. + /// + public void ThrowEnumException(Type type, int value) + { + string desc = type == null ? "" : type.FullName; + throw AddErrorData(new ProtoException("No " + desc + " enum is mapped to the wire-value " + value.ToString()), this); + } + + private void ThrowInvalidLength(long length) + { + throw AddErrorData(new InvalidOperationException("Invalid length: " + length.ToString()), this); + } + + private Exception CreateWireTypeException() + { + return CreateException("Invalid wire-type; this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354"); + } + + private Exception CreateException(string message) + { + return AddErrorData(new ProtoException(message), this); + } + /// + /// Reads a double-precision number from the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + double ReadDouble() + { + switch (wireType) + { + case WireType.Fixed32: + return ReadSingle(); + case WireType.Fixed64: + long value = ReadInt64(); +#if FEAT_SAFE + return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); +#else + return *(double*)&value; +#endif + default: + throw CreateWireTypeException(); + } + } + + /// + /// Reads (merges) a sub-message from the stream, internally calling StartSubItem and EndSubItem, and (in between) + /// parsing the message in accordance with the model associated with the reader + /// + public static object ReadObject(object value, int key, ProtoReader reader) + { + return ReadTypedObject(value, key, reader, null); + } + + internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type) + { + if (reader.model == null) + { + throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader); + } + SubItemToken token = ProtoReader.StartSubItem(reader); + if (key >= 0) + { + value = reader.model.Deserialize(key, value, reader); + } + else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null)) + { + // ok + } + else + { + TypeModel.ThrowUnexpectedType(type); + } + ProtoReader.EndSubItem(token, reader); + return value; + } + + /// + /// Makes the end of consuming a nested message in the stream; the stream must be either at the correct EndGroup + /// marker, or all fields of the sub-message must have been consumed (in either case, this means ReadFieldHeader + /// should return zero) + /// + public static void EndSubItem(SubItemToken token, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + long value64 = token.value64; + switch (reader.wireType) + { + case WireType.EndGroup: + if (value64 >= 0) throw AddErrorData(new ArgumentException("token"), reader); + if (-(int)value64 != reader.fieldNumber) throw reader.CreateException("Wrong group was ended"); // wrong group ended! + reader.wireType = WireType.None; // this releases ReadFieldHeader + reader.depth--; + break; + // case WireType.None: // TODO reinstate once reads reset the wire-type + default: + if (value64 < reader.position64) throw reader.CreateException($"Sub-message not read entirely; expected {value64}, was {reader.position64}"); + if (reader.blockEnd64 != reader.position64 && reader.blockEnd64 != long.MaxValue) + { + throw reader.CreateException("Sub-message not read correctly"); + } + reader.blockEnd64 = value64; + reader.depth--; + break; + /*default: + throw reader.BorkedIt(); */ + } + } + + /// + /// Begins consuming a nested message in the stream; supported wire-types: StartGroup, String + /// + /// The token returned must be help and used when callining EndSubItem + public static SubItemToken StartSubItem(ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + switch (reader.wireType) + { + case WireType.StartGroup: + reader.wireType = WireType.None; // to prevent glitches from double-calling + reader.depth++; + return new SubItemToken((long)(-reader.fieldNumber)); + case WireType.String: + long len = (long)reader.ReadUInt64Variant(); + if (len < 0) reader.ThrowInvalidLength(len); + long lastEnd = reader.blockEnd64; + reader.blockEnd64 = reader.position64 + len; + reader.depth++; + return new SubItemToken(lastEnd); + default: + throw reader.CreateWireTypeException(); // throws + } + } + + /// + /// Reads a field header from the stream, setting the wire-type and retuning the field number. If no + /// more fields are available, then 0 is returned. This methods respects sub-messages. + /// + public int ReadFieldHeader() + { + // at the end of a group the caller must call EndSubItem to release the + // reader (which moves the status to Error, since ReadFieldHeader must + // then be called) + if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return 0; } + + if (TryReadUInt32Variant(out uint tag) && tag != 0) + { + wireType = (WireType)(tag & 7); + fieldNumber = (int)(tag >> 3); + if (fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString()); + } + else + { + wireType = WireType.None; + fieldNumber = 0; + } + if (wireType == ProtoBuf.WireType.EndGroup) + { + if (depth > 0) return 0; // spoof an end, but note we still set the field-number + throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt"); + } + return fieldNumber; + } + /// + /// Looks ahead to see whether the next field in the stream is what we expect + /// (typically; what we've just finished reading - for example ot read successive list items) + /// + public bool TryReadFieldHeader(int field) + { + // check for virtual end of stream + if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return false; } + + int read = TryReadUInt32VariantWithoutMoving(false, out uint tag); + WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens + if (read > 0 && ((int)tag >> 3) == field + && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup) + { + wireType = tmpWireType; + fieldNumber = field; + position64 += read; + ioIndex += read; + available -= read; + return true; + } + return false; + } + + /// + /// Get the TypeModel associated with this reader + /// + public TypeModel Model { get { return model; } } + + /// + /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example, + /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made. + /// + public void Hint(WireType wireType) + { + if (this.wireType == wireType) { } // fine; everything as we expect + else if (((int)wireType & 7) == (int)this.wireType) + { // the underling type is a match; we're customising it with an extension + this.wireType = wireType; + } + // note no error here; we're OK about using alternative data + } + + /// + /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example, + /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown. + /// + public void Assert(WireType wireType) + { + if (this.wireType == wireType) { } // fine; everything as we expect + else if (((int)wireType & 7) == (int)this.wireType) + { // the underling type is a match; we're customising it with an extension + this.wireType = wireType; + } + else + { // nope; that is *not* what we were expecting! + throw CreateWireTypeException(); + } + } + + /// + /// Discards the data for the current field. + /// + public void SkipField() + { + switch (wireType) + { + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + available -= 4; + ioIndex += 4; + position64 += 4; + return; + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + available -= 8; + ioIndex += 8; + position64 += 8; + return; + case WireType.String: + long len = (long)ReadUInt64Variant(); + if (len < 0) ThrowInvalidLength(len); + if (len <= available) + { // just jump it! + available -= (int)len; + ioIndex += (int)len; + position64 += len; + return; + } + // everything remaining in the buffer is garbage + position64 += len; // assumes success, but if it fails we're screwed anyway + len -= available; // discount anything we've got to-hand + ioIndex = available = 0; // note that we have no data in the buffer + if (isFixedLength) + { + if (len > dataRemaining64) throw EoF(this); + // else assume we're going to be OK + dataRemaining64 -= len; + } + ProtoReader.Seek(source, len, ioBuffer); + return; + case WireType.Variant: + case WireType.SignedVariant: + ReadUInt64Variant(); // and drop it + return; + case WireType.StartGroup: + int originalFieldNumber = this.fieldNumber; + depth++; // need to satisfy the sanity-checks in ReadFieldHeader + while (ReadFieldHeader() > 0) { SkipField(); } + depth--; + if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber) + { // we expect to exit in a similar state to how we entered + wireType = ProtoBuf.WireType.None; + return; + } + throw CreateWireTypeException(); + case WireType.None: // treat as explicit errorr + case WireType.EndGroup: // treat as explicit error + default: // treat as implicit error + throw CreateWireTypeException(); + } + } + + /// + /// Reads an unsigned 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public ulong ReadUInt64() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt64Variant(); + case WireType.Fixed32: + return ReadUInt32(); + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + position64 += 8; + available -= 8; + + return ((ulong)ioBuffer[ioIndex++]) + | (((ulong)ioBuffer[ioIndex++]) << 8) + | (((ulong)ioBuffer[ioIndex++]) << 16) + | (((ulong)ioBuffer[ioIndex++]) << 24) + | (((ulong)ioBuffer[ioIndex++]) << 32) + | (((ulong)ioBuffer[ioIndex++]) << 40) + | (((ulong)ioBuffer[ioIndex++]) << 48) + | (((ulong)ioBuffer[ioIndex++]) << 56); + default: + throw CreateWireTypeException(); + } + } + /// + /// Reads a single-precision number from the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + float ReadSingle() + { + switch (wireType) + { + case WireType.Fixed32: + { + int value = ReadInt32(); +#if FEAT_SAFE + return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); +#else + return *(float*)&value; +#endif + } + case WireType.Fixed64: + { + double value = ReadDouble(); + float f = (float)value; + if (float.IsInfinity(f) && !double.IsInfinity(value)) + { + throw AddErrorData(new OverflowException(), this); + } + return f; + } + default: + throw CreateWireTypeException(); + } + } + + /// + /// Reads a boolean value from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + /// + public bool ReadBoolean() + { + switch (ReadUInt32()) + { + case 0: return false; + case 1: return true; + default: throw CreateException("Unexpected boolean value"); + } + } + + private static readonly byte[] EmptyBlob = new byte[0]; + /// + /// Reads a byte-sequence from the stream, appending them to an existing byte-sequence (which can be null); supported wire-types: String + /// + public static byte[] AppendBytes(byte[] value, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + switch (reader.wireType) + { + case WireType.String: + int len = (int)reader.ReadUInt32Variant(false); + reader.wireType = WireType.None; + if (len == 0) return value ?? EmptyBlob; + if (len < 0) reader.ThrowInvalidLength(len); + int offset; + if (value == null || value.Length == 0) + { + offset = 0; + value = new byte[len]; + } + else + { + offset = value.Length; + byte[] tmp = new byte[value.Length + len]; + Buffer.BlockCopy(value, 0, tmp, 0, value.Length); + value = tmp; + } + // value is now sized with the final length, and (if necessary) + // contains the old data up to "offset" + reader.position64 += len; // assume success + while (len > reader.available) + { + if (reader.available > 0) + { + // copy what we *do* have + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available); + len -= reader.available; + offset += reader.available; + reader.ioIndex = reader.available = 0; // we've drained the buffer + } + // now refill the buffer (without overflowing it) + int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len; + if (count > 0) reader.Ensure(count, true); + } + // at this point, we know that len <= available + if (len > 0) + { // still need data, but we have enough buffered + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len); + reader.ioIndex += len; + reader.available -= len; + } + return value; + case WireType.Variant: + return new byte[0]; + default: + throw reader.CreateWireTypeException(); + } + } + + //static byte[] ReadBytes(Stream stream, int length) + //{ + // if (stream == null) throw new ArgumentNullException("stream"); + // if (length < 0) throw new ArgumentOutOfRangeException("length"); + // byte[] buffer = new byte[length]; + // int offset = 0, read; + // while (length > 0 && (read = stream.Read(buffer, offset, length)) > 0) + // { + // length -= read; + // } + // if (length > 0) throw EoF(null); + // return buffer; + //} + private static int ReadByteOrThrow(Stream source) + { + int val = source.ReadByte(); + if (val < 0) throw EoF(null); + return val; + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber) + => ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out int bytesRead); + + /// + /// Reads a little-endian encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadLittleEndianInt32(Stream source) + { + return ReadByteOrThrow(source) + | (ReadByteOrThrow(source) << 8) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 24); + } + + /// + /// Reads a big-endian encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadBigEndianInt32(Stream source) + { + return (ReadByteOrThrow(source) << 24) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 8) + | ReadByteOrThrow(source); + } + + /// + /// Reads a varint encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadVarintInt32(Stream source) + { + int bytes = TryReadUInt64Variant(source, out ulong val); + if (bytes <= 0) throw EoF(null); + return checked((int)val); + } + + /// + /// Reads a string (of a given lenth, in bytes) directly from the source into a pre-existing buffer. An exception is thrown if the data is not all available. + /// + public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count) + { + int read; + if (source == null) throw new ArgumentNullException("source"); + while (count > 0 && (read = source.Read(buffer, offset, count)) > 0) + { + count -= read; + offset += read; + } + if (count > 0) throw EoF(null); + } + + /// + /// Reads a given number of bytes directly from the source. An exception is thrown if the data is not all available. + /// + public static byte[] DirectReadBytes(Stream source, int count) + { + byte[] buffer = new byte[count]; + DirectReadBytes(source, buffer, 0, count); + return buffer; + } + + /// + /// Reads a string (of a given lenth, in bytes) directly from the source. An exception is thrown if the data is not all available. + /// + public static string DirectReadString(Stream source, int length) + { + byte[] buffer = new byte[length]; + DirectReadBytes(source, buffer, 0, length); + return Encoding.UTF8.GetString(buffer, 0, length); + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + if (style == PrefixStyle.None) + { + bytesRead = fieldNumber = 0; + return int.MaxValue; // avoid the long.maxvalue causing overflow + } + long len64 = ReadLongLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead); + return checked((int)len64); + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static long ReadLongLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + fieldNumber = 0; + switch (style) + { + case PrefixStyle.None: + bytesRead = 0; + return long.MaxValue; + case PrefixStyle.Base128: + ulong val; + int tmpBytesRead; + bytesRead = 0; + if (expectHeader) + { + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + if (tmpBytesRead > 0) + { + if ((val & 7) != (uint)WireType.String) + { // got a header, but it isn't a string + throw new InvalidOperationException(); + } + fieldNumber = (int)(val >> 3); + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + if (bytesRead == 0) + { // got a header, but no length + throw EoF(null); + } + return (long)val; + } + else + { // no header + bytesRead = 0; + return -1; + } + } + // check for a length + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + return bytesRead < 0 ? -1 : (long)val; + + case PrefixStyle.Fixed32: + { + int b = source.ReadByte(); + if (b < 0) + { + bytesRead = 0; + return -1; + } + bytesRead = 4; + return b + | (ReadByteOrThrow(source) << 8) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 24); + } + case PrefixStyle.Fixed32BigEndian: + { + int b = source.ReadByte(); + if (b < 0) + { + bytesRead = 0; + return -1; + } + bytesRead = 4; + return (b << 24) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 8) + | ReadByteOrThrow(source); + } + default: + throw new ArgumentOutOfRangeException("style"); + } + } + + /// The number of bytes consumed; 0 if no data available + private static int TryReadUInt64Variant(Stream source, out ulong value) + { + value = 0; + int b = source.ReadByte(); + if (b < 0) { return 0; } + value = (uint)b; + if ((value & 0x80) == 0) { return 1; } + value &= 0x7F; + int bytesRead = 1, shift = 7; + while (bytesRead < 9) + { + b = source.ReadByte(); + if (b < 0) throw EoF(null); + value |= ((ulong)b & 0x7F) << shift; + shift += 7; + bytesRead++; + + if ((b & 0x80) == 0) return bytesRead; + } + b = source.ReadByte(); + if (b < 0) throw EoF(null); + if ((b & 1) == 0) // only use 1 bit from the last byte + { + value |= ((ulong)b & 0x7F) << shift; + return ++bytesRead; + } + throw new OverflowException(); + } + + internal static void Seek(Stream source, long count, byte[] buffer) + { + if (source.CanSeek) + { + source.Seek(count, SeekOrigin.Current); + count = 0; + } + else if (buffer != null) + { + int bytesRead; + while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= bytesRead; + } + while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0) + { + count -= bytesRead; + } + } + else // borrow a buffer + { + buffer = BufferPool.GetBuffer(); + try + { + int bytesRead; + while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= bytesRead; + } + while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0) + { + count -= bytesRead; + } + } + finally + { + BufferPool.ReleaseBufferToPool(ref buffer); + } + } + if (count > 0) throw EoF(null); + } + internal static Exception AddErrorData(Exception exception, ProtoReader source) + { +#if !CF && !PORTABLE + if (exception != null && source != null && !exception.Data.Contains("protoSource")) + { + exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}", + source.fieldNumber, source.wireType, source.position64, source.depth)); + } +#endif + return exception; + } + + private static Exception EoF(ProtoReader source) + { + return AddErrorData(new EndOfStreamException(), source); + } + + /// + /// Copies the current field into the instance as extension data + /// + public void AppendExtensionData(IExtensible instance) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + IExtension extn = instance.GetExtensionObject(true); + bool commit = false; + // unusually we *don't* want "using" here; the "finally" does that, with + // the extension object being responsible for disposal etc + Stream dest = extn.BeginAppend(); + try + { + //TODO: replace this with stream-based, buffered raw copying + using (ProtoWriter writer = ProtoWriter.Create(dest, model, null)) + { + AppendExtensionField(writer); + writer.Close(); + } + commit = true; + } + finally { extn.EndAppend(dest, commit); } + } + + private void AppendExtensionField(ProtoWriter writer) + { + //TODO: replace this with stream-based, buffered raw copying + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer); + switch (wireType) + { + case WireType.Fixed32: + ProtoWriter.WriteInt32(ReadInt32(), writer); + return; + case WireType.Variant: + case WireType.SignedVariant: + case WireType.Fixed64: + ProtoWriter.WriteInt64(ReadInt64(), writer); + return; + case WireType.String: + ProtoWriter.WriteBytes(AppendBytes(null, this), writer); + return; + case WireType.StartGroup: + SubItemToken readerToken = StartSubItem(this), + writerToken = ProtoWriter.StartSubItem(null, writer); + while (ReadFieldHeader() > 0) { AppendExtensionField(writer); } + EndSubItem(readerToken, this); + ProtoWriter.EndSubItem(writerToken, writer); + return; + case WireType.None: // treat as explicit errorr + case WireType.EndGroup: // treat as explicit error + default: // treat as implicit error + throw CreateWireTypeException(); + } + } + + /// + /// Indicates whether the reader still has data remaining in the current sub-item, + /// additionally setting the wire-type for the next field if there is more data. + /// This is used when decoding packed data. + /// + public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source) + { + if (source == null) throw new ArgumentNullException("source"); + // check for virtual end of stream + if (source.blockEnd64 <= source.position64 || wireType == WireType.EndGroup) { return false; } + source.wireType = wireType; + return true; + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + internal NetObjectCache NetCache => netCache; + + internal Type DeserializeType(string value) + { + return TypeModel.DeserializeType(model, value); + } + + internal void SetRootObject(object value) + { + netCache.SetKeyedObject(NetObjectCache.Root, value); + trapCount--; + } + + /// + /// Utility method, not intended for public use; this helps maintain the root object is complex scenarios + /// + public static void NoteObject(object value, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + if (reader.trapCount != 0) + { + reader.netCache.RegisterTrappedObject(value); + reader.trapCount--; + } + } + + /// + /// Reads a Type from the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String + /// + public Type ReadType() + { + return TypeModel.DeserializeType(model, ReadString()); + } + + internal void TrapNextObject(int newObjectKey) + { + trapCount++; + netCache.SetKeyedObject(newObjectKey, null); // use null as a temp + } + + internal void CheckFullyConsumed() + { + if (isFixedLength) + { + if (dataRemaining64 != 0) throw new ProtoException("Incorrect number of bytes consumed"); + } + else + { + if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input"); + } + } + + /// + /// Merge two objects using the details from the current reader; this is used to change the type + /// of objects when an inheritance relationship is discovered later than usual during deserilazation. + /// + public static object Merge(ProtoReader parent, object from, object to) + { + if (parent == null) throw new ArgumentNullException("parent"); + TypeModel model = parent.Model; + SerializationContext ctx = parent.Context; + if (model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified"); + using (var ms = new MemoryStream()) + { + model.Serialize(ms, from, ctx); + ms.Position = 0; + return model.Deserialize(ms, to, null); + } + } + + #region RECYCLER + + internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len) + => Create(source, model, context, (long)len); + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + public static ProtoReader Create(Stream source, TypeModel model, SerializationContext context = null, long length = TO_EOF) + { + ProtoReader reader = GetRecycled(); + if (reader == null) + { +#pragma warning disable CS0618 + return new ProtoReader(source, model, context, length); +#pragma warning restore CS0618 + } + Init(reader, source, model, context, length); + return reader; + } + +#if !PLAT_NO_THREADSTATIC + [ThreadStatic] + private static ProtoReader lastReader; + + private static ProtoReader GetRecycled() + { + ProtoReader tmp = lastReader; + lastReader = null; + return tmp; + } + internal static void Recycle(ProtoReader reader) + { + if (reader != null) + { + reader.Dispose(); + lastReader = reader; + } + } +#elif !PLAT_NO_INTERLOCKED + private static object lastReader; + private static ProtoReader GetRecycled() + { + return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null); + } + internal static void Recycle(ProtoReader reader) + { + if(reader != null) + { + reader.Dispose(); + System.Threading.Interlocked.Exchange(ref lastReader, reader); + } + } +#else + private static readonly object recycleLock = new object(); + private static ProtoReader lastReader; + private static ProtoReader GetRecycled() + { + lock(recycleLock) + { + ProtoReader tmp = lastReader; + lastReader = null; + return tmp; + } + } + internal static void Recycle(ProtoReader reader) + { + if(reader != null) + { + reader.Dispose(); + lock(recycleLock) + { + lastReader = reader; + } + } + } +#endif + + #endregion + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs.meta new file mode 100644 index 0000000..437aa0a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9becd50ddd1084d47896bebfa2393b80 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs new file mode 100644 index 0000000..23fa42d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs @@ -0,0 +1,1003 @@ +using System; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// Represents an output stream for writing protobuf data. + /// + /// Why is the API backwards (static methods with writer arguments)? + /// See: http://marcgravell.blogspot.com/2010/03/last-will-be-first-and-first-will-be.html + /// + public sealed class ProtoWriter : IDisposable + { + private Stream dest; + TypeModel model; + /// + /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type). + /// + /// The object to write. + /// The key that uniquely identifies the type within the model. + /// The destination. + public static void WriteObject(object value, int key, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + + SubItemToken token = StartSubItem(value, writer); + if (key >= 0) + { + writer.model.Serialize(key, value, writer); + } + else if (writer.model != null && writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + // all ok + } + else + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + + EndSubItem(token, writer); + } + /// + /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type) - but the + /// caller is asserting that this relationship is non-recursive; no recursion check will be + /// performed. + /// + /// The object to write. + /// The key that uniquely identifies the type within the model. + /// The destination. + public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + SubItemToken token = StartSubItem(null, writer); + writer.model.Serialize(key, value, writer); + EndSubItem(token, writer); + } + + internal static void WriteObject(object value, int key, ProtoWriter writer, PrefixStyle style, int fieldNumber) + { + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + if (writer.wireType != WireType.None) throw ProtoWriter.CreateException(writer); + + switch (style) + { + case PrefixStyle.Base128: + writer.wireType = WireType.String; + writer.fieldNumber = fieldNumber; + if (fieldNumber > 0) WriteHeaderCore(fieldNumber, WireType.String, writer); + break; + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + writer.fieldNumber = 0; + writer.wireType = WireType.Fixed32; + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + SubItemToken token = StartSubItem(value, writer, true); + if (key < 0) + { + if (!writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + } + else + { + writer.model.Serialize(key, value, writer); + } + EndSubItem(token, writer, style); + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + private readonly NetObjectCache netCache = new NetObjectCache(); + internal NetObjectCache NetCache => netCache; + + private int fieldNumber, flushLock; + WireType wireType; + internal WireType WireType { get { return wireType; } } + /// + /// Writes a field-header, indicating the format of the next data we plan to write. + /// + public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.None) throw new InvalidOperationException("Cannot write a " + wireType.ToString() + + " header until the " + writer.wireType.ToString() + " data has been written"); + if (fieldNumber < 0) throw new ArgumentOutOfRangeException("fieldNumber"); +#if DEBUG + switch (wireType) + { // validate requested header-type + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.String: + case WireType.StartGroup: + case WireType.SignedVariant: + case WireType.Variant: + break; // fine + case WireType.None: + case WireType.EndGroup: + default: + throw new ArgumentException("Invalid wire-type: " + wireType.ToString(), "wireType"); + } +#endif + if (writer.packedFieldNumber == 0) + { + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + WriteHeaderCore(fieldNumber, wireType, writer); + } + else if (writer.packedFieldNumber == fieldNumber) + { // we'll set things up, but note we *don't* actually write the header here + switch (wireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.Variant: + case WireType.SignedVariant: + break; // fine + default: + throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType.ToString()); + } + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + } + else + { + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString()); + } + } + internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) + { + uint header = (((uint)fieldNumber) << 3) + | (((uint)wireType) & 7); + WriteUInt32Variant(header, writer); + } + + /// + /// Writes a byte-array to the stream; supported wire-types: String + /// + public static void WriteBytes(byte[] data, ProtoWriter writer) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + ProtoWriter.WriteBytes(data, 0, data.Length, writer); + } + /// + /// Writes a byte-array to the stream; supported wire-types: String + /// + public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed32: + if (length != 4) throw new ArgumentException(nameof(length)); + goto CopyFixedLength; // ugly but effective + case WireType.Fixed64: + if (length != 8) throw new ArgumentException(nameof(length)); + goto CopyFixedLength; // ugly but effective + case WireType.String: + WriteUInt32Variant((uint)length, writer); + writer.wireType = WireType.None; + if (length == 0) return; + if (writer.flushLock != 0 || length <= writer.ioBuffer.Length) // write to the buffer + { + goto CopyFixedLength; // ugly but effective + } + // writing data that is bigger than the buffer (and the buffer + // isn't currently locked due to a sub-object needing the size backfilled) + Flush(writer); // commit any existing data from the buffer + // now just write directly to the underlying stream + writer.dest.Write(data, offset, length); + writer.position64 += length; // since we've flushed offset etc is 0, and remains + // zero since we're writing directly to the stream + return; + } + throw CreateException(writer); + CopyFixedLength: // no point duplicating this lots of times, and don't really want another stackframe + DemandSpace(length, writer); + Buffer.BlockCopy(data, offset, writer.ioBuffer, writer.ioIndex, length); + IncrementedAndReset(length, writer); + } + private static void CopyRawFromStream(Stream source, ProtoWriter writer) + { + byte[] buffer = writer.ioBuffer; + int space = buffer.Length - writer.ioIndex, bytesRead = 1; // 1 here to spoof case where already full + + // try filling the buffer first + while (space > 0 && (bytesRead = source.Read(buffer, writer.ioIndex, space)) > 0) + { + writer.ioIndex += bytesRead; + writer.position64 += bytesRead; + space -= bytesRead; + } + if (bytesRead <= 0) return; // all done using just the buffer; stream exhausted + + // at this point the stream still has data, but buffer is full; + if (writer.flushLock == 0) + { + // flush the buffer and write to the underlying stream instead + Flush(writer); + while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + writer.dest.Write(buffer, 0, bytesRead); + writer.position64 += bytesRead; + } + } + else + { + do + { + // need more space; resize (double) as necessary, + // requesting a reasonable minimum chunk each time + // (128 is the minimum; there may actually be much + // more space than this in the buffer) + DemandSpace(128, writer); + if ((bytesRead = source.Read(writer.ioBuffer, writer.ioIndex, + writer.ioBuffer.Length - writer.ioIndex)) <= 0) break; + writer.position64 += bytesRead; + writer.ioIndex += bytesRead; + } while (true); + } + + } + private static void IncrementedAndReset(int length, ProtoWriter writer) + { + Helpers.DebugAssert(length >= 0); + writer.ioIndex += length; + writer.position64 += length; + writer.wireType = WireType.None; + } + int depth = 0; + const int RecursionCheckDepth = 25; + /// + /// Indicates the start of a nested record. + /// + /// The instance to write. + /// The destination. + /// A token representing the state of the stream; this token is given to EndSubItem. + public static SubItemToken StartSubItem(object instance, ProtoWriter writer) + { + return StartSubItem(instance, writer, false); + } + + MutableList recursionStack; + private void CheckRecursionStackAndPush(object instance) + { + int hitLevel; + if (recursionStack == null) { recursionStack = new MutableList(); } + else if (instance != null && (hitLevel = recursionStack.IndexOfReference(instance)) >= 0) + { +#if DEBUG + Helpers.DebugWriteLine("Stack:"); + foreach (object obj in recursionStack) + { + Helpers.DebugWriteLine(obj == null ? "" : obj.ToString()); + } + Helpers.DebugWriteLine(instance == null ? "" : instance.ToString()); +#endif + throw new ProtoException("Possible recursion detected (offset: " + (recursionStack.Count - hitLevel).ToString() + " level(s)): " + instance.ToString()); + } + recursionStack.Add(instance); + } + private void PopRecursionStack() { recursionStack.RemoveLast(); } + + private static SubItemToken StartSubItem(object instance, ProtoWriter writer, bool allowFixed) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (++writer.depth > RecursionCheckDepth) + { + writer.CheckRecursionStackAndPush(instance); + } + if (writer.packedFieldNumber != 0) throw new InvalidOperationException("Cannot begin a sub-item while performing packed encoding"); + switch (writer.wireType) + { + case WireType.StartGroup: + writer.wireType = WireType.None; + return new SubItemToken((long)(-writer.fieldNumber)); + case WireType.String: +#if DEBUG + if (writer.model != null && writer.model.ForwardsOnly) + { + throw new ProtoException("Should not be buffering data: " + instance ?? "(null)"); + } +#endif + writer.wireType = WireType.None; + DemandSpace(32, writer); // make some space in anticipation... + writer.flushLock++; + writer.position64++; + return new SubItemToken((long)(writer.ioIndex++)); // leave 1 space (optimistic) for length + case WireType.Fixed32: + { + if (!allowFixed) throw CreateException(writer); + DemandSpace(32, writer); // make some space in anticipation... + writer.flushLock++; + SubItemToken token = new SubItemToken((long)writer.ioIndex); + ProtoWriter.IncrementedAndReset(4, writer); // leave 4 space (rigid) for length + return token; + } + default: + throw CreateException(writer); + } + } + + /// + /// Indicates the end of a nested record. + /// + /// The token obtained from StartubItem. + /// The destination. + public static void EndSubItem(SubItemToken token, ProtoWriter writer) + { + EndSubItem(token, writer, PrefixStyle.Base128); + } + private static void EndSubItem(SubItemToken token, ProtoWriter writer, PrefixStyle style) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.None) { throw CreateException(writer); } + int value = (int)token.value64; + if (writer.depth <= 0) throw CreateException(writer); + if (writer.depth-- > RecursionCheckDepth) + { + writer.PopRecursionStack(); + } + writer.packedFieldNumber = 0; // ending the sub-item always wipes packed encoding + if (value < 0) + { // group - very simple append + WriteHeaderCore(-value, WireType.EndGroup, writer); + writer.wireType = WireType.None; + return; + } + + // so we're backfilling the length into an existing sequence + int len; + switch (style) + { + case PrefixStyle.Fixed32: + len = (int)((writer.ioIndex - value) - 4); + ProtoWriter.WriteInt32ToBuffer(len, writer.ioBuffer, value); + break; + case PrefixStyle.Fixed32BigEndian: + len = (int)((writer.ioIndex - value) - 4); + byte[] buffer = writer.ioBuffer; + ProtoWriter.WriteInt32ToBuffer(len, buffer, value); + // and swap the byte order + byte b = buffer[value]; + buffer[value] = buffer[value + 3]; + buffer[value + 3] = b; + b = buffer[value + 1]; + buffer[value + 1] = buffer[value + 2]; + buffer[value + 2] = b; + break; + case PrefixStyle.Base128: + // string - complicated because we only reserved one byte; + // if the prefix turns out to need more than this then + // we need to shuffle the existing data + len = (int)((writer.ioIndex - value) - 1); + int offset = 0; + uint tmp = (uint)len; + while ((tmp >>= 7) != 0) offset++; + if (offset == 0) + { + writer.ioBuffer[value] = (byte)(len & 0x7F); + } + else + { + DemandSpace(offset, writer); + byte[] blob = writer.ioBuffer; + Buffer.BlockCopy(blob, value + 1, blob, value + 1 + offset, len); + tmp = (uint)len; + do + { + blob[value++] = (byte)((tmp & 0x7F) | 0x80); + } while ((tmp >>= 7) != 0); + blob[value - 1] = (byte)(blob[value - 1] & ~0x80); + writer.position64 += offset; + writer.ioIndex += offset; + } + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + // and this object is no longer a blockage - also flush if sensible + const int ADVISORY_FLUSH_SIZE = 1024; + if (--writer.flushLock == 0 && writer.ioIndex >= ADVISORY_FLUSH_SIZE) + { + ProtoWriter.Flush(writer); + } + + } + + /// + /// Creates a new writer against a stream + /// + /// The destination stream + /// The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects + /// Additional context about this serialization operation + public static ProtoWriter Create(Stream dest, TypeModel model, SerializationContext context = null) +#pragma warning disable CS0618 + => new ProtoWriter(dest, model, context); +#pragma warning restore CS0618 + + /// + /// Creates a new writer against a stream + /// + /// The destination stream + /// The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects + /// Additional context about this serialization operation + [Obsolete("Please use ProtoWriter.Create; this API may be removed in a future version", error: false)] + public ProtoWriter(Stream dest, TypeModel model, SerializationContext context) + { + if (dest == null) throw new ArgumentNullException("dest"); + if (!dest.CanWrite) throw new ArgumentException("Cannot write to stream", "dest"); + //if (model == null) throw new ArgumentNullException("model"); + this.dest = dest; + this.ioBuffer = BufferPool.GetBuffer(); + this.model = model; + this.wireType = WireType.None; + if (context == null) { context = SerializationContext.Default; } + else { context.Freeze(); } + this.context = context; + + } + + private readonly SerializationContext context; + /// + /// Addition information about this serialization operation. + /// + public SerializationContext Context => context; + + void IDisposable.Dispose() + { + Dispose(); + } + + private void Dispose() + { // importantly, this does **not** own the stream, and does not dispose it + if (dest != null) + { + Flush(this); + dest = null; + } + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + } + + private byte[] ioBuffer; + private int ioIndex; + // note that this is used by some of the unit tests and should not be removed + internal static long GetLongPosition(ProtoWriter writer) { return writer.position64; } + internal static int GetPosition(ProtoWriter writer) { return checked((int)writer.position64); } + private long position64; + private static void DemandSpace(int required, ProtoWriter writer) + { + // check for enough space + if ((writer.ioBuffer.Length - writer.ioIndex) < required) + { + TryFlushOrResize(required, writer); + } + } + + private static void TryFlushOrResize(int required, ProtoWriter writer) + { + if (writer.flushLock == 0) + { + Flush(writer); // try emptying the buffer + if ((writer.ioBuffer.Length - writer.ioIndex) >= required) return; + } + + // either can't empty the buffer, or that didn't help; need more space + BufferPool.ResizeAndFlushLeft(ref writer.ioBuffer, required + writer.ioIndex, 0, writer.ioIndex); + } + + /// + /// Flushes data to the underlying stream, and releases any resources. The underlying stream is *not* disposed + /// by this operation. + /// + public void Close() + { + if (depth != 0 || flushLock != 0) throw new InvalidOperationException("Unable to close stream in an incomplete state"); + Dispose(); + } + + internal void CheckDepthFlushlock() + { + if (depth != 0 || flushLock != 0) throw new InvalidOperationException("The writer is in an incomplete state"); + } + + /// + /// Get the TypeModel associated with this writer + /// + public TypeModel Model => model; + + /// + /// Writes any buffered data (if possible) to the underlying stream. + /// + /// The writer to flush + /// It is not always possible to fully flush, since some sequences + /// may require values to be back-filled into the byte-stream. + internal static void Flush(ProtoWriter writer) + { + if (writer.flushLock == 0 && writer.ioIndex != 0) + { + writer.dest.Write(writer.ioBuffer, 0, writer.ioIndex); + writer.ioIndex = 0; + } + } + + /// + /// Writes an unsigned 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + private static void WriteUInt32Variant(uint value, ProtoWriter writer) + { + DemandSpace(5, writer); + int count = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + count++; + } while ((value >>= 7) != 0); + writer.ioBuffer[writer.ioIndex - 1] &= 0x7F; + writer.position64 += count; + } + +#if COREFX + static readonly Encoding encoding = Encoding.UTF8; +#else + static readonly UTF8Encoding encoding = new UTF8Encoding(); +#endif + + internal static uint Zig(int value) + { + return (uint)((value << 1) ^ (value >> 31)); + } + + internal static ulong Zig(long value) + { + return (ulong)((value << 1) ^ (value >> 63)); + } + + private static void WriteUInt64Variant(ulong value, ProtoWriter writer) + { + DemandSpace(10, writer); + int count = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + count++; + } while ((value >>= 7) != 0); + writer.ioBuffer[writer.ioIndex - 1] &= 0x7F; + writer.position64 += count; + } + + /// + /// Writes a string to the stream; supported wire-types: String + /// + public static void WriteString(string value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.String) throw CreateException(writer); + if (value == null) throw new ArgumentNullException("value"); // written header; now what? + int len = value.Length; + if (len == 0) + { + WriteUInt32Variant(0, writer); + writer.wireType = WireType.None; + return; // just a header + } + int predicted = encoding.GetByteCount(value); + WriteUInt32Variant((uint)predicted, writer); + DemandSpace(predicted, writer); + int actual = encoding.GetBytes(value, 0, value.Length, writer.ioBuffer, writer.ioIndex); + Helpers.DebugAssert(predicted == actual); + IncrementedAndReset(actual, writer); + } + + /// + /// Writes an unsigned 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt64(ulong value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed64: + ProtoWriter.WriteInt64((long)value, writer); + return; + case WireType.Variant: + WriteUInt64Variant(value, writer); + writer.wireType = WireType.None; + return; + case WireType.Fixed32: + checked { ProtoWriter.WriteUInt32((uint)value, writer); } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a signed 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt64(long value, ProtoWriter writer) + { + byte[] buffer; + int index; + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed64: + DemandSpace(8, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + +#if NETCOREAPP2_1 + System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian(buffer.AsSpan(index, 8), value); +#else + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); + buffer[index + 4] = (byte)(value >> 32); + buffer[index + 5] = (byte)(value >> 40); + buffer[index + 6] = (byte)(value >> 48); + buffer[index + 7] = (byte)(value >> 56); +#endif + IncrementedAndReset(8, writer); + return; + case WireType.SignedVariant: + WriteUInt64Variant(Zig(value), writer); + writer.wireType = WireType.None; + return; + case WireType.Variant: + if (value >= 0) + { + WriteUInt64Variant((ulong)value, writer); + writer.wireType = WireType.None; + } + else + { + DemandSpace(10, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)(value | 0x80); + buffer[index + 1] = (byte)((int)(value >> 7) | 0x80); + buffer[index + 2] = (byte)((int)(value >> 14) | 0x80); + buffer[index + 3] = (byte)((int)(value >> 21) | 0x80); + buffer[index + 4] = (byte)((int)(value >> 28) | 0x80); + buffer[index + 5] = (byte)((int)(value >> 35) | 0x80); + buffer[index + 6] = (byte)((int)(value >> 42) | 0x80); + buffer[index + 7] = (byte)((int)(value >> 49) | 0x80); + buffer[index + 8] = (byte)((int)(value >> 56) | 0x80); + buffer[index + 9] = 0x01; // sign bit + IncrementedAndReset(10, writer); + } + return; + case WireType.Fixed32: + checked { WriteInt32((int)value, writer); } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt32(uint value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: + ProtoWriter.WriteInt32((int)value, writer); + return; + case WireType.Fixed64: + ProtoWriter.WriteInt64((int)value, writer); + return; + case WireType.Variant: + WriteUInt32Variant(value, writer); + writer.wireType = WireType.None; + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a signed 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt16(short value, ProtoWriter writer) + { + ProtoWriter.WriteInt32(value, writer); + } + + /// + /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt16(ushort value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value, writer); + } + + /// + /// Writes an unsigned 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteByte(byte value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value, writer); + } + /// + /// Writes a signed 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteSByte(sbyte value, ProtoWriter writer) + { + ProtoWriter.WriteInt32(value, writer); + } + + private static void WriteInt32ToBuffer(int value, byte[] buffer, int index) + { +#if NETCOREAPP2_1 + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(index, 4), value); +#else + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); +#endif + } + + /// + /// Writes a signed 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt32(int value, ProtoWriter writer) + { + byte[] buffer; + int index; + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed32: + DemandSpace(4, writer); + WriteInt32ToBuffer(value, writer.ioBuffer, writer.ioIndex); + IncrementedAndReset(4, writer); + return; + case WireType.Fixed64: + DemandSpace(8, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); + buffer[index + 4] = buffer[index + 5] = + buffer[index + 6] = buffer[index + 7] = 0; + IncrementedAndReset(8, writer); + return; + case WireType.SignedVariant: + WriteUInt32Variant(Zig(value), writer); + writer.wireType = WireType.None; + return; + case WireType.Variant: + if (value >= 0) + { + WriteUInt32Variant((uint)value, writer); + writer.wireType = WireType.None; + } + else + { + DemandSpace(10, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)(value | 0x80); + buffer[index + 1] = (byte)((value >> 7) | 0x80); + buffer[index + 2] = (byte)((value >> 14) | 0x80); + buffer[index + 3] = (byte)((value >> 21) | 0x80); + buffer[index + 4] = (byte)((value >> 28) | 0x80); + buffer[index + 5] = buffer[index + 6] = + buffer[index + 7] = buffer[index + 8] = (byte)0xFF; + buffer[index + 9] = (byte)0x01; + IncrementedAndReset(10, writer); + } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a double-precision number to the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + + static void WriteDouble(double value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: + float f = (float)value; + if (float.IsInfinity(f) && !double.IsInfinity(value)) + { + throw new OverflowException(); + } + ProtoWriter.WriteSingle(f, writer); + return; + case WireType.Fixed64: +#if FEAT_SAFE + ProtoWriter.WriteInt64(BitConverter.ToInt64(BitConverter.GetBytes(value), 0), writer); +#else + ProtoWriter.WriteInt64(*(long*)&value, writer); +#endif + return; + default: + throw CreateException(writer); + } + } + /// + /// Writes a single-precision number to the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + static void WriteSingle(float value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: +#if FEAT_SAFE + ProtoWriter.WriteInt32(BitConverter.ToInt32(BitConverter.GetBytes(value), 0), writer); +#else + ProtoWriter.WriteInt32(*(int*)&value, writer); +#endif + return; + case WireType.Fixed64: + ProtoWriter.WriteDouble((double)value, writer); + return; + default: + throw CreateException(writer); + } + } + + /// + /// Throws an exception indicating that the given enum cannot be mapped to a serialized value. + /// + public static void ThrowEnumException(ProtoWriter writer, object enumValue) + { + if (writer == null) throw new ArgumentNullException("writer"); + string rhs = enumValue == null ? "" : (enumValue.GetType().FullName + "." + enumValue.ToString()); + throw new ProtoException("No wire-value is mapped to the enum " + rhs + " at position " + writer.position64.ToString()); + } + + // general purpose serialization exception message + internal static Exception CreateException(ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + return new ProtoException("Invalid serialization operation with wire-type " + writer.wireType.ToString() + " at position " + writer.position64.ToString()); + } + + /// + /// Writes a boolean to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteBoolean(bool value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value ? (uint)1 : (uint)0, writer); + } + + /// + /// Copies any extension data stored for the instance to the underlying stream + /// + public static void AppendExtensionData(IExtensible instance, ProtoWriter writer) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + // we expect the writer to be raw here; the extension data will have the + // header detail, so we'll copy it implicitly + if (writer.wireType != WireType.None) throw CreateException(writer); + + IExtension extn = instance.GetExtensionObject(false); + if (extn != null) + { + // unusually we *don't* want "using" here; the "finally" does that, with + // the extension object being responsible for disposal etc + Stream source = extn.BeginQuery(); + try + { + CopyRawFromStream(source, writer); + } + finally { extn.EndQuery(source); } + } + } + + private int packedFieldNumber; + /// + /// Used for packed encoding; indicates that the next field should be skipped rather than + /// a field header written. Note that the field number must match, else an exception is thrown + /// when the attempt is made to write the (incorrect) field. The wire-type is taken from the + /// subsequent call to WriteFieldHeader. Only primitive types can be packed. + /// + public static void SetPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.packedFieldNumber = fieldNumber; + } + + /// + /// Used for packed encoding; explicitly reset the packed field marker; this is not required + /// if using StartSubItem/EndSubItem + /// + public static void ClearPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber != writer.packedFieldNumber) + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString()); + writer.packedFieldNumber = 0; + } + + /// + /// Used for packed encoding; writes the length prefix using fixed sizes rather than using + /// buffering. Only valid for fixed-32 and fixed-64 encoding. + /// + public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer) + { + if (writer.WireType != WireType.String) throw new InvalidOperationException("Invalid wire-type: " + writer.WireType); + if (elementCount < 0) throw new ArgumentOutOfRangeException(nameof(elementCount)); + ulong bytes; + switch (wireType) + { + // use long in case very large arrays are enabled + case WireType.Fixed32: bytes = ((ulong)elementCount) << 2; break; // x4 + case WireType.Fixed64: bytes = ((ulong)elementCount) << 3; break; // x8 + default: + throw new ArgumentOutOfRangeException(nameof(wireType), "Invalid wire-type: " + wireType); + } + WriteUInt64Variant(bytes, writer); + writer.wireType = WireType.None; + } + + internal string SerializeType(Type type) + { + return TypeModel.SerializeType(model, type); + } + + /// + /// Specifies a known root object to use during reference-tracked serialization + /// + public void SetRootObject(object value) + { + NetCache.SetKeyedObject(NetObjectCache.Root, value); + } + + /// + /// Writes a Type to the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String + /// + public static void WriteType(Type value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + WriteString(writer.SerializeType(value), writer); + } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs.meta new file mode 100644 index 0000000..9ed7489 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ProtoWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a197fcaa5f6e524d821688bc3ca173b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs new file mode 100644 index 0000000..80b76af --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs @@ -0,0 +1,76 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Additional information about a serialization operation + /// + public sealed class SerializationContext + { + private bool frozen; + internal void Freeze() { frozen = true; } + private void ThrowIfFrozen() { if (frozen) throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); } + private object context; + /// + /// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation. + /// + public object Context + { + get { return context; } + set { if (context != value) { ThrowIfFrozen(); context = value; } } + } + + private static readonly SerializationContext @default; + + static SerializationContext() + { + @default = new SerializationContext(); + @default.Freeze(); + } + /// + /// A default SerializationContext, with minimal information. + /// + internal static SerializationContext Default => @default; +#if PLAT_BINARYFORMATTER + +#if !(COREFX || PROFILE259) + private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence; + /// + /// Gets or sets the source or destination of the transmitted data. + /// + public System.Runtime.Serialization.StreamingContextStates State + { + get { return state; } + set { if (state != value) { ThrowIfFrozen(); state = value; } } + } +#endif + /// + /// Convert a SerializationContext to a StreamingContext + /// + public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx) + { +#if COREFX + return new System.Runtime.Serialization.StreamingContext(); +#else + if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence); + return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context); +#endif + } + /// + /// Convert a StreamingContext to a SerializationContext + /// + public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx) + { + SerializationContext result = new SerializationContext(); + +#if !(COREFX || PROFILE259) + result.Context = ctx.Context; + result.State = ctx.State; +#endif + + return result; + } +#endif + } + +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs.meta new file mode 100644 index 0000000..2457cc2 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/SerializationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb7f2dd67f481174db9ae6683acfec2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs new file mode 100644 index 0000000..8a4c38a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs @@ -0,0 +1,514 @@ +using ProtoBuf.Meta; +using System; +using System.IO; +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf +{ + /// + /// Provides protocol-buffer serialization capability for concrete, attributed types. This + /// is a *default* model, but custom serializer models are also supported. + /// + /// + /// Protocol-buffer serialization is a compact binary format, designed to take + /// advantage of sparse data and knowledge of specific data types; it is also + /// extensible, allowing a type to be deserialized / merged even if some data is + /// not recognised. + /// + public static class Serializer + { +#if !NO_RUNTIME + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for + /// The .proto definition as a string + public static string GetProto() => GetProto(ProtoSyntax.Proto2); + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for + /// The .proto definition as a string + public static string GetProto(ProtoSyntax syntax) + { + return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax); + } + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public static T DeepClone(T instance) + { + return instance == null ? instance : (T)RuntimeTypeModel.Default.DeepClone(instance); + } + + /// + /// Applies a protocol-buffer stream to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static T Merge(Stream source, T instance) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T)); + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static T Deserialize(Stream source) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, null, typeof(T)); + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public static void Serialize(Stream destination, T instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(destination, instance); + } + } + + /// + /// Serializes a given instance and deserializes it as a different type; + /// this can be used to translate between wire-compatible objects (where + /// two .NET types represent the same data), or to promote/demote a type + /// through an inheritance hierarchy. + /// + /// No assumption of compatibility is made between the types. + /// The type of the object being copied. + /// The type of the new object to be created. + /// The existing instance to use as a template. + /// A new instane of type TNewType, with the data from TOldType. + public static TTo ChangeType(TFrom instance) + { + using (var ms = new MemoryStream()) + { + Serialize(ms, instance); + ms.Position = 0; + return Deserialize(ms); + } + } +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination SerializationInfo to write to. + public static void Serialize(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + Serialize(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance); + } + /// + /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination SerializationInfo to write to. + /// Additional information about this serialization operation. + public static void Serialize(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization) + if (info == null) throw new ArgumentNullException("info"); + if (instance == null) throw new ArgumentNullException("instance"); + if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance"); + using (MemoryStream ms = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(ms, instance, context); + info.AddValue(ProtoBinaryField, ms.ToArray()); + } + } +#endif +#if PLAT_XMLSERIALIZER + /// + /// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination XmlWriter to write to. + public static void Serialize(System.Xml.XmlWriter writer, T instance) where T : System.Xml.Serialization.IXmlSerializable + { + if (writer == null) throw new ArgumentNullException("writer"); + if (instance == null) throw new ArgumentNullException("instance"); + + using (MemoryStream ms = new MemoryStream()) + { + Serializer.Serialize(ms, instance); + writer.WriteBase64(Helpers.GetBuffer(ms), 0, (int)ms.Length); + } + } + /// + /// Applies a protocol-buffer from an XmlReader to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The XmlReader containing the data to apply to the instance (cannot be null). + public static void Merge(System.Xml.XmlReader reader, T instance) where T : System.Xml.Serialization.IXmlSerializable + { + if (reader == null) throw new ArgumentNullException("reader"); + if (instance == null) throw new ArgumentNullException("instance"); + + const int LEN = 4096; + byte[] buffer = new byte[LEN]; + int read; + using (MemoryStream ms = new MemoryStream()) + { + int depth = reader.Depth; + while(reader.Read() && reader.Depth > depth) + { + if (reader.NodeType == System.Xml.XmlNodeType.Text) + { + while ((read = reader.ReadContentAsBase64(buffer, 0, LEN)) > 0) + { + ms.Write(buffer, 0, read); + } + if (reader.Depth <= depth) break; + } + } + ms.Position = 0; + Serializer.Merge(ms, instance); + } + } +#endif + + private const string ProtoBinaryField = "proto"; +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Applies a protocol-buffer from a SerializationInfo to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The SerializationInfo containing the data to apply to the instance (cannot be null). + public static void Merge(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + Merge(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance); + } + /// + /// Applies a protocol-buffer from a SerializationInfo to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The SerializationInfo containing the data to apply to the instance (cannot be null). + /// Additional information about this serialization operation. + public static void Merge(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization) + if (info == null) throw new ArgumentNullException("info"); + if (instance == null) throw new ArgumentNullException("instance"); + if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance"); + + byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[])); + using (MemoryStream ms = new MemoryStream(buffer)) + { + T result = (T)RuntimeTypeModel.Default.Deserialize(ms, instance, typeof(T), context); + if (!ReferenceEquals(result, instance)) + { + throw new ProtoException("Deserialization changed the instance; cannot succeed."); + } + } + } +#endif + + /// + /// Precompiles the serializer for a given type. + /// + public static void PrepareSerializer() + { + NonGeneric.PrepareSerializer(typeof(T)); + } + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Creates a new IFormatter that uses protocol-buffer [de]serialization. + /// + /// The type of object to be [de]deserialized by the formatter. + /// A new IFormatter to be used during [de]serialization. + public static System.Runtime.Serialization.IFormatter CreateFormatter() + { + return RuntimeTypeModel.Default.CreateFormatter(typeof(T)); + } +#endif + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignored for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + public static IEnumerable DeserializeItems(Stream source, PrefixStyle style, int fieldNumber) + { + return RuntimeTypeModel.Default.DeserializeItems(source, style, fieldNumber); + } + + /// + /// Creates a new instance from a protocol-buffer stream that has a length-prefix + /// on data (to assist with network IO). + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// How to encode the length prefix. + /// A new, initialized instance. + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style) + { + return DeserializeWithLengthPrefix(source, style, 0); + } + + /// + /// Creates a new instance from a protocol-buffer stream that has a length-prefix + /// on data (to assist with network IO). + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// How to encode the length prefix. + /// The expected tag of the item (only used with base-128 prefix style). + /// A new, initialized instance. + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + return (T)model.DeserializeWithLengthPrefix(source, null, model.MapType(typeof(T)), style, fieldNumber); + } + + /// + /// Applies a protocol-buffer stream to an existing instance, using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static T MergeWithLengthPrefix(Stream source, T instance, PrefixStyle style) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + return (T)model.DeserializeWithLengthPrefix(source, instance, model.MapType(typeof(T)), style, 0); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style) + { + SerializeWithLengthPrefix(destination, instance, style, 0); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + model.SerializeWithLengthPrefix(destination, instance, model.MapType(typeof(T)), style, fieldNumber); + } + + /// Indicates the number of bytes expected for the next message. + /// The stream containing the data to investigate for a length. + /// The algorithm used to encode the length. + /// The length of the message, if it could be identified. + /// True if a length could be obtained, false otherwise. + public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length) + { + length = ProtoReader.ReadLengthPrefix(source, false, style, out int fieldNumber, out int bytesRead); + return bytesRead > 0; + } + + /// Indicates the number of bytes expected for the next message. + /// The buffer containing the data to investigate for a length. + /// The offset of the first byte to read from the buffer. + /// The number of bytes to read from the buffer. + /// The algorithm used to encode the length. + /// The length of the message, if it could be identified. + /// True if a length could be obtained, false otherwise. + public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length) + { + using (Stream source = new MemoryStream(buffer, index, count)) + { + return TryReadLengthPrefix(source, style, out length); + } + } +#endif + /// + /// The field number that is used as a default when serializing/deserializing a list of objects. + /// The data is treated as repeated message with field number 1. + /// + public const int ListItemTag = 1; + + +#if !NO_RUNTIME + /// + /// Provides non-generic access to the default serializer. + /// + public static class NonGeneric + { + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public static object DeepClone(object instance) + { + return instance == null ? null : RuntimeTypeModel.Default.DeepClone(instance); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public static void Serialize(Stream dest, object instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(dest, instance); + } + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + /// Applies a protocol-buffer stream to an existing instance. + /// The existing instance to be modified (cannot be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance + public static object Merge(Stream source, object instance) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + RuntimeTypeModel model = RuntimeTypeModel.Default; + model.SerializeWithLengthPrefix(destination, instance, model.MapType(instance.GetType()), style, fieldNumber); + } + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// Used to resolve types on a per-field basis. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value) + { + value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver); + return value != null; + } + + /// + /// Indicates whether the supplied type is explicitly modelled by the model + /// + public static bool CanSerialize(Type type) => RuntimeTypeModel.Default.IsDefined(type); + + /// + /// Precompiles the serializer for a given type. + /// + public static void PrepareSerializer(Type t) + { +#if FEAT_COMPILER + RuntimeTypeModel model = RuntimeTypeModel.Default; + model[model.MapType(t)].CompileInPlace(); +#endif + } + } + + /// + /// Global switches that change the behavior of protobuf-net + /// + public static class GlobalOptions + { + /// + /// + /// + [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)] + public static bool InferTagFromName + { + get { return RuntimeTypeModel.Default.InferTagFromNameDefault; } + set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; } + } + } +#endif + /// + /// Maps a field-number to a type + /// + public delegate Type TypeResolver(int fieldNumber); + + /// + /// Releases any internal buffers that have been reserved for efficiency; this does not affect any serialization + /// operations; simply: it can be used (optionally) to release the buffers for garbage collection (at the expense + /// of having to re-allocate a new buffer for the next operation, rather than re-use prior buffers). + /// + public static void FlushPool() + { + BufferPool.Flush(); + } + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs.meta new file mode 100644 index 0000000..3a40e98 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 847a51cf99c2f594cbd7644dd86dd110 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers.meta new file mode 100644 index 0000000..e8653cc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9f9b7f4d169ceba41a6ae039604082ab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs new file mode 100644 index 0000000..cad005f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs @@ -0,0 +1,310 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class ArrayDecorator : ProtoDecoratorBase + { + private readonly int fieldNumber; + private const byte + OPTIONS_WritePacked = 1, + OPTIONS_OverwriteList = 2, + OPTIONS_SupportNull = 4; + private readonly byte options; + private readonly WireType packedWireType; + public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) + : base(tail) + { + Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); + Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); + this.itemType = arrayType.GetElementType(); + Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType); + + Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType + || (Tail.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)), "invalid tail"); + Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer"); + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); + if (!ListDecorator.CanPack(packedWireType)) + { + if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); + packedWireType = WireType.None; + } + this.fieldNumber = fieldNumber; + this.packedWireType = packedWireType; + if (writePacked) options |= OPTIONS_WritePacked; + if (overwriteList) options |= OPTIONS_OverwriteList; + if (supportNull) options |= OPTIONS_SupportNull; + this.arrayType = arrayType; + } + readonly Type arrayType, itemType; // this is, for example, typeof(int[]) + public override Type ExpectedType { get { return arrayType; } } + public override bool RequiresOldValue { get { return AppendToCollection; } } + public override bool ReturnsValue { get { return true; } } + private bool CanUsePackedPrefix() => CanUsePackedPrefix(packedWireType, itemType); + + internal static bool CanUsePackedPrefix(WireType packedWireType, Type itemType) + { + // needs to be a suitably simple type *and* be definitely not nullable + switch (packedWireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + break; + default: + return false; // nope + } + if (!Helpers.IsValueType(itemType)) return false; + return Helpers.GetUnderlyingType(itemType) == null; + } + +#if FEAT_COMPILER + protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + // int i and T[] arr + using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom)) + using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + bool writePacked = (options & OPTIONS_WritePacked) != 0; + bool fixedLengthPacked = writePacked && CanUsePackedPrefix(); + + using (Compiler.Local token = (writePacked && !fixedLengthPacked) ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null) + { + Type mappedWriter = ctx.MapType(typeof(ProtoWriter)); + if (writePacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)WireType.String); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("WriteFieldHeader")); + + if (fixedLengthPacked) + { + // write directly - no need for buffering + ctx.LoadLength(arr, false); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("WritePackedPrefix")); + } + else + { + ctx.LoadValue(arr); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("StartSubItem")); + ctx.StoreValue(token); + } + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("SetPackedField")); + } + EmitWriteArrayLoop(ctx, i, arr); + + if (writePacked) + { + if (fixedLengthPacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("ClearPackedField")); + } + else + { + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("EndSubItem")); + } + } + } + } + } + + private void EmitWriteArrayLoop(Compiler.CompilerContext ctx, Compiler.Local i, Compiler.Local arr) + { + // i = 0 + ctx.LoadValue(0); + ctx.StoreValue(i); + + // range test is last (to minimise branches) + Compiler.CodeLabel loopTest = ctx.DefineLabel(), processItem = ctx.DefineLabel(); + ctx.Branch(loopTest, false); + ctx.MarkLabel(processItem); + + // {...} + ctx.LoadArrayValue(arr, i); + if (SupportNull) + { + Tail.EmitWrite(ctx, null); + } + else + { + ctx.WriteNullCheckedTail(itemType, Tail, null); + } + + // i++ + ctx.LoadValue(i); + ctx.LoadValue(1); + ctx.Add(); + ctx.StoreValue(i); + + // i < arr.Length + ctx.MarkLabel(loopTest); + ctx.LoadValue(i); + ctx.LoadLength(arr, false); + ctx.BranchIfLess(processItem, false); + } +#endif + private bool AppendToCollection => (options & OPTIONS_OverwriteList) == 0; + + private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } } + + public override void Write(object value, ProtoWriter dest) + { + IList arr = (IList)value; + int len = arr.Count; + SubItemToken token; + bool writePacked = (options & OPTIONS_WritePacked) != 0; + bool fixedLengthPacked = writePacked && CanUsePackedPrefix(); + + if (writePacked) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + + if (fixedLengthPacked) + { + ProtoWriter.WritePackedPrefix(arr.Count, packedWireType, dest); + token = new SubItemToken(); // default + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = new SubItemToken(); // default + } + bool checkForNull = !SupportNull; + for (int i = 0; i < len; i++) + { + object obj = arr[i]; + if (checkForNull && obj == null) { throw new NullReferenceException(); } + Tail.Write(obj, dest); + } + if (writePacked) + { + if (fixedLengthPacked) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + public override object Read(object value, ProtoReader source) + { + int field = source.FieldNumber; + BasicList list = new BasicList(); + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + list.Add(Tail.Read(null, source)); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + list.Add(Tail.Read(null, source)); + } while (source.TryReadFieldHeader(field)); + } + int oldLen = AppendToCollection ? ((value == null ? 0 : ((Array)value).Length)) : 0; + Array result = Array.CreateInstance(itemType, oldLen + list.Count); + if (oldLen != 0) ((Array)value).CopyTo(result, 0); + list.CopyTo(result, oldLen); + return result; + } + +#if FEAT_COMPILER + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + Type listType; + listType = ctx.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + Type expected = ExpectedType; + using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(expected, valueFrom) : null) + using (Compiler.Local newArr = new Compiler.Local(ctx, expected)) + using (Compiler.Local list = new Compiler.Local(ctx, listType)) + { + ctx.EmitCtor(listType); + ctx.StoreValue(list); + ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false); + + // leave this "using" here, as it can share the "FieldNumber" local with EmitReadList + using (Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null) + { + Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) }; + + if (AppendToCollection) + { + ctx.LoadLength(oldArr, true); + ctx.CopyValue(); + ctx.StoreValue(oldLen); + + ctx.LoadAddress(list, listType); + ctx.LoadValue(listType.GetProperty("Count")); + ctx.Add(); + ctx.CreateArray(itemType, null); // length is on the stack + ctx.StoreValue(newArr); + + ctx.LoadValue(oldLen); + Compiler.CodeLabel nothingToCopy = ctx.DefineLabel(); + ctx.BranchIfFalse(nothingToCopy, true); + ctx.LoadValue(oldArr); + ctx.LoadValue(newArr); + ctx.LoadValue(0); // index in target + + ctx.EmitCall(expected.GetMethod("CopyTo", copyToArrayInt32Args)); + ctx.MarkLabel(nothingToCopy); + + ctx.LoadValue(list); + ctx.LoadValue(newArr); + ctx.LoadValue(oldLen); + + } + else + { + ctx.LoadAddress(list, listType); + ctx.LoadValue(listType.GetProperty("Count")); + ctx.CreateArray(itemType, null); + ctx.StoreValue(newArr); + + ctx.LoadAddress(list, listType); + ctx.LoadValue(newArr); + ctx.LoadValue(0); + } + + copyToArrayInt32Args[0] = expected; // // prefer: CopyTo(T[], int) + MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args); + if (copyTo == null) + { // fallback: CopyTo(Array, int) + copyToArrayInt32Args[1] = ctx.MapType(typeof(Array)); + copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args); + } + ctx.EmitCall(copyTo); + } + ctx.LoadValue(newArr); + } + + + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta new file mode 100644 index 0000000..bf330ac --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 994c27d30c8e3834c93fc6fa8c397236 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs new file mode 100644 index 0000000..40b2b89 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs @@ -0,0 +1,59 @@ +#if !NO_RUNTIME +using System; +#if COREFX +using System.Reflection; +#endif +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class BlobSerializer : IProtoSerializer + { + public Type ExpectedType { get { return expectedType; } } + + static readonly Type expectedType = typeof(byte[]); + + public BlobSerializer(ProtoBuf.Meta.TypeModel model, bool overwriteList) + { + this.overwriteList = overwriteList; + } + + private readonly bool overwriteList; + + public object Read(object value, ProtoReader source) + { + return ProtoReader.AppendBytes(overwriteList ? null : (byte[])value, source); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBytes((byte[])value, dest); + } + + bool IProtoSerializer.RequiresOldValue { get { return !overwriteList; } } + bool IProtoSerializer.ReturnsValue { get { return true; } } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteBytes", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (overwriteList) + { + ctx.LoadNullRef(); + } + else + { + ctx.LoadValue(valueFrom); + } + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)) + .GetMethod("AppendBytes")); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta new file mode 100644 index 0000000..bfa0ebc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 257d977cc298d2348a1ef8a60a63b616 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs new file mode 100644 index 0000000..c64886a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class BooleanSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(bool); + + public BooleanSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBoolean((bool)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadBoolean(); + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteBoolean", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadBoolean", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta new file mode 100644 index 0000000..3aaaa6d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 16fce0ba1c3bd344eb1f3f2f9e185baf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs new file mode 100644 index 0000000..e44a83c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class ByteSerializer : IProtoSerializer + { + public Type ExpectedType { get { return expectedType; } } + + static readonly Type expectedType = typeof(byte); + + public ByteSerializer(ProtoBuf.Meta.TypeModel model) { } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteByte((byte)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadByte(); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteByte", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadByte", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta new file mode 100644 index 0000000..af743b8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba8e31868ee3815409ab37e8286499ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs new file mode 100644 index 0000000..3bc30d0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs @@ -0,0 +1,32 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class CharSerializer : UInt16Serializer + { + static readonly Type expectedType = typeof(char); + + public CharSerializer(ProtoBuf.Meta.TypeModel model) : base(model) + { + + } + + public override Type ExpectedType => expectedType; + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((ushort)(char)value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return (char)source.ReadUInt16(); + } + + // no need for any special IL here; ushort and char are + // interchangeable as long as there is no boxing/unboxing + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta new file mode 100644 index 0000000..7d9e11f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81a1e1f6bc039db4e8f3aae9cf69ce2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs new file mode 100644 index 0000000..1ec3027 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs @@ -0,0 +1,88 @@ +#if FEAT_COMPILER +using System; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class CompiledSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return head.HasCallbacks(callbackType); // these routes only used when bits of the model not compiled + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return head.CanCreateInstance(); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return head.CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + head.Callback(value, callbackType, context); // these routes only used when bits of the model not compiled + } + + public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model) + { + CompiledSerializer result = head as CompiledSerializer; + if (result == null) + { + result = new CompiledSerializer(head, model); + Helpers.DebugAssert(((IProtoTypeSerializer)result).ExpectedType == head.ExpectedType); + } + return result; + } + + private readonly IProtoTypeSerializer head; + private readonly Compiler.ProtoSerializer serializer; + private readonly Compiler.ProtoDeserializer deserializer; + + private CompiledSerializer(IProtoTypeSerializer head, TypeModel model) + { + this.head = head; + serializer = Compiler.CompilerContext.BuildSerializer(head, model); + deserializer = Compiler.CompilerContext.BuildDeserializer(head, model); + } + + bool IProtoSerializer.RequiresOldValue => head.RequiresOldValue; + + bool IProtoSerializer.ReturnsValue => head.ReturnsValue; + + Type IProtoSerializer.ExpectedType => head.ExpectedType; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + serializer(value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return deserializer(value, source); + } + + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + head.EmitWrite(ctx, valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + head.EmitRead(ctx, valueFrom); + } + + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + head.EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + head.EmitCreateInstance(ctx); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta new file mode 100644 index 0000000..bbfe65d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca54a7c7f8fb570418c85a9842de69c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs new file mode 100644 index 0000000..9755df9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs @@ -0,0 +1,65 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + internal sealed class DateTimeSerializer : IProtoSerializer + { + private static readonly Type expectedType = typeof(DateTime); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + bool IProtoSerializer.ReturnsValue => true; + + private readonly bool includeKind, wellKnown; + + public DateTimeSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model) + { + wellKnown = dataFormat == DataFormat.WellKnown; + includeKind = model?.SerializeDateTimeKind() == true; + } + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadTimestamp(source); + } + else + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadDateTime(source); + } + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + BclHelpers.WriteTimestamp((DateTime)value, dest); + else if (includeKind) + BclHelpers.WriteDateTimeWithKind((DateTime)value, dest); + else + BclHelpers.WriteDateTime((DateTime)value, dest); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.WriteTimestamp) + : includeKind ? nameof(BclHelpers.WriteDateTimeWithKind) : nameof(BclHelpers.WriteDateTime), valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity) + { + if (wellKnown) ctx.LoadValue(entity); + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.ReadTimestamp) : nameof(BclHelpers.ReadDateTime), + ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta new file mode 100644 index 0000000..994226d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3a68578cab4cef840b4d27a6e3bd486d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs new file mode 100644 index 0000000..1edc621 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class DecimalSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(decimal); + + public DecimalSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadDecimal(source); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteDecimal((decimal)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDecimal", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDecimal", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta new file mode 100644 index 0000000..e0102a6 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 975c221ef9e845249841bf18b3f6fd08 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs new file mode 100644 index 0000000..895d0c4 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs @@ -0,0 +1,259 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class DefaultValueDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly object defaultValue; + public DefaultValueDecorator(TypeModel model, object defaultValue, IProtoSerializer tail) : base(tail) + { + if (defaultValue == null) throw new ArgumentNullException(nameof(defaultValue)); + Type type = model.MapType(defaultValue.GetType()); + if (type != tail.ExpectedType) + { + throw new ArgumentException("Default value is of incorrect type", "defaultValue"); + } + this.defaultValue = defaultValue; + } + + public override void Write(object value, ProtoWriter dest) + { + if (!object.Equals(value, defaultValue)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + return Tail.Read(value, source); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Compiler.CodeLabel done = ctx.DefineLabel(); + if (valueFrom == null) + { + ctx.CopyValue(); // on the stack + Compiler.CodeLabel needToPop = ctx.DefineLabel(); + EmitBranchIfDefaultValue(ctx, needToPop); + Tail.EmitWrite(ctx, null); + ctx.Branch(done, true); + ctx.MarkLabel(needToPop); + ctx.DiscardValue(); + } + else + { + ctx.LoadValue(valueFrom); // variable/parameter + EmitBranchIfDefaultValue(ctx, done); + Tail.EmitWrite(ctx, valueFrom); + } + ctx.MarkLabel(done); + } + private void EmitBeq(Compiler.CompilerContext ctx, Compiler.CodeLabel label, Type type) + { + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Double: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Single: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + ctx.BranchIfEqual(label, false); + break; + default: +#if COREFX + MethodInfo method = type.GetMethod("op_Equality", new Type[] { type, type }); + if (method == null || !method.IsPublic || !method.IsStatic) method = null; +#else + MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static, + null, new Type[] { type, type }, null); +#endif + if (method == null || method.ReturnType != ctx.MapType(typeof(bool))) + { + throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName); + } + ctx.EmitCall(method); + ctx.BranchIfTrue(label, false); + break; + + } + } + private void EmitBranchIfDefaultValue(Compiler.CompilerContext ctx, Compiler.CodeLabel label) + { + Type expected = ExpectedType; + switch (Helpers.GetTypeCode(expected)) + { + case ProtoTypeCode.Boolean: + if ((bool)defaultValue) + { + ctx.BranchIfTrue(label, false); + } + else + { + ctx.BranchIfFalse(label, false); + } + break; + case ProtoTypeCode.Byte: + if ((byte)defaultValue == (byte)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(byte)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.SByte: + if ((sbyte)defaultValue == (sbyte)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(sbyte)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int16: + if ((short)defaultValue == (short)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(short)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.UInt16: + if ((ushort)defaultValue == (ushort)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(ushort)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int32: + if ((int)defaultValue == (int)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.UInt32: + if ((uint)defaultValue == (uint)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(uint)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Char: + if ((char)defaultValue == (char)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(char)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int64: + ctx.LoadValue((long)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.UInt64: + ctx.LoadValue((long)(ulong)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Double: + ctx.LoadValue((double)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Single: + ctx.LoadValue((float)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.String: + ctx.LoadValue((string)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Decimal: + { + decimal d = (decimal)defaultValue; + ctx.LoadValue(d); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.TimeSpan: + { + TimeSpan ts = (TimeSpan)defaultValue; + if (ts == TimeSpan.Zero) + { + ctx.LoadValue(typeof(TimeSpan).GetField("Zero")); + } + else + { + ctx.LoadValue(ts.Ticks); + ctx.EmitCall(ctx.MapType(typeof(TimeSpan)).GetMethod("FromTicks")); + } + EmitBeq(ctx, label, expected); + break; + } + case ProtoTypeCode.Guid: + { + ctx.LoadValue((Guid)defaultValue); + EmitBeq(ctx, label, expected); + break; + } + case ProtoTypeCode.DateTime: + { + ctx.LoadValue(((DateTime)defaultValue).ToBinary()); + ctx.EmitCall(ctx.MapType(typeof(DateTime)).GetMethod("FromBinary")); + + EmitBeq(ctx, label, expected); + break; + } + default: + throw new NotSupportedException("Type cannot be represented as a default value: " + expected.FullName); + } + } + + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta new file mode 100644 index 0000000..556c450 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ffe4b3b37fd5074da95b623467af560 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs new file mode 100644 index 0000000..8b25523 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class DoubleSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(double); + + public DoubleSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadDouble(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteDouble((double)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteDouble", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadDouble", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta new file mode 100644 index 0000000..d01306d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a729a251d91c68b41bb794eccc700d58 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs new file mode 100644 index 0000000..78cb78a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs @@ -0,0 +1,267 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class EnumSerializer : IProtoSerializer + { + public readonly struct EnumPair + { + public readonly object RawValue; // note that this is boxing, but I'll live with it + public readonly Enum TypedValue; // note that this is boxing, but I'll live with it + public readonly int WireValue; + public EnumPair(int wireValue, object raw, Type type) + { + WireValue = wireValue; + RawValue = raw; + TypedValue = (Enum)Enum.ToObject(type, raw); + } + } + + private readonly Type enumType; + private readonly EnumPair[] map; + public EnumSerializer(Type enumType, EnumPair[] map) + { + this.enumType = enumType ?? throw new ArgumentNullException(nameof(enumType)); + this.map = map; + if (map != null) + { + for (int i = 1; i < map.Length; i++) + for (int j = 0; j < i; j++) + { + if (map[i].WireValue == map[j].WireValue && !Equals(map[i].RawValue, map[j].RawValue)) + { + throw new ProtoException("Multiple enums with wire-value " + map[i].WireValue.ToString()); + } + if (Equals(map[i].RawValue, map[j].RawValue) && map[i].WireValue != map[j].WireValue) + { + throw new ProtoException("Multiple enums with deserialized-value " + map[i].RawValue); + } + } + + } + } + + private ProtoTypeCode GetTypeCode() + { + Type type = Helpers.GetUnderlyingType(enumType); + if (type == null) type = enumType; + return Helpers.GetTypeCode(type); + } + + public Type ExpectedType => enumType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + private int EnumToWire(object value) + { + unchecked + { + switch (GetTypeCode()) + { // unbox then convert to int + case ProtoTypeCode.Byte: return (int)(byte)value; + case ProtoTypeCode.SByte: return (int)(sbyte)value; + case ProtoTypeCode.Int16: return (int)(short)value; + case ProtoTypeCode.Int32: return (int)value; + case ProtoTypeCode.Int64: return (int)(long)value; + case ProtoTypeCode.UInt16: return (int)(ushort)value; + case ProtoTypeCode.UInt32: return (int)(uint)value; + case ProtoTypeCode.UInt64: return (int)(ulong)value; + default: throw new InvalidOperationException(); + } + } + } + + private object WireToEnum(int value) + { + unchecked + { + switch (GetTypeCode()) + { // convert from int then box + case ProtoTypeCode.Byte: return Enum.ToObject(enumType, (byte)value); + case ProtoTypeCode.SByte: return Enum.ToObject(enumType, (sbyte)value); + case ProtoTypeCode.Int16: return Enum.ToObject(enumType, (short)value); + case ProtoTypeCode.Int32: return Enum.ToObject(enumType, value); + case ProtoTypeCode.Int64: return Enum.ToObject(enumType, (long)value); + case ProtoTypeCode.UInt16: return Enum.ToObject(enumType, (ushort)value); + case ProtoTypeCode.UInt32: return Enum.ToObject(enumType, (uint)value); + case ProtoTypeCode.UInt64: return Enum.ToObject(enumType, (ulong)value); + default: throw new InvalidOperationException(); + } + } + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + int wireValue = source.ReadInt32(); + if (map == null) + { + return WireToEnum(wireValue); + } + for (int i = 0; i < map.Length; i++) + { + if (map[i].WireValue == wireValue) + { + return map[i].TypedValue; + } + } + source.ThrowEnumException(ExpectedType, wireValue); + return null; // to make compiler happy + } + + public void Write(object value, ProtoWriter dest) + { + if (map == null) + { + ProtoWriter.WriteInt32(EnumToWire(value), dest); + } + else + { + for (int i = 0; i < map.Length; i++) + { + if (object.Equals(map[i].TypedValue, value)) + { + ProtoWriter.WriteInt32(map[i].WireValue, dest); + return; + } + } + ProtoWriter.ThrowEnumException(dest, value); + } + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.LoadValue(valueFrom); + ctx.ConvertToInt32(typeCode, false); + ctx.EmitBasicWrite("WriteInt32", null); + } + else + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + Compiler.CodeLabel @continue = ctx.DefineLabel(); + for (int i = 0; i < map.Length; i++) + { + Compiler.CodeLabel tryNextValue = ctx.DefineLabel(), processThisValue = ctx.DefineLabel(); + ctx.LoadValue(loc); + WriteEnumValue(ctx, typeCode, map[i].RawValue); + ctx.BranchIfEqual(processThisValue, true); + ctx.Branch(tryNextValue, true); + ctx.MarkLabel(processThisValue); + ctx.LoadValue(map[i].WireValue); + ctx.EmitBasicWrite("WriteInt32", null); + ctx.Branch(@continue, false); + ctx.MarkLabel(tryNextValue); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(loc); + ctx.CastToObject(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(@continue); + } + } + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.ConvertFromInt32(typeCode, false); + } + else + { + int[] wireValues = new int[map.Length]; + object[] values = new object[map.Length]; + for (int i = 0; i < map.Length; i++) + { + wireValues[i] = map[i].WireValue; + values[i] = map[i].RawValue; + } + using (Compiler.Local result = new Compiler.Local(ctx, ExpectedType)) + using (Compiler.Local wireValue = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.StoreValue(wireValue); + Compiler.CodeLabel @continue = ctx.DefineLabel(); + foreach (BasicList.Group group in BasicList.GetContiguousGroups(wireValues, values)) + { + Compiler.CodeLabel tryNextGroup = ctx.DefineLabel(); + int groupItemCount = group.Items.Count; + if (groupItemCount == 1) + { + // discreet group; use an equality test + ctx.LoadValue(wireValue); + ctx.LoadValue(group.First); + Compiler.CodeLabel processThisValue = ctx.DefineLabel(); + ctx.BranchIfEqual(processThisValue, true); + ctx.Branch(tryNextGroup, false); + WriteEnumValue(ctx, typeCode, processThisValue, @continue, group.Items[0], @result); + } + else + { + // implement as a jump-table-based switch + ctx.LoadValue(wireValue); + ctx.LoadValue(group.First); + ctx.Subtract(); // jump-tables are zero-based + Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount]; + for (int i = 0; i < groupItemCount; i++) + { + jmp[i] = ctx.DefineLabel(); + } + ctx.Switch(jmp); + // write the default... + ctx.Branch(tryNextGroup, false); + for (int i = 0; i < groupItemCount; i++) + { + WriteEnumValue(ctx, typeCode, jmp[i], @continue, group.Items[i], @result); + } + } + ctx.MarkLabel(tryNextGroup); + } + // throw source.CreateEnumException(ExpectedType, wireValue); + ctx.LoadReaderWriter(); + ctx.LoadValue(ExpectedType); + ctx.LoadValue(wireValue); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(@continue); + ctx.LoadValue(result); + } + } + } + private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, object value) + { + switch (typeCode) + { + case ProtoTypeCode.Byte: ctx.LoadValue((int)(byte)value); break; + case ProtoTypeCode.SByte: ctx.LoadValue((int)(sbyte)value); break; + case ProtoTypeCode.Int16: ctx.LoadValue((int)(short)value); break; + case ProtoTypeCode.Int32: ctx.LoadValue((int)(int)value); break; + case ProtoTypeCode.Int64: ctx.LoadValue((long)(long)value); break; + case ProtoTypeCode.UInt16: ctx.LoadValue((int)(ushort)value); break; + case ProtoTypeCode.UInt32: ctx.LoadValue((int)(uint)value); break; + case ProtoTypeCode.UInt64: ctx.LoadValue((long)(ulong)value); break; + default: throw new InvalidOperationException(); + } + } + private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, Compiler.CodeLabel handler, Compiler.CodeLabel @continue, object value, Compiler.Local local) + { + ctx.MarkLabel(handler); + WriteEnumValue(ctx, typeCode, value); + ctx.StoreValue(local); + ctx.Branch(@continue, false); // "continue" + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta new file mode 100644 index 0000000..0911d49 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ddfa6ffe6f127a84aa6ddbbf7a64e7e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs new file mode 100644 index 0000000..26c0452 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs @@ -0,0 +1,104 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class FieldDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => forType; + private readonly FieldInfo field; + private readonly Type forType; + public override bool RequiresOldValue => true; + public override bool ReturnsValue => false; + public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(field != null); + this.forType = forType; + this.field = field; + } + + public override void Write(object value, ProtoWriter dest) + { + Helpers.DebugAssert(value != null); + value = field.GetValue(value); + if (value != null) Tail.Write(value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value != null); + object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source); + if (newValue != null) field.SetValue(value, newValue); + return null; + } + + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(field); + ctx.WriteNullCheckedTail(field.FieldType, Tail, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(field); + } + // value is either now on the stack or not needed + ctx.ReadNullCheckedTail(field.FieldType, Tail, null); + + // the field could be a backing field that needs to be raised back to + // the property if we're doing a full compile + MemberInfo member = field; + ctx.CheckAccessibility(ref member); + bool writeValue = member is FieldInfo; + + if (writeValue) + { + if (Tail.ReturnsValue) + { + using (Compiler.Local newVal = new Compiler.Local(ctx, field.FieldType)) + { + ctx.StoreValue(newVal); + if (Helpers.IsValueType(field.FieldType)) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(newVal); + ctx.StoreValue(field); + } + else + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + ctx.LoadValue(newVal); + ctx.BranchIfFalse(allDone, true); // interpret null as "don't assign" + + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(newVal); + ctx.StoreValue(field); + + ctx.MarkLabel(allDone); + } + } + } + } + else + { + // can't use result + if (Tail.ReturnsValue) + { + ctx.DiscardValue(); + } + } + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta new file mode 100644 index 0000000..65c1b0f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cd9b2f54595f3ae41b7de708c2b51bb5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs new file mode 100644 index 0000000..27556d5 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class GuidSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(Guid); + + public GuidSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType { get { return expectedType; } } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteGuid((Guid)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadGuid(source); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteGuid", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadGuid", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta new file mode 100644 index 0000000..52a7a23 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: af13180f23621384294c01c6c85aaa7b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs new file mode 100644 index 0000000..59e8cc2 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs @@ -0,0 +1,64 @@ +#if !NO_RUNTIME +using System; + + +namespace ProtoBuf.Serializers +{ + interface IProtoSerializer + { + /// + /// The type that this serializer is intended to work for. + /// + Type ExpectedType { get; } + + /// + /// Perform the steps necessary to serialize this data. + /// + /// The value to be serialized. + /// The writer entity that is accumulating the output data. + void Write(object value, ProtoWriter dest); + + /// + /// Perform the steps necessary to deserialize this data. + /// + /// The current value, if appropriate. + /// The reader providing the input data. + /// The updated / replacement value. + object Read(object value, ProtoReader source); + + /// + /// Indicates whether a Read operation replaces the existing value, or + /// extends the value. If false, the "value" parameter to Read is + /// discarded, and should be passed in as null. + /// + bool RequiresOldValue { get; } + /// + /// Now all Read operations return a value (although most do); if false no + /// value should be expected. + /// + bool ReturnsValue { get; } + +#if FEAT_COMPILER + /// Emit the IL necessary to perform the given actions + /// to serialize this data. + /// + /// Details and utilities for the method being generated. + /// The source of the data to work against; + /// If the value is only needed once, then LoadValue is sufficient. If + /// the value is needed multiple times, then note that a "null" + /// means "the top of the stack", in which case you should create your + /// own copy - GetLocalWithValue. + void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); + + /// + /// Emit the IL necessary to perform the given actions to deserialize this data. + /// + /// Details and utilities for the method being generated. + /// For nested values, the instance holding the values; note + /// that this is not always provided - a null means not supplied. Since this is always + /// a variable or argument, it is not necessary to consume this value. + void EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity); +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta new file mode 100644 index 0000000..d43b751 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e2e0875940ee9a46a5c89accf9142f1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs new file mode 100644 index 0000000..da1439b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs @@ -0,0 +1,20 @@ +#if !NO_RUNTIME +using ProtoBuf.Meta; +namespace ProtoBuf.Serializers +{ + interface IProtoTypeSerializer : IProtoSerializer + { + bool HasCallbacks(TypeModel.CallbackType callbackType); + bool CanCreateInstance(); + object CreateInstance(ProtoReader source); + void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context); + +#if FEAT_COMPILER + void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType); +#endif +#if FEAT_COMPILER + void EmitCreateInstance(Compiler.CompilerContext ctx); +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta new file mode 100644 index 0000000..790dd35 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa8e86751c5977347a9d4d97de2c3ad8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs new file mode 100644 index 0000000..3ab2cb8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs @@ -0,0 +1,10 @@ +#if !NO_RUNTIME + +namespace ProtoBuf.Serializers +{ + interface ISerializerProxy + { + IProtoSerializer Serializer { get; } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta new file mode 100644 index 0000000..6baf2dd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f2e957070048af34db74b51b5b0b60a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs new file mode 100644 index 0000000..918d1fd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs @@ -0,0 +1,304 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class ImmutableCollectionDecorator : ListDecorator + { + protected override bool RequireAdd { get { return false; } } + + static Type ResolveIReadOnlyCollection(Type declaredType, Type t) + { +#if COREFX || PROFILE259 + if (CheckIsIReadOnlyCollectionExactly(declaredType.GetTypeInfo())) return declaredType; + foreach (Type intImplBasic in declaredType.GetTypeInfo().ImplementedInterfaces) + { + TypeInfo intImpl = intImplBasic.GetTypeInfo(); + if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImplBasic; + } +#else + if (CheckIsIReadOnlyCollectionExactly(declaredType)) return declaredType; + foreach (Type intImpl in declaredType.GetInterfaces()) + { + if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImpl; + } +#endif + return null; + } + +#if WINRT || COREFX || PROFILE259 + static bool CheckIsIReadOnlyCollectionExactly(TypeInfo t) +#else + static bool CheckIsIReadOnlyCollectionExactly(Type t) +#endif + { + if (t != null && t.IsGenericType && t.Name.StartsWith("IReadOnlyCollection`")) + { +#if WINRT || COREFX || PROFILE259 + Type[] typeArgs = t.GenericTypeArguments; + if (typeArgs.Length != 1 && typeArgs[0].GetTypeInfo().Equals(t)) return false; +#else + Type[] typeArgs = t.GetGenericArguments(); + if (typeArgs.Length != 1 && typeArgs[0] != t) return false; +#endif + + return true; + } + return false; + } + + internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out PropertyInfo isEmpty, out PropertyInfo length, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish) + { + builderFactory = add = addRange = finish = null; + isEmpty = length = null; + if (model == null || declaredType == null) return false; +#if COREFX || PROFILE259 + TypeInfo declaredTypeInfo = declaredType.GetTypeInfo(); +#else + Type declaredTypeInfo = declaredType; +#endif + + // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection for some T + if (!declaredTypeInfo.IsGenericType) return false; + +#if COREFX || PROFILE259 + Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType; +#else + Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType; +#endif + switch (typeArgs.Length) + { + case 1: + effectiveType = typeArgs; + break; // fine + case 2: + Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)); + if (kvp == null) return false; + kvp = kvp.MakeGenericType(typeArgs); + effectiveType = new Type[] { kvp }; + break; + default: + return false; // no clue! + } + + if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection found + + // and we want to use the builder API, so for generic Foo or IFoo we want to use Foo.CreateBuilder + string name = declaredType.Name; + int i = name.IndexOf('`'); + if (i <= 0) return false; + name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i); + + Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.Assembly); + // I hate special-cases... + if (outerType == null && name == "ImmutableSet") + { + outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.Assembly); + } + if (outerType == null) return false; + +#if PROFILE259 + foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods) +#else + foreach (MethodInfo method in outerType.GetMethods()) +#endif + { + if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0 + || method.GetGenericArguments().Length != typeArgs.Length) continue; + + builderFactory = method.MakeGenericMethod(typeArgs); + break; + } + Type voidType = model.MapType(typeof(void)); + if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false; + +#if COREFX + TypeInfo typeInfo = declaredType.GetTypeInfo(); +#else + Type typeInfo = declaredType; +#endif + isEmpty = Helpers.GetProperty(typeInfo, "IsDefaultOrEmpty", false); //struct based immutabletypes can have both a "default" and "empty" state + if (isEmpty == null) isEmpty = Helpers.GetProperty(typeInfo, "IsEmpty", false); + if (isEmpty == null) + { + //Fallback to checking length if a "IsEmpty" property is not found + length = Helpers.GetProperty(typeInfo, "Length", false); + if (length == null) length = Helpers.GetProperty(typeInfo, "Count", false); + + if (length == null) length = Helpers.GetProperty(ResolveIReadOnlyCollection(declaredType, effectiveType[0]), "Count", false); + + if (length == null) return false; + } + + add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType); + if (add == null) return false; + + finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes); + if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false; + + if (!(finish.ReturnType == declaredType || Helpers.IsAssignableFrom(declaredType, finish.ReturnType))) return false; + + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType }); + if (addRange == null) + { + Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false); + if (enumerable != null) + { + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) }); + } + } + + return true; + } + + private readonly MethodInfo builderFactory, add, addRange, finish; + private readonly PropertyInfo isEmpty, length; + internal ImmutableCollectionDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull, + MethodInfo builderFactory, PropertyInfo isEmpty, PropertyInfo length, MethodInfo add, MethodInfo addRange, MethodInfo finish) + : base(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull) + { + this.builderFactory = builderFactory; + this.isEmpty = isEmpty; + this.length = length; + this.add = add; + this.addRange = addRange; + this.finish = finish; + } + + public override object Read(object value, ProtoReader source) + { + object builderInstance = builderFactory.Invoke(null, null); + int field = source.FieldNumber; + object[] args = new object[1]; + if (AppendToCollection && value != null && (isEmpty != null ? !(bool)isEmpty.GetValue(value, null) : (int)length.GetValue(value, null) != 0)) + { + if (addRange != null) + { + args[0] = value; + addRange.Invoke(builderInstance, args); + } + else + { + foreach (object item in (ICollection)value) + { + args[0] = item; + add.Invoke(builderInstance, args); + } + } + } + + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + args[0] = Tail.Read(null, source); + add.Invoke(builderInstance, args); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + args[0] = Tail.Read(null, source); + add.Invoke(builderInstance, args); + } while (source.TryReadFieldHeader(field)); + } + + return finish.Invoke(builderInstance, null); + } + +#if FEAT_COMPILER + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local oldList = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null) + using (Compiler.Local builder = new Compiler.Local(ctx, builderFactory.ReturnType)) + { + ctx.EmitCall(builderFactory); + ctx.StoreValue(builder); + + if (AppendToCollection) + { + Compiler.CodeLabel done = ctx.DefineLabel(); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadValue(oldList); + ctx.BranchIfFalse(done, false); // old value null; nothing to add + } + + ctx.LoadAddress(oldList, oldList.Type); + if (isEmpty != null) + { + ctx.EmitCall(Helpers.GetGetMethod(isEmpty, false, false)); + ctx.BranchIfTrue(done, false); // old list is empty; nothing to add + } + else + { + ctx.EmitCall(Helpers.GetGetMethod(length, false, false)); + ctx.BranchIfFalse(done, false); // old list is empty; nothing to add + } + + Type voidType = ctx.MapType(typeof(void)); + if (addRange != null) + { + ctx.LoadValue(builder); + ctx.LoadValue(oldList); + ctx.EmitCall(addRange); + if (addRange.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue(); + } + else + { + // loop and call Add repeatedly + MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(ctx.Model, out moveNext, out current); + Helpers.DebugAssert(moveNext != null); + Helpers.DebugAssert(current != null); + Helpers.DebugAssert(getEnumerator != null); + + Type enumeratorType = getEnumerator.ReturnType; + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + { + ctx.LoadAddress(oldList, ExpectedType); + ctx.EmitCall(getEnumerator); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + ctx.LoadAddress(builder, builder.Type); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current); + ctx.EmitCall(add); + if (add.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue(); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext); + ctx.BranchIfTrue(body, false); + } + } + } + + + ctx.MarkLabel(done); + } + + EmitReadList(ctx, builder, Tail, add, packedWireType, false); + + ctx.LoadAddress(builder, builder.Type); + ctx.EmitCall(finish); + if (ExpectedType != finish.ReturnType) + { + ctx.Cast(ExpectedType); + } + } + } +#endif + } +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta new file mode 100644 index 0000000..f44029c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5bd62f540d53c741af50ce244a1db7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs new file mode 100644 index 0000000..eac4eb4 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int16Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(short); + + public Int16Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt16(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt16((short)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt16", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt16", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta new file mode 100644 index 0000000..1546a71 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18cb1207e9a6f87478049bc93c6c92b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs new file mode 100644 index 0000000..204880e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int32Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(int); + + public Int32Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt32((int)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt32", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt32", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta new file mode 100644 index 0000000..6f7cfc0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5ee133af50c52d4cb9d5be880585c2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs new file mode 100644 index 0000000..2791a1e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int64Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(long); + + public Int64Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt64((long)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt64", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt64", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta new file mode 100644 index 0000000..30b7e69 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e5000d1909e2e741bd16b63fb0f4ecd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs new file mode 100644 index 0000000..82bb128 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs @@ -0,0 +1,579 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + class ListDecorator : ProtoDecoratorBase + { + internal static bool CanPack(WireType wireType) + { + switch (wireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.SignedVariant: + case WireType.Variant: + return true; + default: + return false; + } + } + + private readonly byte options; + + private const byte OPTIONS_IsList = 1, + OPTIONS_SuppressIList = 2, + OPTIONS_WritePacked = 4, + OPTIONS_ReturnList = 8, + OPTIONS_OverwriteList = 16, + OPTIONS_SupportNull = 32; + + private readonly Type declaredType, concreteType; + + private readonly MethodInfo add; + + private readonly int fieldNumber; + + private bool IsList { get { return (options & OPTIONS_IsList) != 0; } } + private bool SuppressIList { get { return (options & OPTIONS_SuppressIList) != 0; } } + private bool WritePacked { get { return (options & OPTIONS_WritePacked) != 0; } } + private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } } + private bool ReturnList { get { return (options & OPTIONS_ReturnList) != 0; } } + protected readonly WireType packedWireType; + + internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + { + if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType, + out MethodInfo builderFactory, + out PropertyInfo isEmpty, + out PropertyInfo length, + out MethodInfo add, + out MethodInfo addRange, + out MethodInfo finish)) + { + return new ImmutableCollectionDecorator( + model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull, + builderFactory, isEmpty, length, add, addRange, finish); + } + + return new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull); + } + + protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + : base(tail) + { + if (returnList) options |= OPTIONS_ReturnList; + if (overwriteList) options |= OPTIONS_OverwriteList; + if (supportNull) options |= OPTIONS_SupportNull; + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); + if (!CanPack(packedWireType)) + { + if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); + packedWireType = WireType.None; + } + + this.fieldNumber = fieldNumber; + if (writePacked) options |= OPTIONS_WritePacked; + this.packedWireType = packedWireType; + if (declaredType == null) throw new ArgumentNullException("declaredType"); + if (declaredType.IsArray) throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); + this.declaredType = declaredType; + this.concreteType = concreteType; + + // look for a public list.Add(typedObject) method + if (RequireAdd) + { + bool isList; + add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out isList); + if (isList) + { + options |= OPTIONS_IsList; + string fullName = declaredType.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[[")) + { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned + options |= OPTIONS_SuppressIList; + } + } + if (add == null) throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName); + } + + } + protected virtual bool RequireAdd => true; + + public override Type ExpectedType => declaredType; + + public override bool RequiresOldValue => AppendToCollection; + + public override bool ReturnsValue => ReturnList; + + protected bool AppendToCollection + { + get { return (options & OPTIONS_OverwriteList) == 0; } + } + +#if FEAT_COMPILER + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + /* This looks more complex than it is. Look at the non-compiled Read to + * see what it is trying to do, but note that it needs to cope with a + * few more scenarios. Note that it picks the **most specific** Add, + * unlike the runtime version that uses IList when possible. The core + * is just a "do {list.Add(readValue())} while {thereIsMore}" + * + * The complexity is due to: + * - value types vs reference types (boxing etc) + * - initialization if we need to pass in a value to the tail + * - handling whether or not the tail *returns* the value vs updates the input + */ + bool returnList = ReturnList; + + using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Compiler.Local(ctx, declaredType)) + using (Compiler.Local origlist = (returnList && AppendToCollection && !Helpers.IsValueType(ExpectedType)) ? new Compiler.Local(ctx, ExpectedType) : null) + { + if (!AppendToCollection) + { // always new + ctx.LoadNullRef(); + ctx.StoreValue(list); + } + else if (returnList && origlist != null) + { // need a copy + ctx.LoadValue(list); + ctx.StoreValue(origlist); + } + if (concreteType != null) + { + ctx.LoadValue(list); + Compiler.CodeLabel notNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(list); + ctx.MarkLabel(notNull); + } + + bool castListForAdd = !add.DeclaringType.IsAssignableFrom(declaredType); + EmitReadList(ctx, list, Tail, add, packedWireType, castListForAdd); + + if (returnList) + { + if (AppendToCollection && origlist != null) + { + // remember ^^^^ we had a spare copy of the list on the stack; now we'll compare + ctx.LoadValue(origlist); + ctx.LoadValue(list); // [orig] [new-value] + Compiler.CodeLabel sameList = ctx.DefineLabel(), allDone = ctx.DefineLabel(); + ctx.BranchIfEqual(sameList, true); + ctx.LoadValue(list); + ctx.Branch(allDone, true); + ctx.MarkLabel(sameList); + ctx.LoadNullRef(); + ctx.MarkLabel(allDone); + } + else + { + ctx.LoadValue(list); + } + } + } + } + + internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType, bool castListForAdd) + { + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel(); + if (packedWireType != WireType.None) + { + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType")); + ctx.LoadValue((int)WireType.String); + ctx.BranchIfEqual(readPacked, false); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber")); + ctx.StoreValue(fieldNumber); + + Compiler.CodeLabel @continue = ctx.DefineLabel(); + ctx.MarkLabel(@continue); + + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + + ctx.LoadReaderWriter(); + ctx.LoadValue(fieldNumber); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(@continue, false); + + if (packedWireType != WireType.None) + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + ctx.Branch(allDone, false); + ctx.MarkLabel(readPacked); + + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + + Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel(); + ctx.MarkLabel(testForData); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("HasSubValue")); + ctx.BranchIfFalse(noMoreData, false); + + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + ctx.Branch(testForData, false); + + ctx.MarkLabel(noMoreData); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.MarkLabel(allDone); + } + } + } + + private static void EmitReadAndAddItem(Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, bool castListForAdd) + { + ctx.LoadAddress(list, list.Type); // needs to be the reference in case the list is value-type (static-call) + if (castListForAdd) ctx.Cast(add.DeclaringType); + + Type itemType = tail.ExpectedType; + bool tailReturnsValue = tail.ReturnsValue; + if (tail.RequiresOldValue) + { + if (Helpers.IsValueType(itemType) || !tailReturnsValue) + { + // going to need a variable + using (Compiler.Local item = new Compiler.Local(ctx, itemType)) + { + if (Helpers.IsValueType(itemType)) + { // initialise the struct + ctx.LoadAddress(item, itemType); + ctx.EmitCtor(itemType); + } + else + { // assign null + ctx.LoadNullRef(); + ctx.StoreValue(item); + } + tail.EmitRead(ctx, item); + if (!tailReturnsValue) { ctx.LoadValue(item); } + } + } + else + { // no variable; pass the null on the stack and take the value *off* the stack + ctx.LoadNullRef(); + tail.EmitRead(ctx, null); + } + } + else + { + if (tailReturnsValue) + { // out only (on the stack); just emit it + tail.EmitRead(ctx, null); + } + else + { // doesn't take anything in nor return anything! WTF? + throw new InvalidOperationException(); + } + } + // our "Add" is chosen either to take the correct type, or to take "object"; + // we may need to box the value + + Type addParamType = add.GetParameters()[0].ParameterType; + if (addParamType != itemType) + { + if (addParamType == ctx.MapType(typeof(object))) + { + ctx.CastToObject(itemType); + } + else if (Helpers.GetUnderlyingType(addParamType) == itemType) + { // list is nullable + ConstructorInfo ctor = Helpers.GetConstructor(addParamType, new Type[] { itemType }, false); + ctx.EmitCtor(ctor); // the itemType on the stack is now a Nullable + } + else + { + throw new InvalidOperationException("Conflicting item/add type"); + } + } + ctx.EmitCall(add, list.Type); + if (add.ReturnType != ctx.MapType(typeof(void))) + { + ctx.DiscardValue(); + } + } +#endif + +#if COREFX + private static readonly TypeInfo ienumeratorType = typeof(IEnumerator).GetTypeInfo(), ienumerableType = typeof (IEnumerable).GetTypeInfo(); +#else + private static readonly System.Type ienumeratorType = typeof(IEnumerator), ienumerableType = typeof(IEnumerable); +#endif + protected MethodInfo GetEnumeratorInfo(TypeModel model, out MethodInfo moveNext, out MethodInfo current) + => GetEnumeratorInfo(model, ExpectedType, Tail.ExpectedType, out moveNext, out current); + internal static MethodInfo GetEnumeratorInfo(TypeModel model, Type expectedType, Type itemType, out MethodInfo moveNext, out MethodInfo current) + { + +#if COREFX + TypeInfo enumeratorType = null, iteratorType; +#else + Type enumeratorType = null, iteratorType; +#endif + + // try a custom enumerator + MethodInfo getEnumerator = Helpers.GetInstanceMethod(expectedType, "GetEnumerator", null); + + Type getReturnType = null; + if (getEnumerator != null) + { + getReturnType = getEnumerator.ReturnType; + iteratorType = getReturnType +#if COREFX || COREFX + .GetTypeInfo() +#endif + ; + moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext", null); + PropertyInfo prop = Helpers.GetProperty(iteratorType, "Current", false); + current = prop == null ? null : Helpers.GetGetMethod(prop, false, false); +#if PROFILE259 + if (moveNext == null && (model.MapType(ienumeratorType).GetTypeInfo().IsAssignableFrom(iteratorType.GetTypeInfo()))) +#else + if (moveNext == null && (model.MapType(ienumeratorType).IsAssignableFrom(iteratorType))) +#endif + { + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext", null); + } + // fully typed + if (moveNext != null && moveNext.ReturnType == model.MapType(typeof(bool)) + && current != null && current.ReturnType == itemType) + { + return getEnumerator; + } + moveNext = current = getEnumerator = null; + } + + // try IEnumerable + Type tmp = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false); + + if (tmp != null) + { + tmp = tmp.MakeGenericType(itemType); + +#if COREFX + enumeratorType = tmp.GetTypeInfo(); +#else + enumeratorType = tmp; +#endif + } +; +#if PROFILE259 + if (enumeratorType != null && enumeratorType.GetTypeInfo().IsAssignableFrom(expectedType +#else + if (enumeratorType != null && enumeratorType.IsAssignableFrom(expectedType +#endif +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + )) + { + getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator"); + getReturnType = getEnumerator.ReturnType; + +#if COREFX + iteratorType = getReturnType.GetTypeInfo(); +#else + iteratorType = getReturnType; +#endif + + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false); + return getEnumerator; + } + // give up and fall-back to non-generic IEnumerable + enumeratorType = model.MapType(ienumerableType); + getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator"); + getReturnType = getEnumerator.ReturnType; + iteratorType = getReturnType +#if COREFX + .GetTypeInfo() +#endif + ; + moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false); + return getEnumerator; + } +#if FEAT_COMPILER + protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + MethodInfo getEnumerator = GetEnumeratorInfo(ctx.Model, out MethodInfo moveNext, out MethodInfo current); + Helpers.DebugAssert(moveNext != null); + Helpers.DebugAssert(current != null); + Helpers.DebugAssert(getEnumerator != null); + Type enumeratorType = getEnumerator.ReturnType; + bool writePacked = WritePacked; + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null) + { + if (writePacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)WireType.String); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + + ctx.LoadValue(list); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("SetPackedField")); + } + + ctx.LoadAddress(list, ExpectedType); + ctx.EmitCall(getEnumerator, ExpectedType); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current, enumeratorType); + Type itemType = Tail.ExpectedType; + if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(itemType); + } + Tail.EmitWrite(ctx, null); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext, enumeratorType); + ctx.BranchIfTrue(body, false); + } + + if (writePacked) + { + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + } + } + } +#endif + + public override void Write(object value, ProtoWriter dest) + { + SubItemToken token; + bool writePacked = WritePacked; + bool fixedSizePacked = writePacked & CanUsePackedPrefix(value) && value is ICollection; + if (writePacked) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + if (fixedSizePacked) + { + ProtoWriter.WritePackedPrefix(((ICollection)value).Count, packedWireType, dest); + token = default(SubItemToken); + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = new SubItemToken(); // default + } + bool checkForNull = !SupportNull; + foreach (object subItem in (IEnumerable)value) + { + if (checkForNull && subItem == null) { throw new NullReferenceException(); } + Tail.Write(subItem, dest); + } + if (writePacked) + { + if (fixedSizePacked) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + + private bool CanUsePackedPrefix(object obj) => + ArrayDecorator.CanUsePackedPrefix(packedWireType, Tail.ExpectedType); + + public override object Read(object value, ProtoReader source) + { + try + { + int field = source.FieldNumber; + object origValue = value; + if (value == null) value = Activator.CreateInstance(concreteType); + bool isList = IsList && !SuppressIList; + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + if (isList) + { + IList list = (IList)value; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + list.Add(Tail.Read(null, source)); + } + } + else + { + object[] args = new object[1]; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + args[0] = Tail.Read(null, source); + add.Invoke(value, args); + } + } + ProtoReader.EndSubItem(token, source); + } + else + { + if (isList) + { + IList list = (IList)value; + do + { + list.Add(Tail.Read(null, source)); + } while (source.TryReadFieldHeader(field)); + } + else + { + object[] args = new object[1]; + do + { + args[0] = Tail.Read(null, source); + add.Invoke(value, args); + } while (source.TryReadFieldHeader(field)); + } + } + return origValue == value ? null : value; + } + catch (TargetInvocationException tie) + { + if (tie.InnerException != null) throw tie.InnerException; + throw; + } + } + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta new file mode 100644 index 0000000..1ca61f9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a66b11582d7aa2b468fd02eeb85dffa4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs new file mode 100644 index 0000000..033cf26 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs @@ -0,0 +1,298 @@ +using ProtoBuf.Meta; +using System; +#if FEAT_COMPILER +using ProtoBuf.Compiler; +#endif +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + class MapDecorator : ProtoDecoratorBase where TDictionary : class, IDictionary + { + private readonly Type concreteType; + private readonly IProtoSerializer keyTail; + private readonly int fieldNumber; + private readonly WireType wireType; + + internal MapDecorator(TypeModel model, Type concreteType, IProtoSerializer keyTail, IProtoSerializer valueTail, + int fieldNumber, WireType wireType, WireType keyWireType, WireType valueWireType, bool overwriteList) + : base(DefaultValue == null + ? (IProtoSerializer)new TagDecorator(2, valueWireType, false, valueTail) + : (IProtoSerializer)new DefaultValueDecorator(model, DefaultValue, new TagDecorator(2, valueWireType, false, valueTail))) + { + this.wireType = wireType; + this.keyTail = new DefaultValueDecorator(model, DefaultKey, new TagDecorator(1, keyWireType, false, keyTail)); + this.fieldNumber = fieldNumber; + this.concreteType = concreteType ?? typeof(TDictionary); + + if (keyTail.RequiresOldValue) throw new InvalidOperationException("Key tail should not require the old value"); + if (!keyTail.ReturnsValue) throw new InvalidOperationException("Key tail should return a value"); + if (!valueTail.ReturnsValue) throw new InvalidOperationException("Value tail should return a value"); + + AppendToCollection = !overwriteList; + } + + private static readonly MethodInfo indexerSet = GetIndexerSetter(); + + private static MethodInfo GetIndexerSetter() + { +#if PROFILE259 + foreach(var prop in typeof(TDictionary).GetRuntimeProperties()) +#else + foreach (var prop in typeof(TDictionary).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) +#endif + { + if (prop.Name != "Item") continue; + if (prop.PropertyType != typeof(TValue)) continue; + + var args = prop.GetIndexParameters(); + if (args == null || args.Length != 1) continue; + + if (args[0].ParameterType != typeof(TKey)) continue; +#if PROFILE259 + var method = prop.SetMethod; +#else + var method = prop.GetSetMethod(true); +#endif + if (method != null) + { + return method; + } + } + throw new InvalidOperationException("Unable to resolve indexer for map"); + } + + private static readonly TKey DefaultKey = (typeof(TKey) == typeof(string)) ? (TKey)(object)"" : default(TKey); + private static readonly TValue DefaultValue = (typeof(TValue) == typeof(string)) ? (TValue)(object)"" : default(TValue); + public override Type ExpectedType => typeof(TDictionary); + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => AppendToCollection; + + private bool AppendToCollection { get; } + + public override object Read(object untyped, ProtoReader source) + { + TDictionary typed = AppendToCollection ? ((TDictionary)untyped) : null; + if (typed == null) typed = (TDictionary)Activator.CreateInstance(concreteType); + + do + { + var key = DefaultKey; + var value = DefaultValue; + SubItemToken token = ProtoReader.StartSubItem(source); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + switch (field) + { + case 1: + key = (TKey)keyTail.Read(null, source); + break; + case 2: + value = (TValue)Tail.Read(Tail.RequiresOldValue ? (object)value : null, source); + break; + default: + source.SkipField(); + break; + } + } + + ProtoReader.EndSubItem(token, source); + typed[key] = value; + } while (source.TryReadFieldHeader(fieldNumber)); + + return typed; + } + + public override void Write(object untyped, ProtoWriter dest) + { + foreach (var pair in (TDictionary)untyped) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + var token = ProtoWriter.StartSubItem(null, dest); + if (pair.Key != null) keyTail.Write(pair.Key, dest); + if (pair.Value != null) Tail.Write(pair.Value, dest); + ProtoWriter.EndSubItem(token, dest); + } + } + +#if FEAT_COMPILER + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + Type itemType = typeof(KeyValuePair); + MethodInfo moveNext, current, getEnumerator = ListDecorator.GetEnumeratorInfo(ctx.Model, + ExpectedType, itemType, out moveNext, out current); + Type enumeratorType = getEnumerator.ReturnType; + + MethodInfo key = itemType.GetProperty(nameof(KeyValuePair.Key)).GetGetMethod(), + @value = itemType.GetProperty(nameof(KeyValuePair.Value)).GetGetMethod(); + + using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) + using (Compiler.Local kvp = new Compiler.Local(ctx, itemType)) + { + ctx.LoadAddress(list, ExpectedType); + ctx.EmitCall(getEnumerator, ExpectedType); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current, enumeratorType); + + if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(itemType); + } + ctx.StoreValue(kvp); + + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + ctx.LoadAddress(kvp, itemType); + ctx.EmitCall(key, itemType); + ctx.WriteNullCheckedTail(typeof(TKey), keyTail, null); + + ctx.LoadAddress(kvp, itemType); + ctx.EmitCall(value, itemType); + ctx.WriteNullCheckedTail(typeof(TValue), Tail, null); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext, enumeratorType); + ctx.BranchIfTrue(body, false); + } + } + } + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) + : new Compiler.Local(ctx, typeof(TDictionary))) + using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) + using (Compiler.Local key = new Compiler.Local(ctx, typeof(TKey))) + using (Compiler.Local @value = new Compiler.Local(ctx, typeof(TValue))) + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + if (!AppendToCollection) + { // always new + ctx.LoadNullRef(); + ctx.StoreValue(list); + } + if (concreteType != null) + { + ctx.LoadValue(list); + Compiler.CodeLabel notNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(list); + ctx.MarkLabel(notNull); + } + + var redoFromStart = ctx.DefineLabel(); + ctx.MarkLabel(redoFromStart); + + // key = default(TKey); value = default(TValue); + if (typeof(TKey) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(key); + } + else + { + ctx.InitLocal(typeof(TKey), key); + } + if (typeof(TValue) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(value); + } + else + { + ctx.InitLocal(typeof(TValue), @value); + } + + // token = ProtoReader.StartSubItem(reader); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel(); + // while ... + ctx.Branch(@continue, false); + + // switch(fieldNumber) + ctx.MarkLabel(processField); + ctx.LoadValue(fieldNumber); + CodeLabel @default = ctx.DefineLabel(), one = ctx.DefineLabel(), two = ctx.DefineLabel(); + ctx.Switch(new[] { @default, one, two }); // zero based, hence explicit 0 + + // case 0: default: reader.SkipField(); + ctx.MarkLabel(@default); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(@continue, false); + + // case 1: key = ... + ctx.MarkLabel(one); + keyTail.EmitRead(ctx, null); + ctx.StoreValue(key); + ctx.Branch(@continue, false); + + // case 2: value = ... + ctx.MarkLabel(two); + Tail.EmitRead(ctx, Tail.RequiresOldValue ? @value : null); + ctx.StoreValue(value); + + // (fieldNumber = reader.ReadFieldHeader()) > 0 + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + + // ProtoReader.EndSubItem(token, reader); + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + + // list[key] = value; + ctx.LoadAddress(list, ExpectedType); + ctx.LoadValue(key); + ctx.LoadValue(@value); + ctx.EmitCall(indexerSet); + + // while reader.TryReadFieldReader(fieldNumber) + ctx.LoadReaderWriter(); + ctx.LoadValue(this.fieldNumber); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(redoFromStart, false); + + if (ReturnsValue) + { + ctx.LoadValue(list); + } + } + } +#endif + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta new file mode 100644 index 0000000..246ddd0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d760d5b80fa8e954b9ef20bd51700ac4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs new file mode 100644 index 0000000..3ee80a5 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs @@ -0,0 +1,76 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class MemberSpecifiedDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly MethodInfo getSpecified, setSpecified; + public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail) + : base(tail) + { + if (getSpecified == null && setSpecified == null) throw new InvalidOperationException(); + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + + public override void Write(object value, ProtoWriter dest) + { + if (getSpecified == null || (bool)getSpecified.Invoke(value, null)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + object result = Tail.Read(value, source); + if (setSpecified != null) setSpecified.Invoke(value, new object[] { true }); + return result; + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (getSpecified == null) + { + Tail.EmitWrite(ctx, valueFrom); + return; + } + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.EmitCall(getSpecified); + Compiler.CodeLabel done = ctx.DefineLabel(); + ctx.BranchIfFalse(done, false); + Tail.EmitWrite(ctx, loc); + ctx.MarkLabel(done); + } + + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (setSpecified == null) + { + Tail.EmitRead(ctx, valueFrom); + return; + } + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + Tail.EmitRead(ctx, loc); + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(1); // true + ctx.EmitCall(setSpecified); + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta new file mode 100644 index 0000000..3ee9226 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e59e999094fc1974ea9b58ebe87741e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs new file mode 100644 index 0000000..c3d685b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs @@ -0,0 +1,64 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class NetObjectSerializer : IProtoSerializer + { + private readonly int key; + private readonly Type type; + + private readonly BclHelpers.NetObjectOptions options; + + public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options) + { + bool dynamicType = (options & BclHelpers.NetObjectOptions.DynamicType) != 0; + this.key = dynamicType ? -1 : key; + this.type = dynamicType ? model.MapType(typeof(object)) : type; + this.options = options; + } + + public Type ExpectedType => type; + + public bool ReturnsValue => true; + + public bool RequiresOldValue => true; + + public object Read(object value, ProtoReader source) + { + return BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteNetObject(value, dest, key, options); + } + +#if FEAT_COMPILER + public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + if (type == ctx.MapType(typeof(object))) ctx.LoadNullRef(); + else ctx.LoadValue(type); + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject")); + ctx.CastFromObject(type); + } + public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject")); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta new file mode 100644 index 0000000..05580fc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce4590abb454fca44bcec03b996ad149 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs new file mode 100644 index 0000000..52db14c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs @@ -0,0 +1,167 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class NullDecorator : ProtoDecoratorBase + { + private readonly Type expectedType; + public const int Tag = 1; + public NullDecorator(TypeModel model, IProtoSerializer tail) : base(tail) + { + if (!tail.ReturnsValue) + throw new NotSupportedException("NullDecorator only supports implementations that return values"); + + Type tailType = tail.ExpectedType; + if (Helpers.IsValueType(tailType)) + { + expectedType = model.MapType(typeof(Nullable<>)).MakeGenericType(tailType); + } + else + { + expectedType = tailType; + } + } + + public override Type ExpectedType => expectedType; + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => true; + +#if FEAT_COMPILER + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom)) + using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel(); + + ctx.MarkLabel(next); + + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(field); + ctx.LoadValue(Tag); // = 1 - process + ctx.BranchIfEqual(processField, true); + ctx.LoadValue(field); + ctx.LoadValue(1); // < 1 - exit + ctx.BranchIfLess(end, false); + + // default: skip + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(next, true); + + // process + ctx.MarkLabel(processField); + if (Tail.RequiresOldValue) + { + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(oldValue, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(oldValue); + } + } + Tail.EmitRead(ctx, null); + // note we demanded always returns a value + if (Helpers.IsValueType(expectedType)) + { + ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable it + } + ctx.StoreValue(oldValue); + ctx.Branch(next, false); + + // outro + ctx.MarkLabel(end); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.LoadValue(oldValue); // load the old value + } + } + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local valOrNull = ctx.GetLocalWithValue(expectedType, valueFrom)) + using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + { + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(valOrNull, expectedType); + ctx.LoadValue(expectedType.GetProperty("HasValue")); + } + else + { + ctx.LoadValue(valOrNull); + } + Compiler.CodeLabel @end = ctx.DefineLabel(); + ctx.BranchIfFalse(@end, false); + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(valOrNull, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(valOrNull); + } + Tail.EmitWrite(ctx, null); + + ctx.MarkLabel(@end); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + } +#endif + + public override object Read(object value, ProtoReader source) + { + SubItemToken tok = ProtoReader.StartSubItem(source); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + if (field == Tag) + { + value = Tail.Read(value, source); + } + else + { + source.SkipField(); + } + } + ProtoReader.EndSubItem(tok, source); + return value; + } + + public override void Write(object value, ProtoWriter dest) + { + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (value != null) + { + Tail.Write(value, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta new file mode 100644 index 0000000..2005248 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 06055af4aec01b74bb5fd32975c89463 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs new file mode 100644 index 0000000..9a4bb07 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs @@ -0,0 +1,111 @@ +#if !NO_RUNTIME +using System; +using System.Net; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class ParseableSerializer : IProtoSerializer + { + private readonly MethodInfo parse; + public static ParseableSerializer TryCreate(Type type, TypeModel model) + { + if (type == null) throw new ArgumentNullException("type"); +#if PORTABLE || COREFX || PROFILE259 + MethodInfo method = null; + +#if COREFX || PROFILE259 + foreach (MethodInfo tmp in type.GetTypeInfo().GetDeclaredMethods("Parse")) +#else + foreach (MethodInfo tmp in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) +#endif + { + ParameterInfo[] p; + if (tmp.Name == "Parse" && tmp.IsPublic && tmp.IsStatic && tmp.DeclaringType == type && (p = tmp.GetParameters()) != null && p.Length == 1 && p[0].ParameterType == typeof(string)) + { + method = tmp; + break; + } + } +#else + MethodInfo method = type.GetMethod("Parse", + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, + null, new Type[] { model.MapType(typeof(string)) }, null); +#endif + if (method != null && method.ReturnType == type) + { + if (Helpers.IsValueType(type)) + { + MethodInfo toString = GetCustomToString(type); + if (toString == null || toString.ReturnType != model.MapType(typeof(string))) return null; // need custom ToString, fools + } + return new ParseableSerializer(method); + } + return null; + } + private static MethodInfo GetCustomToString(Type type) + { +#if PORTABLE || COREFX || PROFILE259 + MethodInfo method = Helpers.GetInstanceMethod(type, "ToString", Helpers.EmptyTypes); + if (method == null || !method.IsPublic || method.IsStatic || method.DeclaringType != type) return null; + return method; +#else + + return type.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, + null, Helpers.EmptyTypes, null); +#endif + } + + private ParseableSerializer(MethodInfo parse) + { + this.parse = parse; + } + + public Type ExpectedType => parse.DeclaringType; + + bool IProtoSerializer.RequiresOldValue { get { return false; } } + bool IProtoSerializer.ReturnsValue { get { return true; } } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return parse.Invoke(null, new object[] { source.ReadString() }); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString(value.ToString(), dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type type = ExpectedType; + if (Helpers.IsValueType(type)) + { // note that for structs, we've already asserted that a custom ToString + // exists; no need to handle the box/callvirt scenario + + // force it to a variable if needed, so we can take the address + using (Compiler.Local loc = ctx.GetLocalWithValue(type, valueFrom)) + { + ctx.LoadAddress(loc, type); + ctx.EmitCall(GetCustomToString(type)); + } + } + else + { + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("ToString")); + } + ctx.EmitBasicWrite("WriteString", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ctx.MapType(typeof(string))); + ctx.EmitCall(parse); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta new file mode 100644 index 0000000..8041501 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f0b36e406282d274589b377744611625 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs new file mode 100644 index 0000000..8b0a014 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs @@ -0,0 +1,167 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class PropertyDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => forType; + private readonly PropertyInfo property; + private readonly Type forType; + public override bool RequiresOldValue => true; + public override bool ReturnsValue => false; + private readonly bool readOptionsWriteValue; + private readonly MethodInfo shadowSetter; + + public PropertyDecorator(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail) : base(tail) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(property != null); + this.forType = forType; + this.property = property; + SanityCheck(model, property, tail, out readOptionsWriteValue, true, true); + shadowSetter = GetShadowSetter(model, property); + } + + private static void SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, out bool writeValue, bool nonPublic, bool allowInternal) + { + if (property == null) throw new ArgumentNullException("property"); + + writeValue = tail.ReturnsValue && (GetShadowSetter(model, property) != null || (property.CanWrite && Helpers.GetSetMethod(property, nonPublic, allowInternal) != null)); + if (!property.CanRead || Helpers.GetGetMethod(property, nonPublic, allowInternal) == null) + { + throw new InvalidOperationException("Cannot serialize property without a get accessor"); + } + if (!writeValue && (!tail.RequiresOldValue || Helpers.IsValueType(tail.ExpectedType))) + { // so we can't save the value, and the tail doesn't use it either... not helpful + // or: can't write the value, so the struct value will be lost + throw new InvalidOperationException("Cannot apply changes to property " + property.DeclaringType.FullName + "." + property.Name); + } + } + static MethodInfo GetShadowSetter(TypeModel model, PropertyInfo property) + { +#if COREFX + MethodInfo method = Helpers.GetInstanceMethod(property.DeclaringType.GetTypeInfo(), "Set" + property.Name, new Type[] { property.PropertyType }); +#else + +#if PROFILE259 + Type reflectedType = property.DeclaringType; +#else + Type reflectedType = property.ReflectedType; +#endif + MethodInfo method = Helpers.GetInstanceMethod(reflectedType, "Set" + property.Name, new Type[] { property.PropertyType }); +#endif + if (method == null || !method.IsPublic || method.ReturnType != model.MapType(typeof(void))) return null; + return method; + } + + public override void Write(object value, ProtoWriter dest) + { + Helpers.DebugAssert(value != null); + value = property.GetValue(value, null); + if (value != null) Tail.Write(value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value != null); + + object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null; + object newVal = Tail.Read(oldVal, source); + if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no assign* + { + if (shadowSetter == null) + { + property.SetValue(value, newVal, null); + } + else + { + shadowSetter.Invoke(value, new object[] { newVal }); + } + } + return null; + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(property); + ctx.WriteNullCheckedTail(property.PropertyType, Tail, null); + } + + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + SanityCheck(ctx.Model, property, Tail, out bool writeValue, ctx.NonPublic, ctx.AllowInternal(property)); + if (Helpers.IsValueType(ExpectedType) && valueFrom == null) + { + throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost"); + } + + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(loc, ExpectedType); // stack is: old-addr + ctx.LoadValue(property); // stack is: old-value + } + Type propertyType = property.PropertyType; + ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [new-value] + + if (writeValue) + { + using (Compiler.Local newVal = new Compiler.Local(ctx, property.PropertyType)) + { + ctx.StoreValue(newVal); // stack is empty + + Compiler.CodeLabel allDone = new Compiler.CodeLabel(); // <=== default structs + if (!Helpers.IsValueType(propertyType)) + { // if the tail returns a null, intepret that as *no assign* + allDone = ctx.DefineLabel(); + ctx.LoadValue(newVal); // stack is: new-value + ctx.BranchIfFalse(@allDone, true); // stack is empty + } + // assign the value + ctx.LoadAddress(loc, ExpectedType); // parent-addr + ctx.LoadValue(newVal); // parent-obj|new-value + if (shadowSetter == null) + { + ctx.StoreValue(property); // empty + } + else + { + ctx.EmitCall(shadowSetter); // empty + } + if (!Helpers.IsValueType(propertyType)) + { + ctx.MarkLabel(allDone); + } + } + + } + else + { // don't want return value; drop it if anything there + // stack is [new-value] + if (Tail.ReturnsValue) { ctx.DiscardValue(); } + } + } + } +#endif + + internal static bool CanWrite(TypeModel model, MemberInfo member) + { + if (member == null) throw new ArgumentNullException(nameof(member)); + + if (member is PropertyInfo prop) + { + return prop.CanWrite || GetShadowSetter(model, prop) != null; + } + + return member is FieldInfo; // fields are always writeable; anything else: JUST SAY NO! + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta new file mode 100644 index 0000000..7701c11 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a1a9c77a1e9eba41b4088a86185e3da +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs new file mode 100644 index 0000000..e7f2b34 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs @@ -0,0 +1,24 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + abstract class ProtoDecoratorBase : IProtoSerializer + { + public abstract Type ExpectedType { get; } + protected readonly IProtoSerializer Tail; + protected ProtoDecoratorBase(IProtoSerializer tail) { this.Tail = tail; } + public abstract bool ReturnsValue { get; } + public abstract bool RequiresOldValue { get; } + public abstract void Write(object value, ProtoWriter dest); + public abstract object Read(object value, ProtoReader source); + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitWrite(ctx, valueFrom); } + protected abstract void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitRead(ctx, valueFrom); } + protected abstract void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom); +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta new file mode 100644 index 0000000..8cb42cc --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3736f5ea1793294081157ff6704de05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs new file mode 100644 index 0000000..44edef0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs @@ -0,0 +1,90 @@ +#if !NO_RUNTIME +#if PORTABLE +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + /// + /// Manipulates with uris via reflection rather than strongly typed objects. + /// This is because in PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri) + /// + sealed class ReflectedUriDecorator : ProtoDecoratorBase + { + private readonly Type expectedType; + + private readonly PropertyInfo absoluteUriProperty; + + private readonly ConstructorInfo typeConstructor; + + public ReflectedUriDecorator(Type type, ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail) + { + expectedType = type; + +#if PROFILE259 + absoluteUriProperty = expectedType.GetRuntimeProperty("AbsoluteUri"); + IEnumerable constructors = expectedType.GetTypeInfo().DeclaredConstructors; + typeConstructor = null; + foreach(ConstructorInfo constructor in constructors) + { + ParameterInfo[] parameters = constructor.GetParameters(); + ParameterInfo parameterFirst = parameters.FirstOrDefault(); + Type stringType = typeof(string); + if (parameterFirst != null && + parameterFirst.ParameterType == stringType) + { + typeConstructor = constructor; + break; + } + } +#else + absoluteUriProperty = expectedType.GetProperty("AbsoluteUri"); + typeConstructor = expectedType.GetConstructor(new Type[] { typeof(string) }); +#endif + } + public override Type ExpectedType { get { return expectedType; } } + public override bool RequiresOldValue { get { return false; } } + public override bool ReturnsValue { get { return true; } } + + public override void Write(object value, ProtoWriter dest) + { + Tail.Write(absoluteUriProperty.GetValue(value, null), dest); + } + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // not expecting incoming + string s = (string)Tail.Read(null, source); + + return s.Length == 0 ? null : typeConstructor.Invoke(new object[] { s }); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.LoadValue(absoluteUriProperty); + Tail.EmitWrite(ctx, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + ctx.CopyValue(); + Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); + ctx.LoadValue(typeof(string).GetProperty("Length")); + ctx.BranchIfTrue(@nonEmpty, true); + ctx.DiscardValue(); + ctx.LoadNullRef(); + ctx.Branch(@end, true); + ctx.MarkLabel(@nonEmpty); + ctx.EmitCtor(expectedType, ctx.MapType(typeof(string))); + ctx.MarkLabel(@end); + + } +#endif + } +} +#endif +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta new file mode 100644 index 0000000..81a76dd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d63113b6e13238643a548f086b6d96bf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs new file mode 100644 index 0000000..81d233e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs @@ -0,0 +1,45 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class SByteSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(sbyte); + + public SByteSerializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadSByte(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSByte((sbyte)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteSByte", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadSByte", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta new file mode 100644 index 0000000..5a887d1 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 30e3edc884196924eae4060aac30237e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs new file mode 100644 index 0000000..c5ade13 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs @@ -0,0 +1,45 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class SingleSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(float); + + public Type ExpectedType { get { return expectedType; } } + + public SingleSerializer(TypeModel model) + { + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadSingle(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSingle((float)value, dest); + } + + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteSingle", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadSingle", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta new file mode 100644 index 0000000..6ec72b9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dad5ecdc56c764e47b09ff2cde697a97 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs new file mode 100644 index 0000000..399b4bb --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class StringSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(string); + + public StringSerializer(ProtoBuf.Meta.TypeModel model) + { + } + + public Type ExpectedType => expectedType; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString((string)value, dest); + } + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadString(); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteString", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta new file mode 100644 index 0000000..640639d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 61e33496489a7874a8c9c870857fe155 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs new file mode 100644 index 0000000..58015aa --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs @@ -0,0 +1,138 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; + +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class SubItemSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return ((IProtoTypeSerializer)proxy.Serializer).HasCallbacks(callbackType); + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return ((IProtoTypeSerializer)proxy.Serializer).CanCreateInstance(); + } + +#if FEAT_COMPILER + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCreateInstance(ctx); + } +#endif + + void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + ((IProtoTypeSerializer)proxy.Serializer).Callback(value, callbackType, context); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source); + } + + private readonly int key; + private readonly Type type; + private readonly ISerializerProxy proxy; + private readonly bool recursionCheck; + public SubItemSerializer(Type type, int key, ISerializerProxy proxy, bool recursionCheck) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + this.proxy = proxy ?? throw new ArgumentNullException(nameof(proxy)); + this.key = key; + this.recursionCheck = recursionCheck; + } + + Type IProtoSerializer.ExpectedType => type; + + bool IProtoSerializer.RequiresOldValue => true; + + bool IProtoSerializer.ReturnsValue => true; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + if (recursionCheck) + { + ProtoWriter.WriteObject(value, key, dest); + } + else + { + ProtoWriter.WriteRecursionSafeObject(value, key, dest); + } + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return ProtoReader.ReadObject(value, key, source); + } + +#if FEAT_COMPILER + bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read) + { + MethodBuilder method = ctx.GetDedicatedMethod(key, read); + if (method == null) return false; + + using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + { + Type rwType = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter)); + ctx.LoadValue(valueFrom); + if (!read) // write requires the object for StartSubItem; read doesn't + { // (if recursion-check is disabled [subtypes] then null is fine too) + if (Helpers.IsValueType(type) || !recursionCheck) { ctx.LoadNullRef(); } + else { ctx.CopyValue(); } + } + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(rwType, "StartSubItem", + read ? new Type[] { rwType } : new Type[] { ctx.MapType(typeof(object)), rwType })); + ctx.StoreValue(token); + + // note: value already on the stack + ctx.LoadReaderWriter(); + ctx.EmitCall(method); + // handle inheritance (we will be calling the *base* version of things, + // but we expect Read to return the "type" type) + if (read && type != method.ReturnType) ctx.Cast(this.type); + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(rwType, "EndSubItem", new Type[] { ctx.MapType(typeof(SubItemToken)), rwType })); + } + return true; + } + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, false)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) ctx.CastToObject(type); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoWriter)), recursionCheck ? "WriteObject" : "WriteRecursionSafeObject", new Type[] { ctx.MapType(typeof(object)), ctx.MapType(typeof(int)), ctx.MapType(typeof(ProtoWriter)) })); + } + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, true)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) ctx.CastToObject(type); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoReader)), "ReadObject")); + ctx.CastFromObject(type); + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta new file mode 100644 index 0000000..13ea71b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc8c27e4c7ffe0342952d9e042777bc5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs new file mode 100644 index 0000000..86275eb --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs @@ -0,0 +1,157 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class SurrogateSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(ProtoBuf.Meta.TypeModel.CallbackType callbackType) { return false; } +#if FEAT_COMPILER + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, ProtoBuf.Meta.TypeModel.CallbackType callbackType) { } + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); } +#endif + bool IProtoTypeSerializer.CanCreateInstance() => false; + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) => throw new NotSupportedException(); + + void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType, SerializationContext context) { } + + public bool ReturnsValue => false; + + public bool RequiresOldValue => true; + + public Type ExpectedType => forType; + + private readonly Type forType, declaredType; + private readonly MethodInfo toTail, fromTail; + IProtoTypeSerializer rootTail; + + public SurrogateSerializer(TypeModel model, Type forType, Type declaredType, IProtoTypeSerializer rootTail) + { + Helpers.DebugAssert(forType != null, "forType"); + Helpers.DebugAssert(declaredType != null, "declaredType"); + Helpers.DebugAssert(rootTail != null, "rootTail"); + Helpers.DebugAssert(rootTail.RequiresOldValue, "RequiresOldValue"); + Helpers.DebugAssert(!rootTail.ReturnsValue, "ReturnsValue"); + Helpers.DebugAssert(declaredType == rootTail.ExpectedType || Helpers.IsSubclassOf(declaredType, rootTail.ExpectedType)); + this.forType = forType; + this.declaredType = declaredType; + this.rootTail = rootTail; + toTail = GetConversion(model, true); + fromTail = GetConversion(model, false); + } + private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op) + { +#if PROFILE259 + System.Collections.Generic.List list = new System.Collections.Generic.List(); + foreach (var item in type.GetRuntimeMethods()) + { + if (item.IsStatic) list.Add(item); + } + MethodInfo[] found = list.ToArray(); +#else + const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + MethodInfo[] found = type.GetMethods(flags); +#endif + ParameterInfo[] paramTypes; + Type convertAttributeType = null; + for (int i = 0; i < found.Length; i++) + { + MethodInfo m = found[i]; + if (m.ReturnType != to) continue; + paramTypes = m.GetParameters(); + if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from) + { + if (convertAttributeType == null) + { + convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false); + if (convertAttributeType == null) + { // attribute isn't defined in the source assembly: stop looking + break; + } + } + if (m.IsDefined(convertAttributeType, true)) + { + op = m; + return true; + } + } + } + + for (int i = 0; i < found.Length; i++) + { + MethodInfo m = found[i]; + if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to) + { + continue; + } + paramTypes = m.GetParameters(); + if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from) + { + op = m; + return true; + } + } + op = null; + return false; + } + + public MethodInfo GetConversion(TypeModel model, bool toTail) + { + Type to = toTail ? declaredType : forType; + Type from = toTail ? forType : declaredType; + MethodInfo op; + if (HasCast(model, declaredType, from, to, out op) || HasCast(model, forType, from, to, out op)) + { + return op; + } + throw new InvalidOperationException("No suitable conversion operator found for surrogate: " + + forType.FullName + " / " + declaredType.FullName); + } + + public void Write(object value, ProtoWriter writer) + { + rootTail.Write(toTail.Invoke(null, new object[] { value }), writer); + } + + public object Read(object value, ProtoReader source) + { + // convert the incoming value + object[] args = { value }; + value = toTail.Invoke(null, args); + + // invoke the tail and convert the outgoing value + args[0] = rootTail.Read(value, source); + return fromTail.Invoke(null, args); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Helpers.DebugAssert(valueFrom != null); // don't support stack-head for this + using (Compiler.Local converted = new Compiler.Local(ctx, declaredType)) // declare/re-use local + { + ctx.LoadValue(valueFrom); // load primary onto stack + ctx.EmitCall(toTail); // static convert op, primary-to-surrogate + ctx.StoreValue(converted); // store into surrogate local + + rootTail.EmitRead(ctx, converted); // downstream processing against surrogate local + + ctx.LoadValue(converted); // load from surrogate local + ctx.EmitCall(fromTail); // static convert op, surrogate-to-primary + ctx.StoreValue(valueFrom); // store back into primary + } + } + + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.EmitCall(toTail); + rootTail.EmitWrite(ctx, null); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta new file mode 100644 index 0000000..46b1a81 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ecf75b163b5ff4d45a4d266e2db22143 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs new file mode 100644 index 0000000..4b1656d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs @@ -0,0 +1,46 @@ +using System; + +#if !NO_RUNTIME + +namespace ProtoBuf.Serializers +{ + sealed class SystemTypeSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(Type); + + public SystemTypeSerializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteType((Type)value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadType(); + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteType", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadType", ExpectedType); + } +#endif + } +} + +#endif diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta new file mode 100644 index 0000000..9469ed1 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b496ff0ff6a21b41a4a510cda44f507 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs new file mode 100644 index 0000000..509b8a0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs @@ -0,0 +1,108 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class TagDecorator : ProtoDecoratorBase, IProtoTypeSerializer + { + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; + return pts != null && pts.HasCallbacks(callbackType); + } + + public bool CanCreateInstance() + { + IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; + return pts != null && pts.CanCreateInstance(); + } + + public object CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)Tail).CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (Tail is IProtoTypeSerializer pts) + { + pts.Callback(value, callbackType, context); + } + } + +#if FEAT_COMPILER + public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + // we only expect this to be invoked if HasCallbacks returned true, so implicitly Tail + // **must** be of the correct type + ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); + } + + public void EmitCreateInstance(Compiler.CompilerContext ctx) + { + ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx); + } +#endif + public override Type ExpectedType => Tail.ExpectedType; + + public TagDecorator(int fieldNumber, WireType wireType, bool strict, IProtoSerializer tail) + : base(tail) + { + this.fieldNumber = fieldNumber; + this.wireType = wireType; + this.strict = strict; + } + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly bool strict; + private readonly int fieldNumber; + private readonly WireType wireType; + + private bool NeedsHint => ((int)wireType & ~7) != 0; + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(fieldNumber == source.FieldNumber); + if (strict) { source.Assert(wireType); } + else if (NeedsHint) { source.Hint(wireType); } + return Tail.Read(value, source); + } + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + Tail.Write(value, dest); + } + + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue((int)fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + Tail.EmitWrite(ctx, valueFrom); + } + + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + if (strict || NeedsHint) + { + ctx.LoadReaderWriter(); + ctx.LoadValue((int)wireType); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod(strict ? "Assert" : "Hint")); + } + Tail.EmitRead(ctx, valueFrom); + } +#endif + } + +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta new file mode 100644 index 0000000..bd2c387 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa4105005ff5e7841ad896b95e057bf7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs new file mode 100644 index 0000000..4c8b828 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs @@ -0,0 +1,63 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class TimeSpanSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(TimeSpan); + private readonly bool wellKnown; + public TimeSpanSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model) + { + + wellKnown = dataFormat == DataFormat.WellKnown; + } + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadDuration(source); + } + else + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadTimeSpan(source); + } + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + { + BclHelpers.WriteDuration((TimeSpan)value, dest); + } + else + { + BclHelpers.WriteTimeSpan((TimeSpan)value, dest); + } + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.WriteDuration) : nameof(BclHelpers.WriteTimeSpan), valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (wellKnown) ctx.LoadValue(valueFrom); + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.ReadDuration) : nameof(BclHelpers.ReadTimeSpan), + ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta new file mode 100644 index 0000000..300b5f7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 265babd45cabb2f4baa92d2c01465982 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs new file mode 100644 index 0000000..b6f9c69 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs @@ -0,0 +1,339 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class TupleSerializer : IProtoTypeSerializer + { + private readonly MemberInfo[] members; + private readonly ConstructorInfo ctor; + private IProtoSerializer[] tails; + public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) + { + this.ctor = ctor ?? throw new ArgumentNullException(nameof(ctor)); + this.members = members ?? throw new ArgumentNullException(nameof(members)); + this.tails = new IProtoSerializer[members.Length]; + + ParameterInfo[] parameters = ctor.GetParameters(); + for (int i = 0; i < members.Length; i++) + { + WireType wireType; + Type finalType = parameters[i].ParameterType; + + Type itemType = null, defaultType = null; + + MetaType.ResolveListTypes(model, finalType, ref itemType, ref defaultType); + Type tmp = itemType == null ? finalType : itemType; + + bool asReference = false; + int typeIndex = model.FindOrAddAuto(tmp, false, true, false); + if (typeIndex >= 0) + { + asReference = model[tmp].AsReferenceDefault; + } + IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, false, false, true), serializer; + if (tail == null) + { + throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); + } + + tail = new TagDecorator(i + 1, wireType, false, tail); + if (itemType == null) + { + serializer = tail; + } + else + { + if (finalType.IsArray) + { + serializer = new ArrayDecorator(model, tail, i + 1, false, wireType, finalType, false, false); + } + else + { + serializer = ListDecorator.Create(model, finalType, defaultType, tail, i + 1, false, wireType, true, false, false); + } + } + tails[i] = serializer; + } + } + public bool HasCallbacks(Meta.TypeModel.CallbackType callbackType) + { + return false; + } + +#if FEAT_COMPILER + public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, Meta.TypeModel.CallbackType callbackType) { } +#endif + public Type ExpectedType => ctor.DeclaringType; + + void IProtoTypeSerializer.Callback(object value, Meta.TypeModel.CallbackType callbackType, SerializationContext context) { } + object IProtoTypeSerializer.CreateInstance(ProtoReader source) { throw new NotSupportedException(); } + private object GetValue(object obj, int index) + { + PropertyInfo prop; + FieldInfo field; + + if ((prop = members[index] as PropertyInfo) != null) + { + if (obj == null) + return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null; + return prop.GetValue(obj, null); + } + else if ((field = members[index] as FieldInfo) != null) + { + if (obj == null) + return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null; + return field.GetValue(obj); + } + else + { + throw new InvalidOperationException(); + } + } + + public object Read(object value, ProtoReader source) + { + object[] values = new object[members.Length]; + bool invokeCtor = false; + if (value == null) + { + invokeCtor = true; + } + for (int i = 0; i < values.Length; i++) + values[i] = GetValue(value, i); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + invokeCtor = true; + if (field <= tails.Length) + { + IProtoSerializer tail = tails[field - 1]; + values[field - 1] = tails[field - 1].Read(tail.RequiresOldValue ? values[field - 1] : null, source); + } + else + { + source.SkipField(); + } + } + return invokeCtor ? ctor.Invoke(values) : value; + } + + public void Write(object value, ProtoWriter dest) + { + for (int i = 0; i < tails.Length; i++) + { + object val = GetValue(value, i); + if (val != null) tails[i].Write(val, dest); + } + } + + public bool RequiresOldValue => true; + + public bool ReturnsValue => false; + + Type GetMemberType(int index) + { + Type result = Helpers.GetMemberType(members[index]); + if (result == null) throw new InvalidOperationException(); + return result; + } + + bool IProtoTypeSerializer.CanCreateInstance() { return false; } + +#if FEAT_COMPILER + public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ctor.DeclaringType, valueFrom)) + { + for (int i = 0; i < tails.Length; i++) + { + Type type = GetMemberType(i); + ctx.LoadAddress(loc, ExpectedType); + if (members[i] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[i]); + } + else if (members[i] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[i]); + } + ctx.WriteNullCheckedTail(type, tails[i], null); + } + } + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); } + + public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming) + { + using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming)) + { + Compiler.Local[] locals = new Compiler.Local[members.Length]; + try + { + for (int i = 0; i < locals.Length; i++) + { + Type type = GetMemberType(i); + bool store = true; + locals[i] = new Compiler.Local(ctx, type); + if (!Helpers.IsValueType(ExpectedType)) + { + // value-types always read the old value + if (Helpers.IsValueType(type)) + { + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.SByte: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + ctx.LoadValue(0); + break; + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + ctx.LoadValue(0L); + break; + case ProtoTypeCode.Single: + ctx.LoadValue(0.0F); + break; + case ProtoTypeCode.Double: + ctx.LoadValue(0.0D); + break; + case ProtoTypeCode.Decimal: + ctx.LoadValue(0M); + break; + case ProtoTypeCode.Guid: + ctx.LoadValue(Guid.Empty); + break; + default: + ctx.LoadAddress(locals[i], type); + ctx.EmitCtor(type); + store = false; + break; + } + } + else + { + ctx.LoadNullRef(); + } + if (store) + { + ctx.StoreValue(locals[i]); + } + } + } + + Compiler.CodeLabel skipOld = Helpers.IsValueType(ExpectedType) + ? new Compiler.CodeLabel() + : ctx.DefineLabel(); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadAddress(objValue, ExpectedType); + ctx.BranchIfFalse(skipOld, false); + } + for (int i = 0; i < members.Length; i++) + { + ctx.LoadAddress(objValue, ExpectedType); + if (members[i] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[i]); + } + else if (members[i] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[i]); + } + ctx.StoreValue(locals[i]); + } + + if (!Helpers.IsValueType(ExpectedType)) ctx.MarkLabel(skipOld); + + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + Compiler.CodeLabel @continue = ctx.DefineLabel(), + processField = ctx.DefineLabel(), + notRecognised = ctx.DefineLabel(); + ctx.Branch(@continue, false); + + Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length]; + for (int i = 0; i < members.Length; i++) + { + handlers[i] = ctx.DefineLabel(); + } + + ctx.MarkLabel(processField); + + ctx.LoadValue(fieldNumber); + ctx.LoadValue(1); + ctx.Subtract(); // jump-table is zero-based + ctx.Switch(handlers); + + // and the default: + ctx.Branch(notRecognised, false); + for (int i = 0; i < handlers.Length; i++) + { + ctx.MarkLabel(handlers[i]); + IProtoSerializer tail = tails[i]; + Compiler.Local oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null; + ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded); + if (tail.ReturnsValue) + { + if (Helpers.IsValueType(locals[i].Type)) + { + ctx.StoreValue(locals[i]); + } + else + { + Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel(); + + ctx.CopyValue(); + ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign" + ctx.DiscardValue(); + ctx.Branch(allDone, true); + ctx.MarkLabel(hasValue); + ctx.StoreValue(locals[i]); + ctx.MarkLabel(allDone); + } + } + ctx.Branch(@continue, false); + } + + ctx.MarkLabel(notRecognised); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + } + for (int i = 0; i < locals.Length; i++) + { + ctx.LoadValue(locals[i]); + } + + ctx.EmitCtor(ctor); + ctx.StoreValue(objValue); + } + finally + { + for (int i = 0; i < locals.Length; i++) + { + if (locals[i] != null) + locals[i].Dispose(); // release for re-use + } + } + } + + } +#endif + } +} + +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta new file mode 100644 index 0000000..81dce16 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7bc4fc3f3fb41534ea8bc85bfc7b07fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs new file mode 100644 index 0000000..d851b47 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs @@ -0,0 +1,798 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +#if FEAT_COMPILER + +#endif + +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class TypeSerializer : IProtoTypeSerializer + { + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + if (callbacks != null && callbacks[callbackType] != null) return true; + for (int i = 0; i < serializers.Length; i++) + { + if (serializers[i].ExpectedType != forType && ((IProtoTypeSerializer)serializers[i]).HasCallbacks(callbackType)) return true; + } + return false; + } + private readonly Type forType, constructType; +#if COREFX || PROFILE259 + private readonly TypeInfo typeInfo; +#endif + public Type ExpectedType { get { return forType; } } + private readonly IProtoSerializer[] serializers; + private readonly int[] fieldNumbers; + private readonly bool isRootType, useConstructor, isExtensible, hasConstructor; + private readonly CallbackSet callbacks; + private readonly MethodInfo[] baseCtorCallbacks; + private readonly MethodInfo factory; + public TypeSerializer(TypeModel model, Type forType, int[] fieldNumbers, IProtoSerializer[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, CallbackSet callbacks, Type constructType, MethodInfo factory) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(fieldNumbers != null); + Helpers.DebugAssert(serializers != null); + Helpers.DebugAssert(fieldNumbers.Length == serializers.Length); + + Helpers.Sort(fieldNumbers, serializers); + bool hasSubTypes = false; + for (int i = 0; i < fieldNumbers.Length; i++) + { + if (i != 0 && fieldNumbers[i] == fieldNumbers[i - 1]) throw new InvalidOperationException("Duplicate field-number detected; " + + fieldNumbers[i].ToString() + " on: " + forType.FullName); + if (!hasSubTypes && serializers[i].ExpectedType != forType) + { + hasSubTypes = true; + } + } + this.forType = forType; + this.factory = factory; +#if COREFX || PROFILE259 + this.typeInfo = forType.GetTypeInfo(); +#endif + if (constructType == null) + { + constructType = forType; + } + else + { +#if COREFX || PROFILE259 + if (!typeInfo.IsAssignableFrom(constructType.GetTypeInfo())) +#else + if (!forType.IsAssignableFrom(constructType)) +#endif + { + throw new InvalidOperationException(forType.FullName + " cannot be assigned from " + constructType.FullName); + } + } + this.constructType = constructType; + this.serializers = serializers; + this.fieldNumbers = fieldNumbers; + this.callbacks = callbacks; + this.isRootType = isRootType; + this.useConstructor = useConstructor; + + if (baseCtorCallbacks != null && baseCtorCallbacks.Length == 0) baseCtorCallbacks = null; + this.baseCtorCallbacks = baseCtorCallbacks; + + if (Helpers.GetUnderlyingType(forType) != null) + { + throw new ArgumentException("Cannot create a TypeSerializer for nullable types", "forType"); + } + +#if COREFX || PROFILE259 + if (iextensible.IsAssignableFrom(typeInfo)) + { + if (typeInfo.IsValueType || !isRootType || hasSubTypes) +#else + if (model.MapType(iextensible).IsAssignableFrom(forType)) + { + if (forType.IsValueType || !isRootType || hasSubTypes) +#endif + { + throw new NotSupportedException("IExtensible is not supported in structs or classes with inheritance"); + } + isExtensible = true; + } +#if COREFX || PROFILE259 + TypeInfo constructTypeInfo = constructType.GetTypeInfo(); + hasConstructor = !constructTypeInfo.IsAbstract && Helpers.GetConstructor(constructTypeInfo, Helpers.EmptyTypes, true) != null; +#else + hasConstructor = !constructType.IsAbstract && Helpers.GetConstructor(constructType, Helpers.EmptyTypes, true) != null; +#endif + if (constructType != forType && useConstructor && !hasConstructor) + { + throw new ArgumentException("The supplied default implementation cannot be created: " + constructType.FullName, "constructType"); + } + } +#if COREFX || PROFILE259 + private static readonly TypeInfo iextensible = typeof(IExtensible).GetTypeInfo(); +#else + private static readonly System.Type iextensible = typeof(IExtensible); +#endif + + private bool CanHaveInheritance + { + get + { +#if COREFX || PROFILE259 + return (typeInfo.IsClass || typeInfo.IsInterface) && !typeInfo.IsSealed; +#else + return (forType.IsClass || forType.IsInterface) && !forType.IsSealed; +#endif + } + } + + bool IProtoTypeSerializer.CanCreateInstance() { return true; } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return CreateInstance(source, false); + } + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (callbacks != null) InvokeCallback(callbacks[callbackType], value, context); + IProtoTypeSerializer ser = (IProtoTypeSerializer)GetMoreSpecificSerializer(value); + if (ser != null) ser.Callback(value, callbackType, context); + } + private IProtoSerializer GetMoreSpecificSerializer(object value) + { + if (!CanHaveInheritance) return null; + Type actualType = value.GetType(); + if (actualType == forType) return null; + + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType != forType && Helpers.IsAssignableFrom(ser.ExpectedType, actualType)) + { + return ser; + } + } + if (actualType == constructType) return null; // needs to be last in case the default concrete type is also a known sub-type + TypeModel.ThrowUnexpectedSubtype(forType, actualType); // might throw (if not a proxy) + return null; + } + + public void Write(object value, ProtoWriter dest) + { + if (isRootType) Callback(value, TypeModel.CallbackType.BeforeSerialize, dest.Context); + // write inheritance first + IProtoSerializer next = GetMoreSpecificSerializer(value); + if (next != null) next.Write(value, dest); + + // write all actual fields + //Helpers.DebugWriteLine(">> Writing fields for " + forType.FullName); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType == forType) + { + //Helpers.DebugWriteLine(": " + ser.ToString()); + ser.Write(value, dest); + } + } + //Helpers.DebugWriteLine("<< Writing fields for " + forType.FullName); + if (isExtensible) ProtoWriter.AppendExtensionData((IExtensible)value, dest); + if (isRootType) Callback(value, TypeModel.CallbackType.AfterSerialize, dest.Context); + } + + public object Read(object value, ProtoReader source) + { + if (isRootType && value != null) { Callback(value, TypeModel.CallbackType.BeforeDeserialize, source.Context); } + int fieldNumber, lastFieldNumber = 0, lastFieldIndex = 0; + bool fieldHandled; + + //Helpers.DebugWriteLine(">> Reading fields for " + forType.FullName); + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + fieldHandled = false; + if (fieldNumber < lastFieldNumber) + { + lastFieldNumber = lastFieldIndex = 0; + } + for (int i = lastFieldIndex; i < fieldNumbers.Length; i++) + { + if (fieldNumbers[i] == fieldNumber) + { + IProtoSerializer ser = serializers[i]; + //Helpers.DebugWriteLine(": " + ser.ToString()); + Type serType = ser.ExpectedType; + if (value == null) + { + if (serType == forType) value = CreateInstance(source, true); + } + else + { + if (serType != forType && ((IProtoTypeSerializer)ser).CanCreateInstance() + && serType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsSubclassOf(value.GetType())) + { + value = ProtoReader.Merge(source, value, ((IProtoTypeSerializer)ser).CreateInstance(source)); + } + } + + if (ser.ReturnsValue) + { + value = ser.Read(value, source); + } + else + { // pop + ser.Read(value, source); + } + + lastFieldIndex = i; + lastFieldNumber = fieldNumber; + fieldHandled = true; + break; + } + } + if (!fieldHandled) + { + //Helpers.DebugWriteLine(": [" + fieldNumber + "] (unknown)"); + if (value == null) value = CreateInstance(source, true); + if (isExtensible) + { + source.AppendExtensionData((IExtensible)value); + } + else + { + source.SkipField(); + } + } + } + //Helpers.DebugWriteLine("<< Reading fields for " + forType.FullName); + if (value == null) value = CreateInstance(source, true); + if (isRootType) { Callback(value, TypeModel.CallbackType.AfterDeserialize, source.Context); } + return value; + } + + private object InvokeCallback(MethodInfo method, object obj, SerializationContext context) + { + object result = null; + object[] args; + if (method != null) + { // pass in a streaming context if one is needed, else null + bool handled; + ParameterInfo[] parameters = method.GetParameters(); + switch (parameters.Length) + { + case 0: + args = null; + handled = true; + break; + default: + args = new object[parameters.Length]; + handled = true; + for (int i = 0; i < args.Length; i++) + { + object val; + Type paramType = parameters[i].ParameterType; + if (paramType == typeof(SerializationContext)) val = context; + else if (paramType == typeof(System.Type)) val = constructType; +#if PLAT_BINARYFORMATTER + else if (paramType == typeof(System.Runtime.Serialization.StreamingContext)) val = (System.Runtime.Serialization.StreamingContext)context; +#endif + else + { + val = null; + handled = false; + } + args[i] = val; + } + break; + } + if (handled) + { + result = method.Invoke(obj, args); + } + else + { + throw Meta.CallbackSet.CreateInvalidCallbackSignature(method); + } + + } + return result; + } + object CreateInstance(ProtoReader source, bool includeLocalCallback) + { + //Helpers.DebugWriteLine("* creating : " + forType.FullName); + object obj; + if (factory != null) + { + obj = InvokeCallback(factory, null, source.Context); + } + else if (useConstructor) + { + if (!hasConstructor) TypeModel.ThrowCannotCreateInstance(constructType); +#if PROFILE259 + ConstructorInfo constructorInfo = System.Linq.Enumerable.First( + constructType.GetTypeInfo().DeclaredConstructors, c => c.GetParameters().Length == 0); + obj = constructorInfo.Invoke(new object[] {}); + +#else + obj = Activator.CreateInstance(constructType +#if !(CF || PORTABLE || NETSTANDARD1_3 || NETSTANDARD1_4 || UAP) + , nonPublic: true +#endif + ); +#endif + } + else + { + obj = BclHelpers.GetUninitializedObject(constructType); + } + ProtoReader.NoteObject(obj, source); + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + InvokeCallback(baseCtorCallbacks[i], obj, source.Context); + } + } + if (includeLocalCallback && callbacks != null) InvokeCallback(callbacks.BeforeDeserialize, obj, source.Context); + return obj; + } + + bool IProtoSerializer.RequiresOldValue { get { return true; } } + bool IProtoSerializer.ReturnsValue { get { return false; } } // updates field directly +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type expected = ExpectedType; + using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom)) + { + // pre-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeSerialize); + + Compiler.CodeLabel startFields = ctx.DefineLabel(); + // inheritance + if (CanHaveInheritance) + { + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + Type serType = ser.ExpectedType; + if (serType != forType) + { + Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel(); + ctx.LoadValue(loc); + ctx.TryCast(serType); + ctx.CopyValue(); + ctx.BranchIfTrue(ifMatch, true); + ctx.DiscardValue(); + ctx.Branch(nextTest, true); + ctx.MarkLabel(ifMatch); + if (Helpers.IsValueType(serType)) + { + ctx.DiscardValue(); + ctx.LoadValue(loc); + ctx.CastFromObject(serType); + } + ser.EmitWrite(ctx, null); + ctx.Branch(startFields, false); + ctx.MarkLabel(nextTest); + } + } + + + if (constructType != null && constructType != forType) + { + using (Compiler.Local actualType = new Compiler.Local(ctx, ctx.MapType(typeof(System.Type)))) + { + // would have jumped to "fields" if an expected sub-type, so two options: + // a: *exactly* that type, b: an *unexpected* type + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.CopyValue(); + ctx.StoreValue(actualType); + ctx.LoadValue(forType); + ctx.BranchIfEqual(startFields, true); + + ctx.LoadValue(actualType); + ctx.LoadValue(constructType); + ctx.BranchIfEqual(startFields, true); + } + } + else + { + // would have jumped to "fields" if an expected sub-type, so two options: + // a: *exactly* that type, b: an *unexpected* type + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.LoadValue(forType); + ctx.BranchIfEqual(startFields, true); + } + // unexpected, then... note that this *might* be a proxy, which + // is handled by ThrowUnexpectedSubtype + ctx.LoadValue(forType); + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowUnexpectedSubtype", + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)); + + } + // fields + + ctx.MarkLabel(startFields); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType == forType) ser.EmitWrite(ctx, loc); + } + + // extension data + if (isExtensible) + { + ctx.LoadValue(loc); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("AppendExtensionData")); + } + // post-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterSerialize); + } + } + static void EmitInvokeCallback(Compiler.CompilerContext ctx, MethodInfo method, bool copyValue, Type constructType, Type type) + { + if (method != null) + { + if (copyValue) ctx.CopyValue(); // assumes the target is on the stack, and that we want to *retain* it on the stack + ParameterInfo[] parameters = method.GetParameters(); + bool handled = true; + + for (int i = 0; i < parameters.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + if (parameterType == ctx.MapType(typeof(SerializationContext))) + { + ctx.LoadSerializationContext(); + } + else if (parameterType == ctx.MapType(typeof(System.Type))) + { + Type tmp = constructType; + if (tmp == null) tmp = type; // no ?? in some C# profiles + ctx.LoadValue(tmp); + } +#if PLAT_BINARYFORMATTER + else if (parameterType == ctx.MapType(typeof(System.Runtime.Serialization.StreamingContext))) + { + ctx.LoadSerializationContext(); + MethodInfo op = ctx.MapType(typeof(SerializationContext)).GetMethod("op_Implicit", new Type[] { ctx.MapType(typeof(SerializationContext)) }); + if (op != null) + { // it isn't always! (framework versions, etc) + ctx.EmitCall(op); + handled = true; + } + } +#endif + else + { + handled = false; + } + } + if (handled) + { + ctx.EmitCall(method); + if (constructType != null) + { + if (method.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(type); + } + } + } + else + { + throw Meta.CallbackSet.CreateInvalidCallbackSignature(method); + } + } + } + + private void EmitCallbackIfNeeded(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + Helpers.DebugAssert(valueFrom != null); + if (isRootType && ((IProtoTypeSerializer)this).HasCallbacks(callbackType)) + { + ((IProtoTypeSerializer)this).EmitCallback(ctx, valueFrom, callbackType); + } + } + + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + bool actuallyHasInheritance = false; + if (CanHaveInheritance) + { + + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType != forType && ((IProtoTypeSerializer)ser).HasCallbacks(callbackType)) + { + actuallyHasInheritance = true; + } + } + } + + Helpers.DebugAssert(((IProtoTypeSerializer)this).HasCallbacks(callbackType), "Shouldn't be calling this if there is nothing to do"); + MethodInfo method = callbacks?[callbackType]; + if (method == null && !actuallyHasInheritance) + { + return; + } + ctx.LoadAddress(valueFrom, ExpectedType); + EmitInvokeCallback(ctx, method, actuallyHasInheritance, null, forType); + + if (actuallyHasInheritance) + { + Compiler.CodeLabel @break = ctx.DefineLabel(); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + IProtoTypeSerializer typeser; + Type serType = ser.ExpectedType; + if (serType != forType && + (typeser = (IProtoTypeSerializer)ser).HasCallbacks(callbackType)) + { + Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel(); + ctx.CopyValue(); + ctx.TryCast(serType); + ctx.CopyValue(); + ctx.BranchIfTrue(ifMatch, true); + ctx.DiscardValue(); + ctx.Branch(nextTest, false); + ctx.MarkLabel(ifMatch); + typeser.EmitCallback(ctx, null, callbackType); + ctx.Branch(@break, false); + ctx.MarkLabel(nextTest); + } + } + ctx.MarkLabel(@break); + ctx.DiscardValue(); + } + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type expected = ExpectedType; + Helpers.DebugAssert(valueFrom != null); + + using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom)) + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + // pre-callbacks + if (HasCallbacks(TypeModel.CallbackType.BeforeDeserialize)) + { + if (Helpers.IsValueType(ExpectedType)) + { + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize); + } + else + { // could be null + Compiler.CodeLabel callbacksDone = ctx.DefineLabel(); + ctx.LoadValue(loc); + ctx.BranchIfFalse(callbacksDone, false); + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize); + ctx.MarkLabel(callbacksDone); + } + } + + Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel(); + ctx.Branch(@continue, false); + + ctx.MarkLabel(processField); + foreach (BasicList.Group group in BasicList.GetContiguousGroups(fieldNumbers, serializers)) + { + Compiler.CodeLabel tryNextField = ctx.DefineLabel(); + int groupItemCount = group.Items.Count; + if (groupItemCount == 1) + { + // discreet group; use an equality test + ctx.LoadValue(fieldNumber); + ctx.LoadValue(group.First); + Compiler.CodeLabel processThisField = ctx.DefineLabel(); + ctx.BranchIfEqual(processThisField, true); + ctx.Branch(tryNextField, false); + WriteFieldHandler(ctx, expected, loc, processThisField, @continue, (IProtoSerializer)group.Items[0]); + } + else + { // implement as a jump-table-based switch + ctx.LoadValue(fieldNumber); + ctx.LoadValue(group.First); + ctx.Subtract(); // jump-tables are zero-based + Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount]; + for (int i = 0; i < groupItemCount; i++) + { + jmp[i] = ctx.DefineLabel(); + } + ctx.Switch(jmp); + // write the default... + ctx.Branch(tryNextField, false); + for (int i = 0; i < groupItemCount; i++) + { + WriteFieldHandler(ctx, expected, loc, jmp[i], @continue, (IProtoSerializer)group.Items[i]); + } + } + ctx.MarkLabel(tryNextField); + } + + EmitCreateIfNull(ctx, loc); + ctx.LoadReaderWriter(); + if (isExtensible) + { + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendExtensionData")); + } + else + { + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + } + + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + + EmitCreateIfNull(ctx, loc); + // post-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterDeserialize); + + if (valueFrom != null && !loc.IsSame(valueFrom)) + { + ctx.LoadValue(loc); + ctx.Cast(valueFrom.Type); + ctx.StoreValue(valueFrom); + } + } + } + + private void WriteFieldHandler( + Compiler.CompilerContext ctx, Type expected, Compiler.Local loc, + Compiler.CodeLabel handler, Compiler.CodeLabel @continue, IProtoSerializer serializer) + { + ctx.MarkLabel(handler); + Type serType = serializer.ExpectedType; + if (serType == forType) + { + EmitCreateIfNull(ctx, loc); + serializer.EmitRead(ctx, loc); + } + else + { + //RuntimeTypeModel rtm = (RuntimeTypeModel)ctx.Model; + if (((IProtoTypeSerializer)serializer).CanCreateInstance()) + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + + ctx.LoadValue(loc); + ctx.BranchIfFalse(allDone, false); // null is always ok + + ctx.LoadValue(loc); + ctx.TryCast(serType); + ctx.BranchIfTrue(allDone, false); // not null, but of the correct type + + // otherwise, need to convert it + ctx.LoadReaderWriter(); + ctx.LoadValue(loc); + ((IProtoTypeSerializer)serializer).EmitCreateInstance(ctx); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("Merge")); + ctx.Cast(expected); + ctx.StoreValue(loc); // Merge always returns a value + + // nothing needs doing + ctx.MarkLabel(allDone); + } + + if (Helpers.IsValueType(serType)) + { + Compiler.CodeLabel initValue = ctx.DefineLabel(); + Compiler.CodeLabel hasValue = ctx.DefineLabel(); + using (Compiler.Local emptyValue = new Compiler.Local(ctx, serType)) + { + ctx.LoadValue(loc); + ctx.BranchIfFalse(initValue, false); + + ctx.LoadValue(loc); + ctx.CastFromObject(serType); + ctx.Branch(hasValue, false); + + ctx.MarkLabel(initValue); + ctx.InitLocal(serType, emptyValue); + ctx.LoadValue(emptyValue); + + ctx.MarkLabel(hasValue); + } + } + else + { + ctx.LoadValue(loc); + ctx.Cast(serType); + } + + serializer.EmitRead(ctx, null); + + } + + if (serializer.ReturnsValue) + { // update the variable + if (Helpers.IsValueType(serType)) + { + // but box it first in case of value type + ctx.CastToObject(serType); + } + ctx.StoreValue(loc); + } + ctx.Branch(@continue, false); // "continue" + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + // different ways of creating a new instance + bool callNoteObject = true; + if (factory != null) + { + EmitInvokeCallback(ctx, factory, false, constructType, forType); + } + else if (!useConstructor) + { // DataContractSerializer style + ctx.LoadValue(constructType); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("GetUninitializedObject")); + ctx.Cast(forType); + } + else if (Helpers.IsClass(constructType) && hasConstructor) + { // XmlSerializer style + ctx.EmitCtor(constructType); + } + else + { + ctx.LoadValue(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowCannotCreateInstance", + BindingFlags.Static | BindingFlags.Public)); + ctx.LoadNullRef(); + callNoteObject = false; + } + if (callNoteObject) + { + // track root object creation + ctx.CopyValue(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("NoteObject", + BindingFlags.Static | BindingFlags.Public)); + } + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + EmitInvokeCallback(ctx, baseCtorCallbacks[i], true, null, forType); + } + } + } + private void EmitCreateIfNull(Compiler.CompilerContext ctx, Compiler.Local storage) + { + Helpers.DebugAssert(storage != null); + if (!Helpers.IsValueType(ExpectedType)) + { + Compiler.CodeLabel afterNullCheck = ctx.DefineLabel(); + ctx.LoadValue(storage); + ctx.BranchIfTrue(afterNullCheck, false); + + ((IProtoTypeSerializer)this).EmitCreateInstance(ctx); + + if (callbacks != null) EmitInvokeCallback(ctx, callbacks.BeforeDeserialize, true, null, forType); + ctx.StoreValue(storage); + ctx.MarkLabel(afterNullCheck); + } + } +#endif + } + +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta new file mode 100644 index 0000000..b8303ec --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 77e0f152f69b38c4298afd4032ed7bd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs new file mode 100644 index 0000000..ff9f89b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + class UInt16Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(ushort); + + public UInt16Serializer(ProtoBuf.Meta.TypeModel model) + { + } + + public virtual Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public virtual object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt16(); + } + + public virtual void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((ushort)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt16", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt16", ctx.MapType(typeof(ushort))); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta new file mode 100644 index 0000000..0bbf0b0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39621eeb2867dea4faee2a999ed61721 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs new file mode 100644 index 0000000..08b4f4b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class UInt32Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(uint); + + public UInt32Serializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt32((uint)value, dest); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt32", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt32", ctx.MapType(typeof(uint))); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta new file mode 100644 index 0000000..7de4f8e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c882761e4681784b9f317fe9ac99a21 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs new file mode 100644 index 0000000..8577edd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class UInt64Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(ulong); + + public UInt64Serializer(ProtoBuf.Meta.TypeModel model) + { + + } + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt64((ulong)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt64", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt64", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta new file mode 100644 index 0000000..9e267f1 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c94ec7745e5d33e41820dc1bf97965ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs new file mode 100644 index 0000000..d34ac2d --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs @@ -0,0 +1,62 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +#if FEAT_COMPILER +using ProtoBuf.Compiler; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class UriDecorator : ProtoDecoratorBase + { + static readonly Type expectedType = typeof(Uri); + public UriDecorator(ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail) + { + + } + + public override Type ExpectedType => expectedType; + + public override bool RequiresOldValue => false; + + public override bool ReturnsValue => true; + + public override void Write(object value, ProtoWriter dest) + { + Tail.Write(((Uri)value).OriginalString, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // not expecting incoming + string s = (string)Tail.Read(null, source); + return s.Length == 0 ? null : new Uri(s, UriKind.RelativeOrAbsolute); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.LoadValue(typeof(Uri).GetProperty("OriginalString")); + Tail.EmitWrite(ctx, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + ctx.CopyValue(); + Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); + ctx.LoadValue(typeof(string).GetProperty("Length")); + ctx.BranchIfTrue(@nonEmpty, true); + ctx.DiscardValue(); + ctx.LoadNullRef(); + ctx.Branch(@end, true); + ctx.MarkLabel(@nonEmpty); + ctx.LoadValue((int)UriKind.RelativeOrAbsolute); + ctx.EmitCtor(ctx.MapType(typeof(Uri)), ctx.MapType(typeof(string)), ctx.MapType(typeof(UriKind))); + ctx.MarkLabel(@end); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta new file mode 100644 index 0000000..d6dbcf2 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1641fcd6b5ca2ba459095863b2a536b1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel.meta new file mode 100644 index 0000000..4639238 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dd592340222bc254b9c36921de63aec8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs new file mode 100644 index 0000000..928207e --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs @@ -0,0 +1,35 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.ServiceModel.Channels; +using System.ServiceModel.Description; +using System.ServiceModel.Dispatcher; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Uses protocol buffer serialization on the specified operation; note that this + /// must be enabled on both the client and server. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public sealed class ProtoBehaviorAttribute : Attribute, IOperationBehavior + { + void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) + { } + + void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) + { + IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); + innerBehavior.ApplyClientBehavior(operationDescription, clientOperation); + } + + void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) + { + IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); + innerBehavior.ApplyDispatchBehavior(operationDescription, dispatchOperation); + } + + void IOperationBehavior.Validate(OperationDescription operationDescription) + { } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta new file mode 100644 index 0000000..d47e982 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e0c23ab9adeb0bd468e11167635e89bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs new file mode 100644 index 0000000..56edb79 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs @@ -0,0 +1,29 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER && FEAT_SERVICECONFIGMODEL +using System; +using System.ServiceModel.Configuration; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Configuration element to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. + /// + /// + public class ProtoBehaviorExtension : BehaviorExtensionElement + { + /// + /// Creates a new ProtoBehaviorExtension instance. + /// + public ProtoBehaviorExtension() { } + /// + /// Gets the type of behavior. + /// + public override Type BehaviorType => typeof(ProtoEndpointBehavior); + + /// + /// Creates a behavior extension based on the current configuration settings. + /// + /// The behavior extension. + protected override object CreateBehavior() => new ProtoEndpointBehavior(); + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta new file mode 100644 index 0000000..448ddbd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d2afc1b26f215bd4a9df96a12b2c0197 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs new file mode 100644 index 0000000..9bcfb99 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs @@ -0,0 +1,82 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System.ServiceModel.Description; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Behavior to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. + /// + /// Add the following to the server and client app.config in the system.serviceModel section: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Configure your endpoints to have a behaviorConfiguration as follows: + /// + /// + /// + /// + /// + /// + /// + /// + /// + public class ProtoEndpointBehavior : IEndpointBehavior + { + #region IEndpointBehavior Members + + void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) + { + } + + void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.Validate(ServiceEndpoint endpoint) + { + } + + private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint) + { + foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations) + { + ReplaceDataContractSerializerOperationBehavior(operationDescription); + } + } + + private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description) + { + DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find(); + if (dcsOperationBehavior != null) + { + description.Behaviors.Remove(dcsOperationBehavior); + + ProtoOperationBehavior newBehavior = new ProtoOperationBehavior(description); + newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph; + description.Behaviors.Add(newBehavior); + } + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta new file mode 100644 index 0000000..8023379 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f636dc4ac0282304481b5d051d7a239d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs new file mode 100644 index 0000000..9d5f02c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs @@ -0,0 +1,52 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.ServiceModel.Description; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Describes a WCF operation behaviour that can perform protobuf serialization + /// + public sealed class ProtoOperationBehavior : DataContractSerializerOperationBehavior + { + private TypeModel model; + + /// + /// Create a new ProtoOperationBehavior instance + /// + public ProtoOperationBehavior(OperationDescription operation) : base(operation) + { +#if !NO_RUNTIME + model = RuntimeTypeModel.Default; +#endif + } + + /// + /// The type-model that should be used with this behaviour + /// + public TypeModel Model + { + get { return model; } + set + { + model = value ?? throw new ArgumentNullException(nameof(value)); + } + } + + //public ProtoOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormat) : base(operation, dataContractFormat) { } + + /// + /// Creates a protobuf serializer if possible (falling back to the default WCF serializer) + /// + public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) + { + if (model == null) throw new InvalidOperationException("No Model instance has been assigned to the ProtoOperationBehavior"); + return XmlProtoSerializer.TryCreate(model, type) ?? base.CreateSerializer(type, name, ns, knownTypes); + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta new file mode 100644 index 0000000..5ebe67c --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0ad90e4c382348647a42746b51b80ea4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs new file mode 100644 index 0000000..23959ea --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs @@ -0,0 +1,208 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel +{ + /// + /// An xml object serializer that can embed protobuf data in a base-64 hunk (looking like a byte[]) + /// + public sealed class XmlProtoSerializer : XmlObjectSerializer + { + private readonly TypeModel model; + private readonly int key; + private readonly bool isList, isEnum; + private readonly Type type; + internal XmlProtoSerializer(TypeModel model, int key, Type type, bool isList) + { + if (key < 0) throw new ArgumentOutOfRangeException(nameof(key)); + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.key = key; + this.isList = isList; + this.type = type ?? throw new ArgumentOutOfRangeException(nameof(type)); + this.isEnum = Helpers.IsEnum(type); + } + /// + /// Attempt to create a new serializer for the given model and type + /// + /// A new serializer instance if the type is recognised by the model; null otherwise + public static XmlProtoSerializer TryCreate(TypeModel model, Type type) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + if (type == null) throw new ArgumentNullException(nameof(type)); + + int key = GetKey(model, ref type, out bool isList); + if (key >= 0) + { + return new XmlProtoSerializer(model, key, type, isList); + } + return null; + } + + /// + /// Creates a new serializer for the given model and type + /// + public XmlProtoSerializer(TypeModel model, Type type) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + if (type == null) throw new ArgumentNullException(nameof(type)); + + key = GetKey(model, ref type, out isList); + this.model = model; + this.type = type; + this.isEnum = Helpers.IsEnum(type); + if (key < 0) throw new ArgumentOutOfRangeException(nameof(type), "Type not recognised by the model: " + type.FullName); + } + + static int GetKey(TypeModel model, ref Type type, out bool isList) + { + if (model != null && type != null) + { + int key = model.GetKey(ref type); + if (key >= 0) + { + isList = false; + return key; + } + Type itemType = TypeModel.GetListItemType(model, type); + if (itemType != null) + { + key = model.GetKey(ref itemType); + if (key >= 0) + { + isList = true; + return key; + } + } + } + + isList = false; + return -1; + } + + /// + /// Ends an object in the output + /// + public override void WriteEndObject(XmlDictionaryWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.WriteEndElement(); + } + + /// + /// Begins an object in the output + /// + public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.WriteStartElement(PROTO_ELEMENT); + } + + private const string PROTO_ELEMENT = "proto"; + + /// + /// Writes the body of an object in the output + /// + public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + if (graph == null) + { + writer.WriteAttributeString("nil", "true"); + } + else + { + using (MemoryStream ms = new MemoryStream()) + { + if (isList) + { + model.Serialize(ms, graph, null); + } + else + { + using (ProtoWriter protoWriter = ProtoWriter.Create(ms, model, null)) + { + model.Serialize(key, graph, protoWriter); + } + } + byte[] buffer = ms.GetBuffer(); + writer.WriteBase64(buffer, 0, (int)ms.Length); + } + } + } + + /// + /// Indicates whether this is the start of an object we are prepared to handle + /// + public override bool IsStartObject(XmlDictionaryReader reader) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + reader.MoveToContent(); + return reader.NodeType == XmlNodeType.Element && reader.Name == PROTO_ELEMENT; + } + + /// + /// Reads the body of an object + /// + public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + reader.MoveToContent(); + bool isSelfClosed = reader.IsEmptyElement, isNil = reader.GetAttribute("nil") == "true"; + reader.ReadStartElement(PROTO_ELEMENT); + + // explicitly null + if (isNil) + { + if (!isSelfClosed) reader.ReadEndElement(); + return null; + } + if (isSelfClosed) // no real content + { + if (isList || isEnum) + { + return model.Deserialize(Stream.Null, null, type, null); + } + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(Stream.Null, model, null, ProtoReader.TO_EOF); + return model.Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + + object result; + Helpers.DebugAssert(reader.CanReadBinaryContent, "CanReadBinaryContent"); + using (MemoryStream ms = new MemoryStream(reader.ReadContentAsBase64())) + { + if (isList || isEnum) + { + result = model.Deserialize(ms, null, type, null); + } + else + { + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(ms, model, null, ProtoReader.TO_EOF); + result = model.Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + } + reader.ReadEndElement(); + return result; + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta new file mode 100644 index 0000000..a666154 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a0fba5cf667a9a419ea1e565f632511 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs new file mode 100644 index 0000000..51f4a24 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs @@ -0,0 +1,16 @@ + +using System; + +namespace ProtoBuf +{ + /// + /// Used to hold particulars relating to nested objects. This is opaque to the caller - simply + /// give back the token you are given at the end of an object. + /// + public readonly struct SubItemToken + { + internal readonly long value64; + internal SubItemToken(int value) => value64 = value; + internal SubItemToken(long value) => value64 = value; + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs.meta new file mode 100644 index 0000000..29fd4e7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/SubItemToken.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 668d54e05e7dbff4c8d2d4d89a07732e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs b/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs new file mode 100644 index 0000000..ab4fa20 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs @@ -0,0 +1,50 @@ +namespace ProtoBuf +{ + /// + /// Indicates the encoding used to represent an individual value in a protobuf stream + /// + public enum WireType + { + /// + /// Represents an error condition + /// + None = -1, + + /// + /// Base-128 variant-length encoding + /// + Variant = 0, + + /// + /// Fixed-length 8-byte encoding + /// + Fixed64 = 1, + + /// + /// Length-variant-prefixed encoding + /// + String = 2, + + /// + /// Indicates the start of a group + /// + StartGroup = 3, + + /// + /// Indicates the end of a group + /// + EndGroup = 4, + + /// + /// Fixed-length 4-byte encoding + /// 10 + Fixed32 = 5, + + /// + /// This is not a formal wire-type in the "protocol buffers" spec, but + /// denotes a variant integer that should be interpreted using + /// zig-zag semantics (so -ve numbers aren't a significant overhead) + /// + SignedVariant = WireType.Variant | (1 << 3), + } +} diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs.meta new file mode 100644 index 0000000..22788f9 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/WireType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2fe968c877a404746a67b87376136538 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj b/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj new file mode 100644 index 0000000..e72f4ab --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj @@ -0,0 +1,86 @@ + + + protobuf-net + protobuf-net + Provides simple access to fast and efficient "Protocol Buffers" serialization from .NET applications + net20;net35;net452;netstandard2.0;netcoreapp3.1 + true + EMIT_ASSEMBLY_INFO + + True + + + net + true + true + true + true + true + Debug;Release;VS + + + + false + + + false + false + false + false + $(DefineConstants);COREFX;UAP + + + $(DefineConstants);COREFX + standard + true + false + + + $(DefineConstants);COREFX + none + true + false + + + + $(DefineConstants);FEAT_COMPILER + + + $(DefineConstants);FEAT_SERVICEMODEL + + + $(DefineConstants);FEAT_SERVICECONFIGMODEL + + + $(DefineConstants);PLAT_XMLSERIALIZER + + + $(DefineConstants);PLAT_BINARYFORMATTER + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj.meta b/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj.meta new file mode 100644 index 0000000..b3bc6c7 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/Protobuf-net/protobuf-net.csproj.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b8be8b4c6d5c36843bc4377598ffe93e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket.meta b/Runtime/CoreRuntime/Plugins/WSocket.meta new file mode 100644 index 0000000..4214227 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f74eeb18724b4dc44ab5b038b786c614 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core.meta new file mode 100644 index 0000000..7f58768 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f81d46b7279cc8469b21731ef0c5eb0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs new file mode 100644 index 0000000..d0d5831 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs @@ -0,0 +1,89 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// Represents the event data for the event. + /// + /// + /// + /// That event occurs when the WebSocket connection has been closed. + /// + /// + /// If you would like to get the reason for the close, you should access + /// the or property. + /// + /// + public class CloseEventArgs : EventArgs + { + #region Internal Constructors + + internal CloseEventArgs() + { + } + + internal CloseEventArgs(ushort code) + : this(code, null) + { + } + + internal CloseEventArgs(CloseStatusCode code) + : this((ushort)code, null) + { + } + + internal CloseEventArgs(CloseStatusCode code, string reason) + : this((ushort)code, reason) + { + } + + internal CloseEventArgs(ushort code, string reason) + { + Code = code; + Reason = reason; + } + + #endregion + + #region Public Properties + + /// + /// Gets the status code for the close. + /// + /// + /// A that represents the status code for the close if any. + /// + public ushort Code { get; private set; } + + /// + /// Gets the reason for the close. + /// + /// + /// A that represents the reason for the close if any. + /// + public string Reason { get; private set; } + + /// + /// Gets a value indicating whether the connection has been closed cleanly. + /// + /// + /// true if the connection has been closed cleanly; otherwise, false. + /// + public bool WasClean { get; internal set; } + + /// + /// Enum value same as Code + /// + public CloseStatusCode StatusCode + { + get + { + if (Enum.IsDefined(typeof(CloseStatusCode), Code)) + return (CloseStatusCode)Code; + return CloseStatusCode.Unknown; + } + } + + #endregion + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs.meta new file mode 100644 index 0000000..f57f0ba --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e32213bffb4d6c40bc7cb0b951438fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs new file mode 100644 index 0000000..0da2ddb --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs @@ -0,0 +1,91 @@ +namespace UnityWebSocket +{ + /// + /// Indicates the status code for the WebSocket connection close. + /// + /// + /// + /// The values of this enumeration are defined in + /// + /// Section 7.4 of RFC 6455. + /// + /// + /// "Reserved value" cannot be sent as a status code in + /// closing handshake by an endpoint. + /// + /// + public enum CloseStatusCode : ushort + { + Unknown = 65534, + /// + /// Equivalent to close status 1000. Indicates normal close. + /// + Normal = 1000, + /// + /// Equivalent to close status 1001. Indicates that an endpoint is + /// going away. + /// + Away = 1001, + /// + /// Equivalent to close status 1002. Indicates that an endpoint is + /// terminating the connection due to a protocol error. + /// + ProtocolError = 1002, + /// + /// Equivalent to close status 1003. Indicates that an endpoint is + /// terminating the connection because it has received a type of + /// data that it cannot accept. + /// + UnsupportedData = 1003, + /// + /// Equivalent to close status 1004. Still undefined. A Reserved value. + /// + Undefined = 1004, + /// + /// Equivalent to close status 1005. Indicates that no status code was + /// actually present. A Reserved value. + /// + NoStatus = 1005, + /// + /// Equivalent to close status 1006. Indicates that the connection was + /// closed abnormally. A Reserved value. + /// + Abnormal = 1006, + /// + /// Equivalent to close status 1007. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// contains data that is not consistent with the type of the message. + /// + InvalidData = 1007, + /// + /// Equivalent to close status 1008. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// violates its policy. + /// + PolicyViolation = 1008, + /// + /// Equivalent to close status 1009. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// is too big to process. + /// + TooBig = 1009, + /// + /// Equivalent to close status 1010. Indicates that a client is + /// terminating the connection because it has expected the server to + /// negotiate one or more extension, but the server did not return + /// them in the handshake response. + /// + MandatoryExtension = 1010, + /// + /// Equivalent to close status 1011. Indicates that a server is + /// terminating the connection because it has encountered an unexpected + /// condition that prevented it from fulfilling the request. + /// + ServerError = 1011, + /// + /// Equivalent to close status 1015. Indicates that the connection was + /// closed due to a failure to perform a TLS handshake. A Reserved value. + /// + TlsHandshakeFailure = 1015, + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs.meta new file mode 100644 index 0000000..d94e1b5 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/CloseStatusCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d7a0288af399ef4f898fd1987c939d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs new file mode 100644 index 0000000..cfb91b8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs @@ -0,0 +1,59 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// Represents the event data for the event. + /// + /// + /// + /// That event occurs when the gets an error. + /// + /// + /// If you would like to get the error message, you should access + /// the property. + /// + /// + /// And if the error is due to an exception, you can get it by accessing + /// the property. + /// + /// + public class ErrorEventArgs : EventArgs + { + #region Internal Constructors + + internal ErrorEventArgs(string message) + : this(message, null) + { + } + + internal ErrorEventArgs(string message, Exception exception) + { + this.Message = message; + this.Exception = exception; + } + + #endregion + + #region Public Properties + + /// + /// Gets the exception that caused the error. + /// + /// + /// An instance that represents the cause of + /// the error if it is due to an exception; otherwise, . + /// + public Exception Exception { get; private set; } + + /// + /// Gets the error message. + /// + /// + /// A that represents the error message. + /// + public string Message { get; private set; } + + #endregion + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta new file mode 100644 index 0000000..c03eb67 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e8923bad3b03d34daaf4661e8c6b161 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs new file mode 100644 index 0000000..3e08d4b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs @@ -0,0 +1,143 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// IWebSocket indicate a network connection. + /// It can be connecting, connected, closing or closed state. + /// You can send and receive messages by using it. + /// Register callbacks for handling messages. + /// ----------------------------------------------------------- + /// IWebSocket 表示一个网络连接, + /// 它可以是 connecting connected closing closed 状态, + /// 可以发送和接收消息, + /// 通过注册消息回调,来处理接收到的消息。 + /// + public interface IWebSocket + { + /// + /// Establishes a connection asynchronously. + /// + /// + /// + /// This method does not wait for the connect process to be complete. + /// + /// + /// This method does nothing if the connection has already been + /// established. + /// + /// + /// + /// + /// This instance is not a client. + /// + /// + /// -or- + /// + /// + /// The close process is in progress. + /// + /// + /// -or- + /// + /// + /// A series of reconnecting has failed. + /// + /// + void ConnectAsync(); + + /// + /// Closes the connection asynchronously. + /// + /// + /// + /// This method does not wait for the close to be complete. + /// + /// + /// This method does nothing if the current state of the connection is + /// Closing or Closed. + /// + /// + void CloseAsync(); + + /// + /// Sends the specified data asynchronously using the WebSocket connection. + /// + /// + /// This method does not wait for the send to be complete. + /// + /// + /// An array of that represents the binary data to send. + /// + /// + /// The current state of the connection is not Open. + /// + /// + /// is . + /// + void SendAsync(byte[] data); + + /// + /// Sends the specified data using the WebSocket connection. + /// + /// + /// A that represents the text data to send. + /// + /// + /// The current state of the connection is not Open. + /// + /// + /// is . + /// + /// + /// could not be UTF-8 encoded. + /// + void SendAsync(string text); + + /// + /// get the address which to connect. + /// + string Address { get; } + + /// + /// get sub protocols . + /// + string[] SubProtocols { get; } + + /// + /// Gets the current state of the connection. + /// + /// + /// + /// One of the enum values. + /// + /// + /// It indicates the current state of the connection. + /// + /// + /// The default value is . + /// + /// + WebSocketState ReadyState { get; } + + /// + /// Occurs when the WebSocket connection has been established. + /// + event EventHandler OnOpen; + + /// + /// Occurs when the WebSocket connection has been closed. + /// + event EventHandler OnClose; + + /// + /// Occurs when the gets an error. + /// + event EventHandler OnError; + + /// + /// Occurs when the receives a message. + /// + event EventHandler OnMessage; + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs.meta new file mode 100644 index 0000000..9db37a3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/IWebSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f5a93fa42e6bd54a9112feffd1e1452 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs new file mode 100644 index 0000000..a80fbae --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs @@ -0,0 +1,115 @@ +using System; +using System.Text; + +namespace UnityWebSocket +{ + public class MessageEventArgs : EventArgs + { + private byte[] _rawData; + private string _data; + + internal MessageEventArgs(Opcode opcode, byte[] rawData) + { + Opcode = opcode; + _rawData = rawData; + } + + internal MessageEventArgs(Opcode opcode, string data) + { + Opcode = opcode; + _data = data; + } + + /// + /// Gets the opcode for the message. + /// + /// + /// , . + /// + internal Opcode Opcode { get; private set; } + + /// + /// Gets the message data as a . + /// + /// + /// A that represents the message data if its type is + /// text and if decoding it to a string has successfully done; + /// otherwise, . + /// + public string Data + { + get + { + SetData(); + return _data; + } + } + + /// + /// Gets the message data as an array of . + /// + /// + /// An array of that represents the message data. + /// + public byte[] RawData + { + get + { + SetRawData(); + return _rawData; + } + } + + /// + /// Gets a value indicating whether the message type is binary. + /// + /// + /// true if the message type is binary; otherwise, false. + /// + public bool IsBinary + { + get + { + return Opcode == Opcode.Binary; + } + } + + /// + /// Gets a value indicating whether the message type is text. + /// + /// + /// true if the message type is text; otherwise, false. + /// + public bool IsText + { + get + { + return Opcode == Opcode.Text; + } + } + + private void SetData() + { + if (_data != null) return; + + if (RawData == null) + { + return; + } + + _data = Encoding.UTF8.GetString(RawData); + } + + private void SetRawData() + { + if (_rawData != null) return; + + if (_data == null) + { + return; + } + + _rawData = Encoding.UTF8.GetBytes(_data); + } + } +} \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs.meta new file mode 100644 index 0000000..9683f45 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/MessageEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dedd92d29555b11449fa6917168da1ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs new file mode 100644 index 0000000..3e758e2 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs @@ -0,0 +1,26 @@ +namespace UnityWebSocket +{ + /// + /// Indicates the WebSocket frame type. + /// + /// + /// The values of this enumeration are defined in + /// + /// Section 5.2 of RFC 6455. + /// + public enum Opcode : byte + { + /// + /// Equivalent to numeric value 1. Indicates text frame. + /// + Text = 0x1, + /// + /// Equivalent to numeric value 2. Indicates binary frame. + /// + Binary = 0x2, + /// + /// Equivalent to numeric value 8. Indicates connection close frame. + /// + Close = 0x8, + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs.meta new file mode 100644 index 0000000..18db2dd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/Opcode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 33623d31a88ba74428689bea4f551635 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs new file mode 100644 index 0000000..fa84a33 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs @@ -0,0 +1,11 @@ +using System; + +namespace UnityWebSocket +{ + public class OpenEventArgs : EventArgs + { + internal OpenEventArgs() + { + } + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs.meta new file mode 100644 index 0000000..193fe35 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/OpenEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 47b7beb73d16b8b478d1b94d172f60cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs new file mode 100644 index 0000000..f1646c5 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs @@ -0,0 +1,12 @@ +namespace UnityWebSocket +{ + public static class Settings + { + public const string GITHUB = "https://github.com/psygames/UnityWebSocket"; + public const string QQ_GROUP = "1126457634"; + public const string QQ_GROUP_LINK = "https://qm.qq.com/cgi-bin/qm/qr?k=KcexYJ9aYwogFXbj2aN0XHH5b2G7ICmd"; + public const string EMAIL = "799329256@qq.com"; + public const string AUHTOR = "psygames"; + public const string VERSION = "2.8.6"; + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs.meta new file mode 100644 index 0000000..728f26a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/Settings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88b6ad844adc3ea44a9d0ba8ce04219d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs b/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs new file mode 100644 index 0000000..796ab15 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs @@ -0,0 +1,36 @@ +namespace UnityWebSocket +{ + /// + /// Reference html5 WebSocket ReadyState Properties + /// Indicates the state of a WebSocket connection. + /// + /// + /// The values of this enumeration are defined in + /// + /// The WebSocket API. + /// + public enum WebSocketState : ushort + { + /// + /// Equivalent to numeric value 0. Indicates that the connection has not + /// yet been established. + /// + Connecting = 0, + /// + /// Equivalent to numeric value 1. Indicates that the connection has + /// been established, and the communication is possible. + /// + Open = 1, + /// + /// Equivalent to numeric value 2. Indicates that the connection is + /// going through the closing handshake, or the close method has + /// been invoked. + /// + Closing = 2, + /// + /// Equivalent to numeric value 3. Indicates that the connection has + /// been closed or could not be established. + /// + Closed = 3 + } +} diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs.meta new file mode 100644 index 0000000..a19ab05 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Core/WebSocketState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f6accf1bead42f4faa1a8f6a1fc9d45 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation.meta new file mode 100644 index 0000000..f5edc87 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d9045a04ae6cea043af1e284e4391c7c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL.meta new file mode 100644 index 0000000..e18646b --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 68465a6da7c684e4d9843900e57919ba +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs new file mode 100644 index 0000000..3054734 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs @@ -0,0 +1,345 @@ +#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL) +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Net.WebSockets; +using System.IO; +using System.Collections.Concurrent; + +namespace UnityWebSocket +{ + public class WebSocket : IWebSocket + { + public string Address { get; private set; } + public string[] SubProtocols { get; private set; } + + public WebSocketState ReadyState + { + get + { + if (socket == null) + return WebSocketState.Closed; + switch (socket.State) + { + case System.Net.WebSockets.WebSocketState.Closed: + case System.Net.WebSockets.WebSocketState.None: + return WebSocketState.Closed; + case System.Net.WebSockets.WebSocketState.CloseReceived: + case System.Net.WebSockets.WebSocketState.CloseSent: + return WebSocketState.Closing; + case System.Net.WebSockets.WebSocketState.Connecting: + return WebSocketState.Connecting; + case System.Net.WebSockets.WebSocketState.Open: + return WebSocketState.Open; + } + return WebSocketState.Closed; + } + } + + public event EventHandler OnOpen; + public event EventHandler OnClose; + public event EventHandler OnError; + public event EventHandler OnMessage; + + private ClientWebSocket socket; + private bool isOpening => socket != null && socket.State == System.Net.WebSockets.WebSocketState.Open; + private ConcurrentQueue sendQueue = new ConcurrentQueue(); + private ConcurrentQueue eventQueue = new ConcurrentQueue(); + private bool closeProcessing; + private CancellationTokenSource cts = null; + + #region APIs + public WebSocket(string address) + { + this.Address = address; + } + + public WebSocket(string address, string subProtocol) + { + this.Address = address; + this.SubProtocols = new string[] { subProtocol }; + } + + public WebSocket(string address, string[] subProtocols) + { + this.Address = address; + this.SubProtocols = subProtocols; + } + + public void ConnectAsync() + { + if (socket != null) + { + HandleError(new Exception("Socket is busy.")); + return; + } + + WebSocketManager.Instance.Add(this); + + socket = new ClientWebSocket(); + cts = new CancellationTokenSource(); + + // support sub protocols + if (this.SubProtocols != null) + { + foreach (var protocol in this.SubProtocols) + { + if (string.IsNullOrEmpty(protocol)) continue; + Log($"Add Sub Protocol {protocol}"); + socket.Options.AddSubProtocol(protocol); + } + } + + Task.Run(ConnectTask); + } + + public void CloseAsync() + { + if (!isOpening) + { + return; + } + + closeProcessing = true; + } + + public void SendAsync(byte[] data, int offset, int len) + { + if (!isOpening) return; + var buffer = new SendBuffer(data, offset, len, WebSocketMessageType.Binary); + sendQueue.Enqueue(buffer); + } + + public void SendAsync(byte[] data) + { + if (!isOpening) return; + var buffer = new SendBuffer(data, 0, data.Length, WebSocketMessageType.Binary); + sendQueue.Enqueue(buffer); + } + + public void SendAsync(string text) + { + if (!isOpening) return; + var data = Encoding.UTF8.GetBytes(text); + var buffer = new SendBuffer(data, 0, data.Length, WebSocketMessageType.Text); + sendQueue.Enqueue(buffer); + } + #endregion + + class SendBuffer + { + public int offset; + public int len; + public byte[] data; + public WebSocketMessageType type; + public SendBuffer(byte[] data, int offset, int len, WebSocketMessageType type) + { + this.offset = offset; + this.len = len; + this.data = data; + this.type = type; + } + } + + private void CleanSendQueue() + { + while (sendQueue.TryDequeue(out var _)) ; + } + + private void CleanEventQueue() + { + while (eventQueue.TryDequeue(out var _)) ; + } + + private async Task ConnectTask() + { + Log("Connect Task Begin ..."); + + try + { + var uri = new Uri(Address); + await socket.ConnectAsync(uri, cts.Token); + } + catch (Exception e) + { + HandleError(e); + HandleClose((ushort)CloseStatusCode.Abnormal, e.Message); + return; + } + + HandleOpen(); + + Log("Connect Task Success !"); + + StartReceiveTask(); + StartSendTask(); + } + + private async void StartSendTask() + { + Log("Send Task Begin ..."); + + try + { + while (!closeProcessing && socket != null && cts != null && !cts.IsCancellationRequested) + { + while (!closeProcessing && sendQueue.Count > 0 && sendQueue.TryDequeue(out var buffer)) + { + Log($"Send, type: {buffer.type}, size: {buffer.data.Length}, queue left: {sendQueue.Count}"); + await socket.SendAsync(new ArraySegment(buffer.data,buffer.offset, buffer.len), buffer.type, true, cts.Token); + } + Thread.Sleep(3); + } + + if (closeProcessing && socket != null && cts != null && !cts.IsCancellationRequested) + { + CleanSendQueue(); + Log($"Close Send Begin ..."); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", cts.Token); + Log($"Close Send Success !"); + } + } + catch (Exception e) + { + HandleError(e); + } + finally + { + closeProcessing = false; + } + + Log("Send Task End !"); + } + + private async void StartReceiveTask() + { + Log("Receive Task Begin ..."); + + string closeReason = ""; + ushort closeCode = 0; + bool isClosed = false; + var segment = new ArraySegment(new byte[8192]); + var ms = new MemoryStream(); + + try + { + while (!isClosed && !cts.IsCancellationRequested) + { + var result = await socket.ReceiveAsync(segment, cts.Token); + ms.Write(segment.Array, 0, result.Count); + if (!result.EndOfMessage) continue; + var data = ms.ToArray(); + ms.SetLength(0); + switch (result.MessageType) + { + case WebSocketMessageType.Binary: + HandleMessage(Opcode.Binary, data); + break; + case WebSocketMessageType.Text: + HandleMessage(Opcode.Text, data); + break; + case WebSocketMessageType.Close: + isClosed = true; + closeCode = (ushort)result.CloseStatus; + closeReason = result.CloseStatusDescription; + break; + } + } + } + catch (Exception e) + { + HandleError(e); + closeCode = (ushort)CloseStatusCode.Abnormal; + closeReason = e.Message; + } + finally + { + ms.Close(); + } + + HandleClose(closeCode, closeReason); + + Log("Receive Task End !"); + } + + private void SocketDispose() + { + Log("Dispose"); + WebSocketManager.Instance.Remove(this); + CleanSendQueue(); + CleanEventQueue(); + socket.Dispose(); + socket = null; + cts.Dispose(); + cts = null; + } + + private void HandleOpen() + { + Log("OnOpen"); + eventQueue.Enqueue(new OpenEventArgs()); + } + + private void HandleMessage(Opcode opcode, byte[] rawData) + { + Log($"OnMessage, type: {opcode}, size: {rawData.Length}"); + eventQueue.Enqueue(new MessageEventArgs(opcode, rawData)); + } + + private void HandleClose(ushort code, string reason) + { + Log($"OnClose, code: {code}, reason: {reason}"); + eventQueue.Enqueue(new CloseEventArgs(code, reason)); + } + + private void HandleError(Exception exception) + { + Log("OnError, error: " + exception.Message); + eventQueue.Enqueue(new ErrorEventArgs(exception.Message)); + } + + internal void Update() + { + while (eventQueue.Count > 0 && eventQueue.TryDequeue(out var e)) + { + if (e is CloseEventArgs) + { + OnClose?.Invoke(this, e as CloseEventArgs); + SocketDispose(); + break; + } + else if (e is OpenEventArgs) + { + OnOpen?.Invoke(this, e as OpenEventArgs); + } + else if (e is MessageEventArgs) + { + OnMessage?.Invoke(this, e as MessageEventArgs); + } + else if (e is ErrorEventArgs) + { + OnError?.Invoke(this, e as ErrorEventArgs); + } + } + } + + internal void Abort() + { + Log("Abort"); + if (cts != null) + { + cts.Cancel(); + } + } + + [System.Diagnostics.Conditional("UNITY_WEB_SOCKET_LOG")] + static void Log(string msg) + { + var time = DateTime.Now.ToString("HH:mm:ss.fff"); + var thread = Thread.CurrentThread.ManagedThreadId; + UnityEngine.Debug.Log($"[{time}][UnityWebSocket][T-{thread:D3}] {msg}"); + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta new file mode 100644 index 0000000..44c60d8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78e0760e4e77c9d4893acfd4e21b76a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs new file mode 100644 index 0000000..e3f82bd --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs @@ -0,0 +1,72 @@ +#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL) +using System.Collections.Generic; +using UnityEngine; + +namespace UnityWebSocket +{ + [DisallowMultipleComponent] + [DefaultExecutionOrder(-10000)] + internal class WebSocketManager : MonoBehaviour + { + private const string rootName = "[UnityWebSocket]"; + private static WebSocketManager _instance; + public static WebSocketManager Instance + { + get + { + if (!_instance) CreateInstance(); + return _instance; + } + } + + private void Awake() + { + DontDestroyOnLoad(gameObject); + } + + public static void CreateInstance() + { + GameObject go = GameObject.Find("/" + rootName); + if (!go) go = new GameObject(rootName); + _instance = go.GetComponent(); + if (!_instance) _instance = go.AddComponent(); + } + + private readonly List sockets = new List(); + + public void Add(WebSocket socket) + { + if (!sockets.Contains(socket)) + sockets.Add(socket); + } + + public void Remove(WebSocket socket) + { + if (sockets.Contains(socket)) + sockets.Remove(socket); + } + + private void Update() + { + if (sockets.Count <= 0) return; + for (int i = sockets.Count - 1; i >= 0; i--) + { + sockets[i].Update(); + } + } + + private void OnDisable() + { + SocketAbort(); + } + + private void SocketAbort() + { + for (int i = sockets.Count - 1; i >= 0; i--) + { + sockets[i].Abort(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta new file mode 100644 index 0000000..1b480f0 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a1a5b567e69a22747b7641901136485c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL.meta new file mode 100644 index 0000000..38db7bf --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2685c7806309d464e89a59cdcb591edf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs new file mode 100644 index 0000000..59a98b8 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs @@ -0,0 +1,154 @@ +#if !UNITY_EDITOR && UNITY_WEBGL +using System; + +namespace UnityWebSocket +{ + public class WebSocket : IWebSocket + { + public string Address { get; private set; } + public string[] SubProtocols { get; private set; } + public WebSocketState ReadyState { get { return (WebSocketState)WebSocketManager.WebSocketGetState(instanceId); } } + + public event EventHandler OnOpen; + public event EventHandler OnClose; + public event EventHandler OnError; + public event EventHandler OnMessage; + + internal int instanceId = 0; + + public WebSocket(string address) + { + this.Address = address; + AllocateInstance(); + } + + public WebSocket(string address, string subProtocol) + { + this.Address = address; + this.SubProtocols = new string[] { subProtocol }; + AllocateInstance(); + } + + public WebSocket(string address, string[] subProtocols) + { + this.Address = address; + this.SubProtocols = subProtocols; + AllocateInstance(); + } + + internal void AllocateInstance() + { + instanceId = WebSocketManager.AllocateInstance(this.Address); + Log($"Allocate socket with instanceId: {instanceId}"); + if (this.SubProtocols == null) return; + foreach (var protocol in this.SubProtocols) + { + if (string.IsNullOrEmpty(protocol)) continue; + Log($"Add Sub Protocol {protocol}, with instanceId: {instanceId}"); + int code = WebSocketManager.WebSocketAddSubProtocol(instanceId, protocol); + if (code < 0) + { + HandleOnError(GetErrorMessageFromCode(code)); + break; + } + } + } + + ~WebSocket() + { + Log($"Free socket with instanceId: {instanceId}"); + WebSocketManager.WebSocketFree(instanceId); + } + + public void ConnectAsync() + { + Log($"Connect with instanceId: {instanceId}"); + WebSocketManager.Add(this); + int code = WebSocketManager.WebSocketConnect(instanceId); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void CloseAsync() + { + Log($"Close with instanceId: {instanceId}"); + int code = WebSocketManager.WebSocketClose(instanceId, (int)CloseStatusCode.Normal, "Normal Closure"); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(string text) + { + Log($"Send, type: {Opcode.Text}, size: {text.Length}"); + int code = WebSocketManager.WebSocketSendStr(instanceId, text); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(byte[] data) + { + Log($"Send, type: {Opcode.Binary}, size: {data.Length}"); + int code = WebSocketManager.WebSocketSend(instanceId, data, 0, data.Length); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(byte[] data, int offset, int len) + { + Log($"Send, type: {Opcode.Binary}, offset: {offset}, len: {len}, size: {data.Length}"); + int code = WebSocketManager.WebSocketSend(instanceId, data, offset, len); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + internal void HandleOnOpen() + { + Log("OnOpen"); + OnOpen?.Invoke(this, new OpenEventArgs()); + } + + internal void HandleOnMessage(byte[] rawData) + { + Log($"OnMessage, type: {Opcode.Binary}, size: {rawData.Length}"); + OnMessage?.Invoke(this, new MessageEventArgs(Opcode.Binary, rawData)); + } + + internal void HandleOnMessageStr(string data) + { + Log($"OnMessage, type: {Opcode.Text}, size: {data.Length}"); + OnMessage?.Invoke(this, new MessageEventArgs(Opcode.Text, data)); + } + + internal void HandleOnClose(ushort code, string reason) + { + Log($"OnClose, code: {code}, reason: {reason}"); + OnClose?.Invoke(this, new CloseEventArgs(code, reason)); + WebSocketManager.Remove(instanceId); + } + + internal void HandleOnError(string msg) + { + Log("OnError, error: " + msg); + OnError?.Invoke(this, new ErrorEventArgs(msg)); + } + + internal static string GetErrorMessageFromCode(int errorCode) + { + switch (errorCode) + { + case -1: return "WebSocket instance not found."; + case -2: return "WebSocket is already connected or in connecting state."; + case -3: return "WebSocket is not connected."; + case -4: return "WebSocket is already closing."; + case -5: return "WebSocket is already closed."; + case -6: return "WebSocket is not in open state."; + case -7: return "Cannot close WebSocket, An invalid code was specified or reason is too long."; + case -8: return "Not support buffer slice. "; + default: return $"Unknown error code {errorCode}."; + } + } + + [System.Diagnostics.Conditional("UNITY_WEB_SOCKET_LOG")] + static void Log(string msg) + { + var time = DateTime.Now.ToString("HH:mm:ss.fff"); + UnityEngine.Debug.Log($"[{time}][UnityWebSocket] {msg}"); + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta new file mode 100644 index 0000000..ae13a6a --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 03629880dee95f444bb3e16a00fddf5b +timeCreated: 1466578513 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs new file mode 100644 index 0000000..0a862a4 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs @@ -0,0 +1,159 @@ +#if !UNITY_EDITOR && UNITY_WEBGL +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using AOT; + +namespace UnityWebSocket +{ + /// + /// Class providing static access methods to work with JSLIB WebSocket + /// + internal static class WebSocketManager + { + /* Map of websocket instances */ + private static Dictionary sockets = new Dictionary(); + + /* Delegates */ + public delegate void OnOpenCallback(int instanceId); + public delegate void OnMessageCallback(int instanceId, IntPtr msgPtr, int msgSize); + public delegate void OnMessageStrCallback(int instanceId, IntPtr msgStrPtr); + public delegate void OnErrorCallback(int instanceId, IntPtr errorPtr); + public delegate void OnCloseCallback(int instanceId, int closeCode, IntPtr reasonPtr); + + /* WebSocket JSLIB functions */ + [DllImport("__Internal")] + public static extern int WebSocketConnect(int instanceId); + + [DllImport("__Internal")] + public static extern int WebSocketClose(int instanceId, int code, string reason); + + [DllImport("__Internal")] + public static extern int WebSocketSend(int instanceId, byte[] dataPtr, int offset, int dataLength); + + [DllImport("__Internal")] + public static extern int WebSocketSendStr(int instanceId, string data); + + [DllImport("__Internal")] + public static extern int WebSocketGetState(int instanceId); + + /* WebSocket JSLIB callback setters and other functions */ + [DllImport("__Internal")] + public static extern int WebSocketAllocate(string url); + + [DllImport("__Internal")] + public static extern int WebSocketAddSubProtocol(int instanceId, string protocol); + + [DllImport("__Internal")] + public static extern void WebSocketFree(int instanceId); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnOpen(OnOpenCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnMessage(OnMessageCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnMessageStr(OnMessageStrCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnError(OnErrorCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnClose(OnCloseCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetSupport6000(); + + /* If callbacks was initialized and set */ + private static bool isInitialized = false; + + /* Initialize WebSocket callbacks to JSLIB */ + private static void Initialize() + { + WebSocketSetOnOpen(DelegateOnOpenEvent); + WebSocketSetOnMessage(DelegateOnMessageEvent); + WebSocketSetOnMessageStr(DelegateOnMessageStrEvent); + WebSocketSetOnError(DelegateOnErrorEvent); + WebSocketSetOnClose(DelegateOnCloseEvent); +#if UNITY_6000_0_OR_NEWER + WebSocketSetSupport6000(); +#endif + + isInitialized = true; + } + + [MonoPInvokeCallback(typeof(OnOpenCallback))] + public static void DelegateOnOpenEvent(int instanceId) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + socket.HandleOnOpen(); + } + } + + [MonoPInvokeCallback(typeof(OnMessageCallback))] + public static void DelegateOnMessageEvent(int instanceId, IntPtr msgPtr, int msgSize) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + var bytes = new byte[msgSize]; + Marshal.Copy(msgPtr, bytes, 0, msgSize); + socket.HandleOnMessage(bytes); + } + } + + [MonoPInvokeCallback(typeof(OnMessageStrCallback))] + public static void DelegateOnMessageStrEvent(int instanceId, IntPtr msgStrPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string msgStr = Marshal.PtrToStringAuto(msgStrPtr); + socket.HandleOnMessageStr(msgStr); + } + } + + [MonoPInvokeCallback(typeof(OnErrorCallback))] + public static void DelegateOnErrorEvent(int instanceId, IntPtr errorPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string errorMsg = Marshal.PtrToStringAuto(errorPtr); + socket.HandleOnError(errorMsg); + } + } + + [MonoPInvokeCallback(typeof(OnCloseCallback))] + public static void DelegateOnCloseEvent(int instanceId, int closeCode, IntPtr reasonPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string reason = Marshal.PtrToStringAuto(reasonPtr); + socket.HandleOnClose((ushort)closeCode, reason); + } + } + + internal static int AllocateInstance(string address) + { + if (!isInitialized) Initialize(); + return WebSocketAllocate(address); + } + + internal static void Add(WebSocket socket) + { + if (!sockets.ContainsKey(socket.instanceId)) + { + sockets.Add(socket.instanceId, socket); + } + } + + internal static void Remove(int instanceId) + { + if (sockets.ContainsKey(instanceId)) + { + sockets.Remove(instanceId); + } + } + } +} +#endif diff --git a/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta new file mode 100644 index 0000000..7e9d169 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e50fda0e4c26d094f8bea24b5cdb5258 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WebGL.meta b/Runtime/CoreRuntime/Plugins/WebGL.meta new file mode 100644 index 0000000..819ad19 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 704fde93545e7044585907a6fc46323b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib b/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib new file mode 100644 index 0000000..e669cd3 --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib @@ -0,0 +1,392 @@ +var WebSocketLibrary = +{ + $webSocketManager: + { + /* + * Map of instances + * + * Instance structure: + * { + * url: string, + * ws: WebSocket, + * subProtocols: string[], + * } + */ + instances: {}, + + /* Last instance ID */ + lastId: 0, + + /* Event listeners */ + onOpen: null, + onMessage: null, + onMessageStr: null, + onError: null, + onClose: null, + + /* Support Unity 6000 */ + support6000: false + }, + + /** + * Support Unity 6000 + * + */ + WebSocketSetSupport6000: function() + { + webSocketManager.support6000 = true; + }, + + /** + * Set onOpen callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnOpen: function(callback) + { + webSocketManager.onOpen = callback; + }, + + /** + * Set onMessage callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnMessage: function(callback) + { + webSocketManager.onMessage = callback; + }, + + /** + * Set onMessageStr callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnMessageStr: function(callback) + { + webSocketManager.onMessageStr = callback; + }, + + /** + * Set onError callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnError: function(callback) + { + webSocketManager.onError = callback; + }, + + /** + * Set onClose callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnClose: function(callback) + { + webSocketManager.onClose = callback; + }, + + /** + * Allocate new WebSocket instance struct + * + * @param url Server URL + */ + WebSocketAllocate: function(urlPtr) + { + var url = UTF8ToString(urlPtr); + var id = ++webSocketManager.lastId; + webSocketManager.instances[id] = { + url: url, + ws: null, + }; + + return id; + }, + + /** + * Add Sub Protocol + * + * @param instanceId Instance ID + * @param protocol Sub Protocol + */ + WebSocketAddSubProtocol: function(instanceId, protocolPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + + var protocol = UTF8ToString(protocolPtr); + + if (instance.subProtocols == null) + instance.subProtocols = []; + + instance.subProtocols.push(protocol); + + return 0; + }, + + /** + * Remove reference to WebSocket instance + * + * If socket is not closed function will close it but onClose event will not be emitted because + * this function should be invoked by C# WebSocket destructor. + * + * @param instanceId Instance ID + */ + WebSocketFree: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return 0; + + // Close if not closed + if (instance.ws !== null && instance.ws.readyState < 2) + instance.ws.close(); + + // Remove reference + delete webSocketManager.instances[instanceId]; + + return 0; + }, + + /** + * Connect WebSocket to the server + * + * @param instanceId Instance ID + */ + WebSocketConnect: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws !== null) return -2; + + if (instance.subProtocols != null) + instance.ws = new WebSocket(instance.url, instance.subProtocols); + else + instance.ws = new WebSocket(instance.url); + + instance.ws.onopen = function() + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('vi', 'webSocketManager.onOpen') }}}(instanceId); + } + else + { + Module.dynCall_vi(webSocketManager.onOpen, instanceId); + } + }; + + instance.ws.onmessage = function(ev) + { + if (ev.data instanceof ArrayBuffer) + { + var array = new Uint8Array(ev.data); + var buffer = _malloc(array.length); + writeArrayToMemory(array, buffer); + try + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('viii', 'webSocketManager.onMessage') }}}(instanceId, buffer, array.length); + } + else + { + Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length); + } + } + finally + { + _free(buffer); + } + } + else if (typeof ev.data == 'string') + { + var length = lengthBytesUTF8(ev.data) + 1; + var buffer = _malloc(length); + stringToUTF8(ev.data, buffer, length); + try + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('vii', 'webSocketManager.onMessageStr') }}}(instanceId, buffer); + } + else + { + Module.dynCall_vii(webSocketManager.onMessageStr, instanceId, buffer); + } + } + finally + { + _free(buffer); + } + } + else if (typeof Blob !== 'undefined' && ev.data instanceof Blob) + { + var reader = new FileReader(); + reader.onload = function() + { + var array = new Uint8Array(reader.result); + var buffer = _malloc(array.length); + writeArrayToMemory(array, buffer); + try + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('viii', 'webSocketManager.onMessage') }}}(instanceId, buffer, array.length); + } + else + { + Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length); + } + } + finally + { + reader = null; + _free(buffer); + } + }; + reader.readAsArrayBuffer(ev.data); + } + else + { + console.log("[JSLIB WebSocket] not support message type: ", (typeof ev.data)); + } + }; + + instance.ws.onerror = function(ev) + { + var msg = "WebSocket error."; + var length = lengthBytesUTF8(msg) + 1; + var buffer = _malloc(length); + stringToUTF8(msg, buffer, length); + try + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('vii', 'webSocketManager.onError') }}}(instanceId, buffer); + } + else + { + Module.dynCall_vii(webSocketManager.onError, instanceId, buffer); + } + } + finally + { + _free(buffer); + } + }; + + instance.ws.onclose = function(ev) + { + var msg = ev.reason; + var length = lengthBytesUTF8(msg) + 1; + var buffer = _malloc(length); + stringToUTF8(msg, buffer, length); + try + { + if (webSocketManager.support6000) + { + {{{ makeDynCall('viii', 'webSocketManager.onClose') }}}(instanceId, ev.code, buffer); + } + else + { + Module.dynCall_viii(webSocketManager.onClose, instanceId, ev.code, buffer); + } + } + finally + { + _free(buffer); + } + instance.ws = null; + }; + + return 0; + }, + + /** + * Close WebSocket connection + * + * @param instanceId Instance ID + * @param code Close status code + * @param reasonPtr Pointer to reason string + */ + WebSocketClose: function(instanceId, code, reasonPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState === 2) return -4; + if (instance.ws.readyState === 3) return -5; + + var reason = ( reasonPtr ? UTF8ToString(reasonPtr) : undefined ); + try + { + instance.ws.close(code, reason); + } + catch (err) + { + return -7; + } + + return 0; + }, + + /** + * Send message over WebSocket + * + * @param instanceId Instance ID + * @param bufferPtr Pointer to the message buffer + * @param length Length of the message in the buffer + */ + WebSocketSend: function(instanceId, bufferPtr, offset, length) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState !== 1) return -6; + + if (typeof HEAPU8 !== 'undefined') + instance.ws.send(HEAPU8.buffer.slice(bufferPtr + offset, bufferPtr + length)); + else if (typeof buffer !== 'undefined') + instance.ws.send(buffer.slice(bufferPtr + offset, bufferPtr + length)); + else + return -8; // not support buffer slice + + return 0; + }, + + /** + * Send message string over WebSocket + * + * @param instanceId Instance ID + * @param stringPtr Pointer to the message string + */ + WebSocketSendStr: function(instanceId, stringPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState !== 1) return -6; + + instance.ws.send(UTF8ToString(stringPtr)); + + return 0; + }, + + /** + * Return WebSocket readyState + * + * @param instanceId Instance ID + */ + WebSocketGetState: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return 3; // socket null as closed + + return instance.ws.readyState; + } +}; + +autoAddDeps(WebSocketLibrary, '$webSocketManager'); +mergeInto(LibraryManager.library, WebSocketLibrary); diff --git a/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib.meta b/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib.meta new file mode 100644 index 0000000..192201f --- /dev/null +++ b/Runtime/CoreRuntime/Plugins/WebGL/WebSocket.jslib.meta @@ -0,0 +1,42 @@ +fileFormatVersion: 2 +guid: 6efdfc519db4a344bb455fbd3f99c200 +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: {} + - first: + WeixinMiniGame: WeixinMiniGame + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Network.meta b/Runtime/Manager.meta similarity index 100% rename from Runtime/Network.meta rename to Runtime/Manager.meta diff --git a/Runtime/Network/EConnectState.cs b/Runtime/Manager/EConnectState.cs similarity index 100% rename from Runtime/Network/EConnectState.cs rename to Runtime/Manager/EConnectState.cs diff --git a/Runtime/Network/EConnectState.cs.meta b/Runtime/Manager/EConnectState.cs.meta similarity index 100% rename from Runtime/Network/EConnectState.cs.meta rename to Runtime/Manager/EConnectState.cs.meta diff --git a/Runtime/Network/INetworkModule.cs b/Runtime/Manager/INetworkModule.cs similarity index 100% rename from Runtime/Network/INetworkModule.cs rename to Runtime/Manager/INetworkModule.cs diff --git a/Runtime/Network/INetworkModule.cs.meta b/Runtime/Manager/INetworkModule.cs.meta similarity index 100% rename from Runtime/Network/INetworkModule.cs.meta rename to Runtime/Manager/INetworkModule.cs.meta diff --git a/Runtime/Network/NetworkComponent.cs b/Runtime/Manager/NetworkComponent.cs similarity index 100% rename from Runtime/Network/NetworkComponent.cs rename to Runtime/Manager/NetworkComponent.cs diff --git a/Runtime/Network/NetworkComponent.cs.meta b/Runtime/Manager/NetworkComponent.cs.meta similarity index 100% rename from Runtime/Network/NetworkComponent.cs.meta rename to Runtime/Manager/NetworkComponent.cs.meta diff --git a/Runtime/Network/NetworkModule.cs b/Runtime/Manager/NetworkModule.cs similarity index 100% rename from Runtime/Network/NetworkModule.cs rename to Runtime/Manager/NetworkModule.cs diff --git a/Runtime/Network/NetworkModule.cs.meta b/Runtime/Manager/NetworkModule.cs.meta similarity index 100% rename from Runtime/Network/NetworkModule.cs.meta rename to Runtime/Manager/NetworkModule.cs.meta diff --git a/csc.rsp b/csc.rsp new file mode 100644 index 0000000..84aeb38 --- /dev/null +++ b/csc.rsp @@ -0,0 +1,2 @@ +-define:FANTASY_UNITY +-r:System.Threading.Tasks.Extensions.dll \ No newline at end of file diff --git a/csc.rsp.meta b/csc.rsp.meta new file mode 100644 index 0000000..375f2b5 --- /dev/null +++ b/csc.rsp.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7c182478f57e3f449bd9ed09647b4336 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/package.json b/package.json index c5b381b..cfb5ec3 100644 --- a/package.json +++ b/package.json @@ -16,5 +16,8 @@ "author": { "name": "Yuliuren", "email": "yuliuren00@gmail.com" + }, + "dependencies": { + "com.unity.nuget.newtonsoft-json": "3.2.1" } } \ No newline at end of file