Decompiled source of SoulstoneCoopPlus v0.14.1
plugins/SoulstoneCoop.dll
Decompiled 18 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using ECM2.Characters; using ECM2.Examples.Animation.UnityCharacterAnimatorExample; using GameSmithing; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using LiteNetLib; using LiteNetLib.Layers; using LiteNetLib.Utils; using Microsoft.CodeAnalysis; using SoulstoneCoop.Enemies; using SoulstoneCoop.Life; using SoulstoneCoop.Lobby; using SoulstoneCoop.Loot; using SoulstoneCoop.Net; using SoulstoneCoop.Skills; using SoulstoneCoop.Steam; using SoulstoneCoop.Summons; using SoulstoneCoop.Ui; using Steamworks; using TMPro; using UnityEngine; using UnityEngine.AI; using UnityEngine.AddressableAssets; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.Utilities; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; using VolumetricFogAndMist2; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("SoulstoneCoop")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+042a3c9c84781281a0d5c364d2b8edc50912b008")] [assembly: AssemblyProduct("SoulstoneCoop")] [assembly: AssemblyTitle("SoulstoneCoop")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace SoulstoneCoop { public static class ClientSpawnBlock { public static bool NetworkSpawnInProgress; public static int LeakedEnemyCount; private static float _reapplyTimer; public static void Tick(float unscaledDeltaTime) { if (!CoopRole.IsClientSide) { return; } _reapplyTimer += unscaledDeltaTime; if (!(_reapplyTimer < 2f)) { _reapplyTimer = 0f; if (GameManagerUtil.HasGameManager) { GameManagerUtil.StopSpawning(); } } } internal static bool IsEnemyTeam(Entity entity) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 TeamComponent team = entity._team; if ((Object)(object)team == (Object)null) { return false; } return (team.Team & 0xC) > 0; } } [HarmonyPatch(typeof(GameManagerUtil), "StartMatch")] public static class ClientStartMatchPatch { [HarmonyPostfix] public static void Postfix(string mapId) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown bool flag = default(bool); try { if (CoopRole.IsClientSide) { GameManagerUtil.StopSpawning(); ClientSpawnBlock.LeakedEnemyCount = 0; ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(70, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][spawn] Client: StartMatch("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(mapId); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") -> StopSpawning() applied."); } staticLog.LogInfo(val); } } catch (Exception ex) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop] ClientStartMatchPatch: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog2.LogError(val2); } } } [HarmonyPatch(typeof(GameManagerUtil), "ResumeSpawning")] public static class ClientResumeSpawningPatch { [HarmonyPrefix] public static bool Prefix() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown try { if (!CoopRole.IsClientSide) { return true; } Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop][spawn] Client: blocked ResumeSpawning()."); return false; } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(43, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] ClientResumeSpawningPatch: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); return true; } } } [HarmonyPatch(typeof(BossSpawnProcessor), "SpawnBosses")] public static class ClientSpawnBossesPatch { [HarmonyPrefix] public static bool Prefix() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown try { if (!CoopRole.IsClientSide) { return true; } Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop][spawn] Client: blocked BossSpawnProcessor.SpawnBosses()."); return false; } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(40, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] ClientSpawnBossesPatch: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); return true; } } } [HarmonyPatch(typeof(SurvivorsBossRoomGameManager), "SpawnNextBoss")] public static class ClientBossRoomSpawnPatch { private static int _blocked; [HarmonyPrefix] public static bool Prefix() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown try { if (!CoopRole.IsClientSide) { return true; } if (_blocked++ < 20) { Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop][spawn] Client: blocked SurvivorsBossRoomGameManager.SpawnNextBoss() (BossRush map)."); } return false; } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(42, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] ClientBossRoomSpawnPatch: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); return true; } } } [HarmonyPatch(typeof(BossSpawnProcessor), "MasterySpawnBosses")] public static class ClientMasterySpawnBossesPatch { [HarmonyPrefix] public static bool Prefix() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown try { if (!CoopRole.IsClientSide) { return true; } Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop][spawn] Client: blocked BossSpawnProcessor.MasterySpawnBosses()."); return false; } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(47, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] ClientMasterySpawnBossesPatch: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); return true; } } } [HarmonyPatch(typeof(BossSpawnProcessor), "SpawnSpecificBoss")] public static class ClientSpawnSpecificBossPatch { [HarmonyPrefix] public static bool Prefix(ref Entity __result, string bossName) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown bool flag = default(bool); try { if (!CoopRole.IsClientSide) { return true; } ManualLogSource staticLog = Plugin.StaticLog; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(94, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][spawn] Client: blocked BossSpawnProcessor.SpawnSpecificBoss("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(bossName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("), returning null."); } staticLog.LogWarning(val); __result = null; return false; } catch (Exception ex) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(46, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop] ClientSpawnSpecificBossPatch: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog2.LogError(val2); return true; } } } [HarmonyPatch(typeof(BossSpawnProcessor), "SpawnEtherealEntity")] public static class ClientSpawnEtherealPatch { [HarmonyPrefix] public static bool Prefix(string lastBossEntityName) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown bool flag = default(bool); try { if (!CoopRole.IsClientSide) { return true; } ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(80, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][spawn] Client: blocked BossSpawnProcessor.SpawnEtherealEntity("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(lastBossEntityName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")."); } staticLog.LogInfo(val); return false; } catch (Exception ex) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(42, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop] ClientSpawnEtherealPatch: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog2.LogError(val2); return true; } } } [HarmonyPatch(typeof(QuestManager), "Setup")] public static class ClientQuestManagerPatch { [HarmonyPrefix] public static bool Prefix() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown try { if (!CoopRole.IsClientSide) { return true; } Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop][spawn] Client: blocked QuestManager.Setup() (the host's quest entities come as puppets)."); return false; } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] ClientQuestManagerPatch: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); return true; } } } [HarmonyPatch(typeof(Entity), "Setup")] public static class ClientEntitySetupLeakPatch { [HarmonyPostfix] public static void Postfix(Entity __instance) { //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) bool flag = default(bool); try { if (!CoopRole.IsClientSide || ClientSpawnBlock.NetworkSpawnInProgress || (Object)(object)__instance == (Object)null || __instance.IsPlayer() || !ClientSpawnBlock.IsEnemyTeam(__instance) || ClientPuppets.IsPuppet(__instance) || !GameManagerUtil.HasGameManager || __instance.EntityName == "EntityNameGod") { return; } GameData gameData = GameManagerUtil.GameData; if (!((Object)(object)__instance == (Object)(object)((gameData != null) ? gameData.GodEntity : null))) { ClientSpawnBlock.LeakedEnemyCount++; Vector3 position = ((Component)__instance).gameObject.transform.position; ManualLogSource staticLog = Plugin.StaticLog; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(88, 5, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][spawn] Client LEAK #"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(ClientSpawnBlock.LeakedEnemyCount); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": enemy '"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(__instance.EntityName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' "); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)((Component)__instance).gameObject).name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") team="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Team>(__instance._team.Team); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" pos="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Vector3>(position); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" set up outside the network."); } staticLog.LogWarning(val); } } catch (Exception ex) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(44, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop] ClientEntitySetupLeakPatch: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog2.LogError(val2); } } } [HarmonyPatch(typeof(MasteryGameManager), "SpawnBoss")] public static class ClientMasterySpawnBossPatch { [HarmonyPrefix] public static bool Prefix() { try { return !CoopRole.IsClientSide; } catch { return true; } } } [HarmonyPatch(typeof(CharacterAnimator), "UpdateAll")] public static class CharacterAnimatorUpdateGuardPatch { private static int _swallowed; [HarmonyFinalizer] public static Exception? Finalizer(Exception? __exception) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (__exception == null || !CoopRole.IsClientSide) { return __exception; } if (_swallowed++ < 3) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(97, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][puppets] CharacterAnimator.UpdateAll threw on the client (kept the frame going): "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(__exception.Message); } staticLog.LogWarning(val); } return null; } } public class CoopBehaviour : MonoBehaviour { private static CoopBehaviour? _instance; private static bool _firstUpdateLogged; private static bool _networkEventsHooked; private bool _prevPageDown; private bool _prevInsert; private bool _prevDelete; private static bool _autoConnectDone; private float _ghostCheckTimer; private float _statsTimer; private static GameObject? _debugGhost; public CoopBehaviour(IntPtr ptr) : base(ptr) { } public static void EnsureCreated() { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown Application.runInBackground = true; if ((Object)(object)_instance == (Object)null) { if (!ClassInjector.IsTypeRegisteredInIl2Cpp<CoopBehaviour>()) { ClassInjector.RegisterTypeInIl2Cpp<CoopBehaviour>(); } GameObject val = new GameObject("SoulstoneCoop"); Object.DontDestroyOnLoad((Object)val); _instance = val.AddComponent<CoopBehaviour>(); Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop] CoopBehaviour created and attached."); } if (!_networkEventsHooked) { _networkEventsHooked = true; Players.Left += delegate(byte slot) { DestroyGhost(CoopSession.Get(slot)); }; CoopSession.EnsureHooked(); PauseSync.EnsureHooked(); PartyStatus.EnsureHooked(); HostEnemySync.EnsureHooked(); ClientPuppets.EnsureHooked(); RemoteProxy.EnsureHooked(); RemoteCaster.EnsureHooked(); CoopLife.EnsureHooked(); PartnerHealth.EnsureHooked(); SummonSync.EnsureHooked(); } bool flag = default(bool); try { SteamLobby.EnsureInit(); } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop] SteamLobby.EnsureInit: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog.LogError(val2); } if (_autoConnectDone || NetworkManager.Role != NetRole.None) { return; } _autoConnectDone = true; if (Plugin.ConnectAddressArg != null) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("[SoulstoneCoop] Auto-connect to "); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(Plugin.ConnectAddressArg); ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("."); } staticLog2.LogInfo(val3); NetworkManager.StartClient(Plugin.ConnectAddressArg); } else if (Plugin.HostArg || Plugin.AutoHost.Value) { Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop] Auto-host: starting host."); NetworkManager.StartHost(); } } private static void UpdateGhostLifecycle() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Expected O, but got Unknown Entity localPlayerEntity = GameState.LocalPlayerEntity; bool flag = CoopSession.Connected && CoopSession.LocalInRun && !CoopSession.StageTransition && (Object)(object)localPlayerEntity != (Object)null; bool flag3 = default(bool); foreach (RemotePlayer remote in CoopSession.Remotes) { bool flag2 = flag && remote.InRun; if (flag2 && (Object)(object)remote.Ghost == (Object)null) { PlayerSync.ResetForNewGhost(remote); remote.GhostRebuilds = 0; remote.IdentityRebuilds = 0; PartnerHealth.Reset(remote.Slot); PartyStatus.Reset(remote.Slot); Transform transform = ((Component)localPlayerEntity).gameObject.transform; Vector3 position = transform.position + transform.right * 2f; remote.Ghost = VisualGhostFactory.Create(localPlayerEntity, remote, position, transform.rotation, $"SoulstoneCoop_RemoteGhost{remote.Slot}"); ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(63, 2, ref flag3); if (flag3) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Slot "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(remote.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(remote.Name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") is in the run with us - ghost created."); } staticLog.LogInfo(val); } else if (!flag2 && remote.Ghost != null) { DestroyGhost(remote); } } } private static void DestroyGhost(RemotePlayer? r) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown if (r == null) { return; } GameObject ghost = r.Ghost; r.Ghost = null; r.ModelAnimator = null; if ((Object)(object)ghost != (Object)null) { Object.Destroy((Object)(object)ghost); ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(39, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Ghost of slot "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(r.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" removed."); } staticLog.LogInfo(val); } } private void Update() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Expected O, but got Unknown bool flag = default(bool); try { if (!_firstUpdateLogged) { _firstUpdateLogged = true; Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop] First Update() tick received."); } Application.runInBackground = true; Perf.Begin(); NetworkManager.PollEvents(); Perf.Lap("NetworkManager.PollEvents"); try { SteamLobby.Tick(Time.unscaledDeltaTime); } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] SteamLobby.Tick: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } staticLog.LogError(val); } Perf.Lap("SteamLobby"); try { CoopSession.Tick(Time.unscaledDeltaTime); } catch (Exception ex2) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(34, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] CoopSession.Tick: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex2); } staticLog2.LogError(val); } Perf.Lap("CoopSession"); UpdateGhostLifecycle(); Perf.Lap("UpdateGhostLifecycle"); try { Loc.Tick(); } catch (Exception ex3) { ManualLogSource staticLog3 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(26, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Loc.Tick: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex3); } staticLog3.LogError(val); } Perf.Lap("Loc"); CoopUi.Tick(); Perf.Lap("CoopUi"); PlayerSync.Tick(Time.unscaledDeltaTime); Perf.Lap("PlayerSync"); GhostOverhead.Tick(Time.unscaledDeltaTime); Perf.Lap("GhostOverhead"); LobbyPartners.Tick(); Perf.Lap("LobbyPartners"); PartnerHealth.Tick(Time.unscaledDeltaTime); Perf.Lap("PartnerHealth"); SummonSync.Tick(Time.unscaledDeltaTime); Perf.Lap("SummonSync"); ClientSpawnBlock.Tick(Time.unscaledDeltaTime); Perf.Lap("ClientSpawnBlock"); WorldTelemetry.Tick(Time.unscaledDeltaTime); Perf.Lap("WorldTelemetry"); HostEnemySync.Tick(Time.unscaledDeltaTime); Perf.Lap("HostEnemySync"); ClientPuppets.Tick(Time.unscaledDeltaTime); Perf.Lap("ClientPuppets"); RemoteProxy.Tick(Time.unscaledDeltaTime); Perf.Lap("RemoteProxy"); ClientIncomingDamage.Tick(Time.unscaledDeltaTime); Perf.Lap("ClientIncomingDamage"); CastSync.Tick(Time.unscaledDeltaTime); Perf.Lap("CastSync"); LootSync.Tick(Time.unscaledDeltaTime); Perf.Lap("LootSync"); ChestSync.Tick(Time.unscaledDeltaTime); Perf.Lap("ChestSync"); QuestSync.Tick(Time.unscaledDeltaTime); Perf.Lap("QuestSync"); Reconnect.Tick(Time.unscaledDeltaTime); Perf.Lap("Reconnect"); CoopLife.Tick(Time.unscaledDeltaTime); Perf.Lap("CoopLife"); HealOrbs.Tick(Time.unscaledDeltaTime); Perf.Lap("HealOrbs"); GhostDowned.Tick(); Perf.Lap("GhostDowned"); PortalSync.Tick(Time.unscaledDeltaTime); Perf.Lap("PortalSync"); MasterySync.Tick(Time.unscaledDeltaTime); Perf.Lap("MasterySync"); CrusadeSync.Tick(Time.unscaledDeltaTime); Perf.Lap("CrusadeSync"); PartyStatus.Tick(Time.unscaledDeltaTime); Perf.Lap("PartyStatus"); PartyHud.Tick(Time.unscaledDeltaTime); Perf.Lap("PartyHud"); EnemyCasts.Tick(Time.unscaledDeltaTime); Perf.Lap("EnemyCasts"); GuestEffects.Tick(Time.unscaledDeltaTime); Perf.Lap("GuestEffects"); StatueSync.Tick(Time.unscaledDeltaTime); Perf.Lap("StatueSync"); EnemyHealthBonus.Tick(Time.unscaledDeltaTime); Perf.Lap("EnemyHealthBonus"); SpecialsDebug.Tick(Time.unscaledDeltaTime); Perf.Lap("SpecialsDebug"); ObjectiveSync.Tick(Time.unscaledDeltaTime); Perf.Lap("ObjectiveSync"); EnemyScaling.Tick(Time.unscaledDeltaTime); Perf.Lap("EnemyScaling"); BossVisualSync.Tick(Time.unscaledDeltaTime); Perf.Lap("BossVisualSync"); RebuildGhostIfModelInactive(); Perf.Lap("RebuildGhostIfModelInactive"); HandleDebugHotkeys(); Perf.Lap("HandleDebugHotkeys"); TestBridge.Tick(Time.unscaledDeltaTime); Perf.Lap("TestBridge"); LogSyncStats(); Perf.End(Time.unscaledDeltaTime); } catch (Exception ex4) { ManualLogSource staticLog4 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Exception in Update(): "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex4); } staticLog4.LogError(val); } } private void RebuildGhostIfModelInactive() { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Expected O, but got Unknown _ghostCheckTimer += Time.unscaledDeltaTime; if (_ghostCheckTimer < 1f) { return; } _ghostCheckTimer = 0f; Entity localPlayerEntity = GameState.LocalPlayerEntity; if ((Object)(object)localPlayerEntity == (Object)null) { return; } bool flag = default(bool); foreach (RemotePlayer remote in CoopSession.Remotes) { GameObject ghost = remote.Ghost; if ((Object)(object)ghost == (Object)null) { continue; } string text = VisualGhostFactory.KeyFor(remote.Info); if (remote.Info.Known && text != remote.GhostKey && remote.IdentityRebuilds < 3) { remote.IdentityRebuilds++; ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(85, 4, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Slot "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(remote.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" identity is now "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (ghost built for "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(remote.GhostKey); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") - rebuilding the ghost (#"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(remote.IdentityRebuilds); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")."); } staticLog.LogInfo(val); RebuildGhost(remote, ghost, localPlayerEntity); } else { if (remote.GhostRebuilds >= 3) { continue; } Animator val2 = remote.ModelAnimator; if ((Object)(object)val2 == (Object)null) { Il2CppArrayBase<Animator> componentsInChildren = ghost.GetComponentsInChildren<Animator>(true); if (componentsInChildren.Length == 0) { continue; } val2 = componentsInChildren[0]; } Il2CppArrayBase<Animator> componentsInChildren2 = ((Component)localPlayerEntity).gameObject.GetComponentsInChildren<Animator>(true); if (componentsInChildren2.Length != 0 && !((Component)val2).gameObject.activeInHierarchy && ((Component)componentsInChildren2[0]).gameObject.activeInHierarchy) { remote.GhostRebuilds++; ManualLogSource staticLog2 = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(79, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop] Ghost "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(remote.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" model '"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)((Component)val2).gameObject).name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' was cloned inactive - rebuilding the ghost (#"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(remote.GhostRebuilds); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")."); } staticLog2.LogInfo(val); RebuildGhost(remote, ghost, localPlayerEntity); } } } } private static void RebuildGhost(RemotePlayer r, GameObject ghost, Entity local) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Transform transform = ghost.transform; Vector3 position = transform.position; Quaternion rotation = transform.rotation; Object.Destroy((Object)(object)ghost); r.Ghost = VisualGhostFactory.Create(local, r, position, rotation, $"SoulstoneCoop_RemoteGhost{r.Slot}"); } private void LogSyncStats() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown if (NetworkManager.Role == NetRole.None) { return; } _statsTimer += Time.unscaledDeltaTime; if (_statsTimer < 2f) { return; } _statsTimer = 0f; Entity localPlayerEntity = GameState.LocalPlayerEntity; string text = (((Object)(object)localPlayerEntity != (Object)null) ? ((object)((Component)localPlayerEntity).gameObject.transform.position/*cast due to .constrained prefix*/).ToString() : "-"); List<string> list = new List<string>(); foreach (RemotePlayer remote in CoopSession.Remotes) { GameObject ghost = remote.Ghost; list.Add($"{remote.Slot}:{remote.Place}/ping={NetworkManager.PingOf(remote.Slot)}/{(((Object)(object)ghost != (Object)null) ? ((object)ghost.transform.position/*cast due to .constrained prefix*/).ToString() : "-")}/recv={remote.PositionsReceived}{(((Object)(object)ghost != (Object)null && !ghost.activeInHierarchy) ? "/inactive" : "")}"); } ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(151, 19, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][sync] role="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<NetRole>(NetworkManager.Role); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" slot="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(Players.MySlot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" peers="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(NetworkManager.PeerSlots.Count); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ping="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(NetworkManager.PingMs); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" silence="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(NetworkManager.SilenceSeconds, "F1"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("s"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(NetSim.Enabled ? " SIM" : ""); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("place="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LobbyPlace>(CoopSession.LocalPlace); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" sent="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PlayerSync.SentCount); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" recv="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PlayerSync.ReceivedCount); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" dashes="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PlayerSync.DashesSent); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PlayerSync.DashesReceived); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" trail="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(GhostDashTrail.ImagesShown); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" local="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("others=["); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(string.Join(" ", list)); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("] relayed="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(NetworkManager.RelayedPackets); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(NetworkManager.RelayedBytes); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" B) "); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("runInBg="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(Application.runInBackground); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" timeScale="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Time.timeScale); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" focused="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(Application.isFocused); } staticLog.LogInfo(val); NetworkManager.RelayedPackets = (NetworkManager.RelayedBytes = 0); } private void HandleDebugHotkeys() { if (Keyboard.current != null && !CoopUi.IsTyping) { bool isPressed = ((ButtonControl)Keyboard.current.insertKey).isPressed; if (isPressed && !_prevInsert) { Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop] Insert: starting host."); NetworkManager.StartHost(); } _prevInsert = isPressed; bool isPressed2 = ((ButtonControl)Keyboard.current.deleteKey).isPressed; if (isPressed2 && !_prevDelete) { Plugin.StaticLog.LogInfo((object)"[SoulstoneCoop] Delete: connecting to 127.0.0.1."); NetworkManager.StartClient("127.0.0.1"); } _prevDelete = isPressed2; bool isPressed3 = ((ButtonControl)Keyboard.current.pageDownKey).isPressed; if (isPressed3 && !_prevPageDown) { DebugRespawnGhost(); } _prevPageDown = isPressed3; } } private static void DebugRespawnGhost() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) Entity localPlayerEntity = GameState.LocalPlayerEntity; if ((Object)(object)localPlayerEntity == (Object)null) { Plugin.StaticLog.LogWarning((object)"[SoulstoneCoop] PageDown: no local player entity captured yet."); return; } if ((Object)(object)_debugGhost != (Object)null) { Object.Destroy((Object)(object)_debugGhost); } Transform transform = ((Component)localPlayerEntity).gameObject.transform; Vector3 position = transform.position + transform.right * 2f; _debugGhost = VisualGhostFactory.Create(localPlayerEntity, null, position, transform.rotation, "SoulstoneCoop_DebugGhost"); } } public static class CoopRole { public static bool IsClientSide { get { if (NetworkManager.Role != NetRole.Client) { return CoopSession.ClientRunLatched; } return true; } } public static bool IsHostSide => NetworkManager.Role == NetRole.Host; } public static class GameState { public static Entity? LocalPlayerEntity; } internal sealed class GhostDashTrail { private sealed class Template { public GameObject Prefab; public float Interval; public float Life; public int PoolSize; public int ColorId; public int FadeId; public string ColorProperty = ""; public string FadeProperty = ""; } private struct Image { public GameObject Go; public MeshRenderer Renderer; public float Remaining; } private static Template? _template; private static bool _templateMissingLogged; public static int ImagesShown; private readonly byte _slot; private readonly Color _color; private GameObject? _holder; private Mesh? _combined; private MaterialPropertyBlock? _block; private readonly List<Mesh> _baked = new List<Mesh>(); private readonly List<Image> _active = new List<Image>(); private readonly Stack<Image> _pool = new Stack<Image>(); private float _spawnTimer; private bool _wasDashing; private bool _meshReady; private bool _broken; private bool _bakeLogged; public GhostDashTrail(byte slot, byte characterId) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) _slot = slot; _color = Color.white; try { if (characterId != 0) { _color = CharacterDefinition.GetAccentColor((CharactersType)characterId); } } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(43, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][dash] Ghost "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" accent color: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } staticLog.LogWarning(val); } } public void Update(Transform ghostRoot, Transform? modelRoot, bool dashing, float speed) { //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown if (_broken) { return; } try { if (_holder != null && (Object)(object)_holder == (Object)null) { Forget(); } float deltaTime = Time.deltaTime; _spawnTimer -= deltaTime; if (dashing && !_wasDashing) { _meshReady = (Object)(object)modelRoot != (Object)null && EnsurePool() && Rebake(ghostRoot, modelRoot); } _wasDashing = dashing; if (dashing && _meshReady && _spawnTimer < 0f && speed > 0.1f) { _spawnTimer = _template.Interval; Spawn(ghostRoot); } Fade(deltaTime); } catch (Exception ex) { _broken = true; ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(45, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][dash] Ghost "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(_slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" dash trail off: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } staticLog.LogWarning(val); Dispose(); } } public void Dispose() { try { if ((Object)(object)_holder != (Object)null) { Object.Destroy((Object)(object)_holder); } foreach (Mesh item in _baked) { if ((Object)(object)item != (Object)null) { Object.Destroy((Object)(object)item); } } if ((Object)(object)_combined != (Object)null) { Object.Destroy((Object)(object)_combined); } } catch { } _baked.Clear(); _combined = null; Forget(); } private void Forget() { _holder = null; _active.Clear(); _pool.Clear(); _meshReady = false; } private static Template? GetTemplate() { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown if (_template != null && (Object)(object)_template.Prefab != (Object)null) { return _template; } Entity localPlayerEntity = GameState.LocalPlayerEntity; DashEffect val = (((Object)(object)localPlayerEntity != (Object)null) ? ((Component)localPlayerEntity).gameObject.GetComponent<DashEffect>() : null); if ((Object)(object)val == (Object)null || (Object)(object)val.DashEffectPrefab == (Object)null) { if (!_templateMissingLogged) { _templateMissingLogged = true; Plugin.StaticLog.LogWarning((object)"[SoulstoneCoop][dash] No DashEffect on the local player (yet): ghost dash trails wait for it."); } return null; } Template template = new Template { Prefab = val.DashEffectPrefab, Interval = val.TimeBetweenImages, Life = ((val.FadeSpeed > 0.01f) ? val.FadeSpeed : 0.3f), PoolSize = Mathf.Clamp(val.PoolSize, 1, 64), ColorProperty = (val.ColorProperty ?? ""), FadeProperty = (val.FadeProperty ?? "") }; template.ColorId = Shader.PropertyToID(template.ColorProperty); template.FadeId = Shader.PropertyToID(template.FadeProperty); ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(98, 6, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop][dash] Dash trail template: prefab '"); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)template.Prefab).name); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("', pool "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(template.PoolSize); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", "); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("every "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(template.Interval, "0.###"); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" s, life "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(template.Life, "0.###"); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" s, color '"); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(template.ColorProperty); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("', fade '"); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(template.FadeProperty); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("'."); } staticLog.LogInfo(val2); return _template = template; } private bool EnsurePool() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_013a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_holder != (Object)null) { return true; } Template template = GetTemplate(); if (template == null) { return false; } _holder = new GameObject($"SoulstoneCoop_DashTrail{_slot}"); if ((Object)(object)_combined == (Object)null) { _combined = new Mesh { name = $"SoulstoneCoop_DashTrail{_slot}", indexFormat = (IndexFormat)1 }; } if (_block == null) { _block = new MaterialPropertyBlock(); } for (int i = 0; i < template.PoolSize; i++) { GameObject val = Object.Instantiate<GameObject>(template.Prefab, _holder.transform); MeshFilter component = val.GetComponent<MeshFilter>(); MeshRenderer component2 = val.GetComponent<MeshRenderer>(); if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null) { throw new InvalidOperationException("prefab '" + ((Object)template.Prefab).name + "' has no MeshFilter/MeshRenderer"); } component.sharedMesh = _combined; ((Renderer)component2).GetPropertyBlock(_block); _block.SetColor(template.ColorId, _color); ((Renderer)component2).SetPropertyBlock(_block); val.SetActive(false); _pool.Push(new Image { Go = val, Renderer = component2 }); } return true; } private bool Rebake(Transform ghostRoot, Transform modelRoot) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Expected O, but got Unknown //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 worldToLocalMatrix = ghostRoot.worldToLocalMatrix; List<CombineInstance> list = new List<CombineInstance>(); int num = 0; int num2 = 0; int num3 = 0; foreach (SkinnedMeshRenderer componentsInChild in ((Component)modelRoot).GetComponentsInChildren<SkinnedMeshRenderer>()) { if ((Object)(object)componentsInChild == (Object)null || (Object)(object)componentsInChild.sharedMesh == (Object)null) { num3++; continue; } if (_baked.Count <= num) { _baked.Add(new Mesh()); } Mesh val = _baked[num]; componentsInChild.BakeMesh(val, true); list.Add(Part(val, worldToLocalMatrix * ((Renderer)componentsInChild).localToWorldMatrix)); num++; } foreach (MeshRenderer componentsInChild2 in ((Component)modelRoot).GetComponentsInChildren<MeshRenderer>()) { MeshFilter val2 = (((Object)(object)componentsInChild2 != (Object)null) ? ((Component)componentsInChild2).GetComponent<MeshFilter>() : null); Mesh val3 = (((Object)(object)val2 != (Object)null) ? val2.sharedMesh : null); if ((Object)(object)val3 == (Object)null || !val3.isReadable) { num3++; continue; } list.Add(Part(val3, worldToLocalMatrix * ((Component)componentsInChild2).transform.localToWorldMatrix)); num2++; } if (!_bakeLogged) { _bakeLogged = true; ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val4 = new BepInExInfoLogInterpolatedStringHandler(79, 5, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("[SoulstoneCoop][dash] Ghost "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<byte>(_slot); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" dash trail: "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(num); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" skinned + "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(num2); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" mesh renderer(s)"); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>((num3 > 0) ? $", {num3} skipped" : ""); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(", accent "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<Color>(_color); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("."); } staticLog.LogInfo(val4); } if (list.Count == 0) { return false; } Il2CppStructArray<CombineInstance> val5 = new Il2CppStructArray<CombineInstance>((long)list.Count); for (int i = 0; i < list.Count; i++) { ((Il2CppArrayBase<CombineInstance>)(object)val5)[i] = list[i]; } _combined.Clear(); _combined.CombineMeshes(val5); return true; } private static CombineInstance Part(Mesh mesh, Matrix4x4 m) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) return new CombineInstance { m_MeshInstanceID = ((Object)mesh).GetInstanceID(), m_SubMeshIndex = 0, m_Transform = m }; } private void Spawn(Transform ghostRoot) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) Template template = _template; while (_pool.Count > 0) { Image item = _pool.Pop(); if (!((Object)(object)item.Go == (Object)null) && !((Object)(object)item.Renderer == (Object)null)) { ((Renderer)item.Renderer).GetPropertyBlock(_block); _block.SetFloat(template.FadeId, 1f); ((Renderer)item.Renderer).SetPropertyBlock(_block); Transform transform = item.Go.transform; transform.position = ghostRoot.position; transform.rotation = ghostRoot.rotation; transform.localScale = ghostRoot.localScale; item.Go.SetActive(true); item.Remaining = template.Life; _active.Add(item); ImagesShown++; break; } } } private void Fade(float dt) { if (_active.Count == 0) { return; } Template template = _template; for (int num = _active.Count - 1; num >= 0; num--) { Image image = _active[num]; if ((Object)(object)image.Go == (Object)null || (Object)(object)image.Renderer == (Object)null) { _active.RemoveAt(num); } else { image.Remaining -= dt; ((Renderer)image.Renderer).GetPropertyBlock(_block); _block.SetFloat(template.FadeId, image.Remaining / template.Life); ((Renderer)image.Renderer).SetPropertyBlock(_block); if (image.Remaining <= 0f) { image.Go.SetActive(false); _active.RemoveAt(num); _pool.Push(image); } else { _active[num] = image; } } } } } public static class GhostOverhead { private sealed class View { public byte Slot; public RectTransform? Panel; public TextMeshProUGUI? Name; public GameObject? Bar; public RectTransform? Fill; public Image? FillImage; public string ShownName = ""; public IntPtr GhostPtr; public float Height = 2.6f; public bool Visible; public int IconId = -1; public IntPtr IconGhostPtr; public float IconRunStart; public List<Image>? TintedImages; public float TintTimer; } internal static readonly Color AllyColor = new Color(0.35f, 1f, 0.5f, 1f); private static readonly Color DownColor = new Color(0.95f, 0.35f, 0.3f, 1f); private static readonly Color[] SlotColors = (Color[])(object)new Color[8] { AllyColor, new Color(0.35f, 0.8f, 1f, 1f), new Color(1f, 0.85f, 0.3f, 1f), new Color(1f, 0.5f, 0.85f, 1f), new Color(1f, 0.6f, 0.25f, 1f), new Color(0.72f, 0.55f, 1f, 1f), new Color(0.6f, 1f, 0.95f, 1f), new Color(0.92f, 0.92f, 0.92f, 1f) }; private const int MaxChars = 24; private const float NameSize = 26f; private const float BarWidth = 130f; private const float BarHeight = 14f; private static GameObject? _root; private static bool _buildFailed; private static TMP_FontAsset? _font; private static Sprite? _allySprite; private static readonly Dictionary<byte, View> Views = new Dictionary<byte, View>(); private static bool _hooked; private static bool _iconFailed; private static float _telemetryTimer; private static int _locVersion = -1; private static Camera? _gameCam; private static float _camSearchTimer; internal static Color ColorFor(byte slot) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (slot >= SlotColors.Length) { return AllyColor; } return SlotColors[slot]; } public static void Attach(byte slot, GameObject ghost, float height) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown EnsureHooked(); EnsureRoot(); View view = ViewOf(slot); view.GhostPtr = ((Il2CppObjectBase)ghost).Pointer; view.Height = height; ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(78, 4, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Overhead follows ghost "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(height, "0.0"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" above its root (name '"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(CoopSession.NameOf(slot)); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("', ui="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>((Object)(object)view.Panel != (Object)null); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")."); } staticLog.LogInfo(val); } private static void EnsureHooked() { if (_hooked) { return; } _hooked = true; Players.Left += delegate(byte slot) { if (Views.TryGetValue(slot, out View value)) { Views.Remove(slot); RemoveIcon(value); if ((Object)(object)value.Panel != (Object)null) { Object.Destroy((Object)(object)((Component)value.Panel).gameObject); } } }; } private static View ViewOf(byte slot) { if (Views.TryGetValue(slot, out View value)) { return value; } value = new View { Slot = slot }; Views[slot] = value; BuildPanel(value); return value; } public static void Tick(float unscaledDeltaTime) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Expected O, but got Unknown EnsureHooked(); if (_locVersion != Loc.Version) { ApplyLanguage(); } bool flag = default(bool); foreach (RemotePlayer remote in CoopSession.Remotes) { GameObject ghost = remote.Ghost; if ((Object)(object)ghost == (Object)null && !Views.ContainsKey(remote.Slot)) { continue; } View v = ViewOf(remote.Slot); try { UpdateMinimapIcon(v, ghost); } catch (Exception ex) { _iconFailed = true; ManualLogSource staticLog = Plugin.StaticLog; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(46, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Minimap icon disabled: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } staticLog.LogWarning(val); } try { UpdateOverhead(v, ghost); } catch (Exception ex2) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(41, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Overhead tick ("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(remote.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message); } staticLog2.LogWarning(val); SetVisible(v, on: false); } } _telemetryTimer += unscaledDeltaTime; if (_telemetryTimer < 5f) { return; } _telemetryTimer = 0f; if (Views.Count == 0) { return; } List<string> list = new List<string>(); foreach (View value in Views.Values) { PartnerHealth.View view = PartnerHealth.Of(value.Slot); list.Add($"{value.Slot}: hp={view.Health:F0}/{view.MaxHealth:F0} known={view.Known} down={view.Down} shown={value.Visible} icon={value.IconId}"); } ManualLogSource staticLog3 = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(24, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop][hpbar] "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(string.Join(" | ", list)); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(PartnerHealth.TakeStats()); } staticLog3.LogInfo(val2); } private static void UpdateOverhead(View v, GameObject? ghost) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)v.Panel == (Object)null || (Object)(object)ghost == (Object)null || !CoopSession.LocalInRun || Time.timeScale < 0.01f) { SetVisible(v, on: false); return; } if (((Il2CppObjectBase)ghost).Pointer != v.GhostPtr) { v.GhostPtr = ((Il2CppObjectBase)ghost).Pointer; v.Height = 2.6f; } Camera val = FindCamera(); if ((Object)(object)val == (Object)null) { SetVisible(v, on: false); return; } Vector3 val2 = val.WorldToScreenPoint(ghost.transform.position + Vector3.up * v.Height); if (val2.z <= 0f) { SetVisible(v, on: false); return; } ((Transform)v.Panel).position = new Vector3(Mathf.Round(val2.x), Mathf.Round(val2.y), 0f); PartnerHealth.View view = PartnerHealth.Of(v.Slot); bool flag = CoopLife.IsRemoteDown(v.Slot) || view.Down || view.Dead; string text = CoopSession.NameOf(v.Slot); if (text.Length > 24) { text = text.Substring(0, 21) + "..."; } if (flag) { text = Loc.T("gh.down", ("name", text)); } if ((Object)(object)v.Name != (Object)null && text != v.ShownName) { v.ShownName = text; ((TMP_Text)v.Name).text = text; } Color val3 = ColorFor(v.Slot); if ((Object)(object)v.Name != (Object)null) { ((Graphic)v.Name).color = (flag ? DownColor : val3); } bool flag2 = view.Known && view.MaxHealth > 0f; if ((Object)(object)v.Bar != (Object)null && v.Bar.activeSelf != flag2) { v.Bar.SetActive(flag2); } if (flag2 && (Object)(object)v.Fill != (Object)null) { float num = (flag ? 0f : view.Fraction); v.Fill.sizeDelta = new Vector2(126f * num, 10f); if (((Component)v.Fill).gameObject.activeSelf != num > 0.005f) { ((Component)v.Fill).gameObject.SetActive(num > 0.005f); } if ((Object)(object)v.FillImage != (Object)null) { ((Graphic)v.FillImage).color = (((Object)(object)_allySprite != (Object)null) ? Color.white : val3); } } SetVisible(v, on: true); } private static void ApplyLanguage() { //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown _locVersion = Loc.Version; if ((Object)(object)_root == (Object)null) { return; } TMP_FontAsset val = FindFont(); if ((Object)(object)val == (Object)null || ((Object)(object)_font != (Object)null && ((Il2CppObjectBase)val).Pointer == ((Il2CppObjectBase)_font).Pointer)) { return; } _font = val; foreach (View value in Views.Values) { if ((Object)(object)value.Panel != (Object)null) { Object.Destroy((Object)(object)((Component)value.Panel).gameObject); } value.Panel = null; value.Name = null; value.ShownName = ""; BuildPanel(value); } ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(52, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop][hpbar] Name tags rebuilt with font "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("."); } staticLog.LogInfo(val2); Loc.CheckGlyphs(val, "name tag"); } private static void SetVisible(View v, bool on) { v.Visible = on; if ((Object)(object)v.Panel != (Object)null && ((Component)v.Panel).gameObject.activeSelf != on) { ((Component)v.Panel).gameObject.SetActive(on); } } private static void EnsureRoot() { //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown if ((Object)(object)_root != (Object)null || _buildFailed) { return; } bool flag = default(bool); try { _root = new GameObject("SoulstoneCoop_Overhead"); Object.DontDestroyOnLoad((Object)(object)_root); Canvas obj = _root.AddComponent<Canvas>(); obj.renderMode = (RenderMode)0; obj.sortingOrder = -100; CanvasScaler obj2 = _root.AddComponent<CanvasScaler>(); obj2.uiScaleMode = (ScaleMode)1; obj2.referenceResolution = new Vector2(1920f, 1080f); obj2.matchWidthOrHeight = 0.5f; _font = FindFont(); _allySprite = FindAllyBarSprite(); ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(63, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Overhead UI built (font="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)(object)_font != (Object)null) ? ((Object)_font).name : "TMP default"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ally sprite="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)(object)_allySprite != (Object)null) ? ((Object)_allySprite).name : "none, flat color"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")."); } staticLog.LogInfo(val); } catch (Exception ex) { _buildFailed = true; ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(88, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop][hpbar] Overhead UI could not be built (the ghosts go without name/bar): "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } staticLog2.LogError(val2); if ((Object)(object)_root != (Object)null) { Object.Destroy((Object)(object)_root); } _root = null; } } private static void BuildPanel(View v) { //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Expected O, but got Unknown //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) EnsureRoot(); if ((Object)(object)_root == (Object)null) { return; } bool flag = default(bool); try { RectTransform val = MakeRect(_root.transform, $"Panel{v.Slot}"); val.sizeDelta = new Vector2(320f, 60f); val.pivot = new Vector2(0.5f, 0f); RectTransform obj = MakeRect((Transform)(object)val, "Name"); Vector2 anchorMin = (obj.anchorMax = new Vector2(0.5f, 0f)); obj.anchorMin = anchorMin; obj.pivot = new Vector2(0.5f, 0f); obj.anchoredPosition = new Vector2(0f, 18f); obj.sizeDelta = new Vector2(320f, 34f); TextMeshProUGUI val3 = ((Component)obj).gameObject.AddComponent<TextMeshProUGUI>(); if ((Object)(object)_font != (Object)null) { ((TMP_Text)val3).font = _font; } ((TMP_Text)val3).fontSize = 26f; ((TMP_Text)val3).fontStyle = (FontStyles)1; ((TMP_Text)val3).alignment = (TextAlignmentOptions)1026; ((TMP_Text)val3).enableWordWrapping = false; ((TMP_Text)val3).richText = false; ((Graphic)val3).raycastTarget = false; ((Graphic)val3).color = ColorFor(v.Slot); try { ((TMP_Text)val3).outlineWidth = 0.3f; ((TMP_Text)val3).outlineColor = new Color32((byte)0, (byte)0, (byte)0, byte.MaxValue); Material fontMaterial = ((TMP_Text)val3).fontMaterial; fontMaterial.EnableKeyword("UNDERLAY_ON"); fontMaterial.SetColor("_UnderlayColor", new Color(0f, 0f, 0f, 0.8f)); fontMaterial.SetFloat("_UnderlayOffsetX", 0.6f); fontMaterial.SetFloat("_UnderlayOffsetY", -0.6f); fontMaterial.SetFloat("_UnderlaySoftness", 0.3f); } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; BepInExWarningLogInterpolatedStringHandler val4 = new BepInExWarningLogInterpolatedStringHandler(44, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("[SoulstoneCoop][hpbar] Name outline/shadow: "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(ex.Message); } staticLog.LogWarning(val4); } v.Name = val3; RectTransform val5 = MakeRect((Transform)(object)val, "HealthBar"); anchorMin = (val5.anchorMax = new Vector2(0.5f, 0f)); val5.anchorMin = anchorMin; val5.pivot = new Vector2(0.5f, 0f); val5.anchoredPosition = Vector2.zero; val5.sizeDelta = new Vector2(130f, 14f); Image obj2 = ((Component)val5).gameObject.AddComponent<Image>(); ((Graphic)obj2).color = new Color(0f, 0f, 0f, 0.8f); ((Graphic)obj2).raycastTarget = false; RectTransform val7 = MakeRect((Transform)(object)val5, "Fill"); anchorMin = (val7.anchorMax = new Vector2(0f, 0.5f)); val7.anchorMin = anchorMin; val7.pivot = new Vector2(0f, 0.5f); val7.anchoredPosition = new Vector2(2f, 0f); val7.sizeDelta = new Vector2(126f, 10f); Image val9 = ((Component)val7).gameObject.AddComponent<Image>(); ((Graphic)val9).raycastTarget = false; if ((Object)(object)_allySprite != (Object)null) { val9.sprite = _allySprite; Vector4 border = _allySprite.border; val9.type = (Type)(((Vector4)(ref border)).sqrMagnitude > 0f); } ((Graphic)val9).color = (((Object)(object)_allySprite != (Object)null) ? Color.white : ColorFor(v.Slot)); v.Fill = val7; v.FillImage = val9; v.Bar = ((Component)val5).gameObject; v.Bar.SetActive(false); ((Component)val).gameObject.SetActive(false); v.Panel = val; } catch (Exception ex2) { ManualLogSource staticLog2 = Plugin.StaticLog; BepInExErrorLogInterpolatedStringHandler val10 = new BepInExErrorLogInterpolatedStringHandler(68, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val10).AppendLiteral("[SoulstoneCoop][hpbar] Overhead panel for slot "); ((BepInExLogInterpolatedStringHandler)val10).AppendFormatted<byte>(v.Slot); ((BepInExLogInterpolatedStringHandler)val10).AppendLiteral(" could not be built: "); ((BepInExLogInterpolatedStringHandler)val10).AppendFormatted<Exception>(ex2); } staticLog2.LogError(val10); } } private static RectTransform MakeRect(Transform parent, string name) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) RectTransform obj = new GameObject(name).AddComponent<RectTransform>(); ((Transform)obj).SetParent(parent, false); return obj; } private static TMP_FontAsset? FindFont() { TMP_FontAsset gameFont = CoopUi.GameFont; if ((Object)(object)gameFont != (Object)null) { return gameFont; } try { foreach (TextMeshProUGUI item in Object.FindObjectsOfType<TextMeshProUGUI>(true)) { if ((Object)(object)item != (Object)null && (Object)(object)((TMP_Text)item).font != (Object)null) { return ((TMP_Text)item).font; } } } catch { } return TMP_Settings.defaultFontAsset; } private static Camera? FindCamera() { if ((Object)(object)_gameCam != (Object)null && ((Behaviour)_gameCam).isActiveAndEnabled) { return _gameCam; } _camSearchTimer -= Time.unscaledDeltaTime; if (_camSearchTimer <= 0f) { _camSearchTimer = 2f; try { OverheadHealthBarPanelManager val = Object.FindObjectOfType<OverheadHealthBarPanelManager>(); _gameCam = (((Object)(object)val != (Object)null) ? val.GameplayCamera : null); } catch { _gameCam = null; } if ((Object)(object)_gameCam != (Object)null) { return _gameCam; } } return Camera.main; } private static Sprite? FindAllyBarSprite() { try { OverheadHealthBarPanelManager val = Object.FindObjectOfType<OverheadHealthBarPanelManager>(true); return ((Object)(object)val != (Object)null) ? val.AllyHealthBarSprite : null; } catch { return null; } } private static void RemoveIcon(View v) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown if (v.IconId < 0) { return; } UntintIcon(v); bool flag = Mathf.Approximately(v.IconRunStart, CoopSession.LocalRunStartTime); try { if (flag && GameManagerUtil.HasGameManager) { MinimapManager.RequestRemoveIcon(v.IconId); } } catch (Exception ex) { ManualLogSource staticLog = Plugin.StaticLog; bool flag2 = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(47, 2, ref flag2); if (flag2) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Removing minimap icon "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(v.IconId); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } staticLog.LogWarning(val); } v.IconId = -1; v.IconGhostPtr = IntPtr.Zero; } private static void UpdateMinimapIcon(View v, GameObject? ghost) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown if (_iconFailed) { return; } bool flag = Mathf.Approximately(v.IconRunStart, CoopSession.LocalRunStartTime); if (v.IconId >= 0 && ((Object)(object)ghost == (Object)null || ((Il2CppObjectBase)ghost).Pointer != v.IconGhostPtr || !flag)) { RemoveIcon(v); } if (v.IconId >= 0) { TintIcon(v); } else if (!((Object)(object)ghost == (Object)null) && CoopSession.LocalInRun && GameManagerUtil.HasGameManager) { v.IconId = MinimapManager.RequestIcon((MinimapIconType)1, ghost.transform, ghost.transform.position); v.IconGhostPtr = ((Il2CppObjectBase)ghost).Pointer; v.IconRunStart = CoopSession.LocalRunStartTime; ManualLogSource staticLog = Plugin.StaticLog; bool flag2 = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(67, 2, ref flag2); if (flag2) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][hpbar] Minimap icon "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(v.IconId); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (Player) requested for ghost "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(v.Slot); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("."); } staticLog.LogInfo(val); } } private static void TintIcon(View v) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Invalid comparison between Unknown and I4 //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Expected O, but got Unknown if (v.TintedImages != null) { return; } v.TintTimer -= Time.unscaledDeltaTime; if (v.TintTimer > 0f) { return; } v.TintTimer = 0.5f; FastList<MinimapItem> items = MinimapManager._items; if (items == null) { return; } Il2CppArrayBase<MinimapItem> elements = items._elements; int num = Mathf.Min(items.Count, elements?.Length ?? 0); bool flag = default(bool); for (int i = 0; i < num; i++) { MinimapItem val = elements[i]; if (val == null || val.ItemId != v.IconId || (int)val.State != 1 || (Object)(object)val.References == (Object)null) { continue; } Color color = ColorFor(v.Slot); v.TintedImages = new List<Image>(); foreach (Image componentsInChild in ((Component)val.References).GetComponentsInChildren<Image>(true)) { ((Graphic)componentsInChild).color = color; v.TintedImages.Add(componentsInChild); } ManualLogSource staticLog = Plugin.StaticLog; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(63, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[SoulstoneCoop][hpbar] Minimap icon "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(v.IconId); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" of slot "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<byte>(v.Slot); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" tinted ("); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(v.TintedImages.Count); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" images)."); } staticLog.LogInfo(val2); break; } } private static void UntintIcon(View v) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (v.TintedImages != null) { foreach (Image tintedImage in v.TintedImages) { if ((Object)(object)tintedImage != (Object)null) { ((Graphic)tintedImage).color = Color.white; } } } v.TintedImages = null; v.TintTimer = 0f; } internal static string TestInfo(string[] args) { return string.Join(" ", Views.Values.Select((View v) => $"slot{v.Slot}:icon={v.IconId}:tinted={((v.TintedImages != null) ? v.TintedImages.Count : (-1))}")); } } public static class Perf { private const float LogInterval = 10f; private static readonly Dictionary<string, double> _ms = new Dictionary<string, double>(); private static readonly Dictionary<string, double> _peak = new Dictionary<string, double>(); private static long _last; private static double _modMs; private static double _frameMsSum; private static double _worstFrame; private static int _frames; private static float _timer; internal static string LastReport = "no data yet"; public static void Begin() { float num = Time.unscaledDeltaTime * 1000f; _frameMsSum += num; if ((double)num > _worstFrame) { _worstFrame = num; } _frames++; _last = Stopwatch.GetTimestamp(); } public static void Lap(string name) { long timestamp = Stopwatch.GetTimestamp(); double num = (double)(timestamp - _last) * 1000.0 / (double)Stopwatch.Frequency; _last = timestamp; _modMs += num; _ms[name] = (_ms.TryGetValue(name, out var value) ? value : 0.0) + num; if (!_peak.TryGetValue(name, out var value2) || num > value2) { _peak[name] = num; } } public static void End(float dt) { //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Expected O, but got Unknown _timer += dt; if (_timer < 10f) { return; } _timer = 0f; if (_frames == 0) { return; } double num = _frameMsSum / (double)_frames; IEnumerable<string> values = from kv in _ms.OrderByDescending<KeyValuePair<string, double>, double>((KeyValuePair<string, double> kv) => kv.Value).Take(6) select $"{kv.Key}={kv.Value / (double)_frames:F2}ms(peak {_peak[kv.Key]:F1})"; LastReport = $"fps={1000.0 / num:F0} frame={num:F1}ms worst={_worstFrame:F0}ms mod={_modMs / (double)_frames:F2}ms/frame ({_modMs / _frameMsSum * 100.0:F0}%) entities={EntityRegistry.AllEntities?.Count ?? 0} top: {string.Join(", ", values)}"; if (GameManagerUtil.HasGameManager) { ManualLogSource staticLog = Plugin.StaticLog; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(22, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[SoulstoneCoop][perf] "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(LastReport); } staticLog.LogInfo(val); } _ms.Clear(); _peak.Clear(); _modMs = (_frameMsSum = (_worstFrame = 0.0)); _frames = 0; } } [BepInPlugin("com.kolber.soulstonecoop", "Soulstone Coop", "0.14.0")] public class Plugin : BasePlugin { public enum SteamLobbyType { FriendsOnly, Public, Private } public const string PluginGuid = "com.kolber.soulstonecoop"; public const string PluginName = "Soulstone Coop"; public const string PluginVersion = "0.14.0"; internal static ManualLogSource StaticLog; internal static ConfigEntry<bool> AutoHost; internal static ConfigEntry<string> LastAddress; internal static ConfigEntry<bool> AllowRejoin; internal static ConfigEntry<bool> EndRunWhenHostLeaves; internal static ConfigEntry<bool> SenderClock; internal static ConfigEntry<int> MaxPlayers; internal static ConfigEntry<SteamLobbyType> LobbyType; internal static ConfigEntry<float> EnemyScalePerPlayer; internal static ConfigEntry<float> ReplicaCastRadius; internal static ConfigEntry<bool> DashDodge; internal static ConfigEntry<float> EnemyHealthBonus; private static int _simLatency; private static int _simJitter; private static int _simLoss; internal static bool HostArg; internal static string? ConnectAddressArg; internal static string? FakeVersionArg; internal static string? NameArg; internal static string? TestArg; internal static string HandshakeVersion => FakeVersionArg ?? "0.14.0"; public override void Load() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Expected O, but got Unknown //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Expected O, but got Unknown //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Expected O, but got Unknown //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Expected O, but got Unknown //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Expected O, but got Unknown //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_044a: Expected O, but got Unknown //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Expected O, but got Unknown //IL_0389: Expected O, but got Unknown //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Expected O, but got Unknown StaticLog = ((BasePlugin)this).Log; ManualLogSource log = ((BasePlugin)this).Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(12, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Soulstone Coop"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.14.0"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loading..."); } log.LogInfo(val); LevelUpPolicy.Bind(((BasePlugin)this).Config); PartyHud.Bind(((BasePlugin)this).Config); CameraZoom.Bind(((BasePlugin)this).Config); LobbyPartners.Bind(((BasePlugin)this).Config); Loc.Init(((BasePlugin)this).Config); AutoHost = ((BasePlugin)this).Config.Bind<bool>("Debug", "AutoHost", false, "Start hosting automatically when the main menu opens (instead of the Co-op panel or Insert)."); LastAddress = ((BasePlugin)this).Config.Bind<string>("Coop", "LastAddress", "127.0.0.1", "Host address last typed in the Co-op panel (filled in automatically next time)."); ConfigEntry<int> val2 = ((BasePlugin)this).Config.Bind<int>("Debug", "SimulateLatencyMs", 0, "Test only: extra delay in ms on one direction of the co-op link (turn it on in both games: 75 + 75 = about 150 ms of ping). 0 = off."); ConfigEntry<int> val3 = ((BasePlugin)this).Config.Bind<int>("Debug", "SimulateJitterMs", 0, "Test only: random +- variation in ms on top of SimulateLatencyMs. 0 = off."); ConfigEntry<int> obj = ((BasePlugin)this).Config.Bind<int>("Debug", "SimulatePacketLossPercent", 0, "Test only: percent of packets lost (0-50). Reliable messages are resent, so they arrive late instead. 0 = off."); AllowRejoin = ((BasePlugin)this).Config.Bind<bool>("Coop", "AllowRejoin", false, "Host only, experimental: a partner who connects while you are in a run is brought into it (as a new character). Off = they wait in the menu."); EndRunWhenHostLeaves = ((BasePlugin)this).Config.Bind<bool>("Coop", "EndRunWhenHostLeaves", true, "Client: when the host disconnects mid-run, end the run (surrender) a few seconds later instead of staying in an empty map."); SenderClock = ((BasePlugin)this).Config.Bind<bool>("Coop", "SenderClock", false, "Experimental: place the partner and the enemies by the sender's clock instead of the arrival time (smoother with jitter)."); MaxPlayers = ((BasePlugin)this).Config.Bind<int>("Coop", "MaxPlayers", 8, new ConfigDescription("Host: how many players fit in your co-op session, you included (2-8). Clients past that are refused.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 8), Array.Empty<object>())); LobbyType = ((BasePlugin)this).Config.Bind<SteamLobbyType>("Coop", "LobbyType", SteamLobbyType.FriendsOnly, "Host, Steam: who can join your lobby. FriendsOnly = friends and invitees of the players in it (anyone in the group can invite). Public = anyone with the lobby code. Private = only who gets an invite."); EnemyScalePerPlayer = ((BasePlugin)this).Config.Bind<float>("Coop", "EnemyScalePerPlayer", 0f, new ConfigDescription("Host: more enemies alive at once for each extra player in the run (the game's limits x (1 + this x (players - 1)), up to 200). 0 = off (the game's own numbers). Suggested: 0.25 (8 players: x2.75).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>())); ReplicaCastRadius = ((BasePlugin)this).Config.Bind<float>("Coop", "ReplicaCastRadius", 60f, "Spells of the other players are only replayed (visual only) when they are within this distance of you; farther ones are off screen anyway. Saves the effects of 7 builds on every PC. 0 = always replay."); EnemyHealthBonus = ((BasePlugin)this).Config.Bind<float>("Coop", "EnemyHealthBonus", 100f, new ConfigDescription("Host: extra health of every enemy, in percent, for each additional player in the run. 100 = +100 % with 2 players, +200 % with 3. 0 = the game's own health.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>())); ConfigEntry<int> val4 = ((BasePlugin)this).Config.Bind<int>("Internal", "SettingsRevision", 0, "Do not edit: tracks one-time updates of old defaults."); if (val4.Value < 1) { if (EnemyHealthBonus.Value < 100f) { EnemyHealthBonus.Value = 100f; } val4.Value = 1; } DashDodge = ((BasePlugin)this).Config.Bind<bool>("Coop", "DashDodge", true, "Guests: a hit the host computes while you are dashing (or right after, within your ping) is dodged, like the dash dodge when playing alone."); _simLatency = val2.Value; _simJitter = val3.Value; _simLoss = obj.Value; ParseLaunchArgs(); NetSim.Configure(_simLatency, _simJitter, _simLoss); NetSim.LogBanner(); Harmony val5 = new Harmony("com.kolber.soulstonecoop"); val5.PatchAll(typeof(Plugin).Assembly); try { val5.Patch((MethodBase)AccessTools.Method(typeof(EnemyPrefabsUtil), "SpawnEnemyEntity", (Type[])null, (Type[])null), new HarmonyMethod(typeof(HostSpawnEnemyEntityPatch), "Prefix", (Type[])null), new HarmonyMethod(typeof(HostSpawnEnemyEntityPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { ManualLogSource log2 = ((BasePlugin)this).Log; BepInExErrorLogInterpolatedStringHandler val6 = new BepInExErrorLogInterpolatedStringHandler(90, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Could not patch EnemyPrefabsUtil.SpawnEnemyEntity (enemy keys fall back to prefab names): "); ((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<Exception>(ex); } log2.LogError(val6); } try { val5.Patch((MethodBase)AccessTools.Method(typeof(SteamAPI), "RunCallbacks", (Type[])null, (Type[])null), new HarmonyMethod(typeof(SteamRunCallbacksPatch), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex2) { ManualLogSource log3 = ((BasePlugin)this).Log; BepInExErrorLogInterpolatedStringHandler val6 = new BepInExErrorLogInterpolatedStringHandler(75, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Could not patch SteamAPI.RunCallbacks (Steam invites off, IP still works): "); ((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<Exception>(ex2); } log3.LogError(val6); } Application.SetStackTraceLogType((LogType)4, (StackTraceLogType)2); ManualLogSource log4 = ((BasePlugin)this).Log; val = new BepInExInfoLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Soulstone Coop"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded, harmony patches applied."); } log4.LogInfo(val); } private void ParseLaunchArgs() { //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Expected O, but got Unknown string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { int result; int result2; int result3; if (commandLineArgs[i] == "--coop-host") { HostArg = true; } else if (commandLineArgs[i] == "--coop-connect" && i + 1 < commandLineArgs.Length) { ConnectAddressArg = commandLineArgs[i + 1]; } else if (commandLineArgs[i] == "--coop-fake-version" && i + 1 < commandLineArgs.Length) { FakeVersionArg = commandLineArgs[i + 1]; } else if (commandLineArgs[i] == "--coop-name" && i + 1 < commandLineArgs.Length) { NameArg = commandLineArgs[i + 1]; } else if (commandLineArgs[i] == "--coop-test" && i + 1 < commandLineArgs.Length) { TestArg = commandLineArgs[i + 1]; } else if (commandLineArgs[i] == "--coop-test-save" && i + 1 < commandLineArgs.Length) { TestSave.UseRealSave = commandLineArgs[i + 1] == "real"; } else if (commandLineArgs[i] == "--coop-sim-latency" && i + 1 < commandLineArgs.Length && int.TryParse(commandLineArgs[i + 1], out result)) { _simLatency = result; } else if (commandLineArgs[i] == "--coop-sim-jitter" && i + 1 < commandLineArgs.Length && int.TryParse(commandLineArgs[i + 1], out res
plugins/LiteNetLib.dll
Decompiled 18 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using LiteNetLib.Layers; using LiteNetLib.Utils; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Ruslan Pyrch")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2024 Ruslan Pyrch")] [assembly: AssemblyDescription("Lite reliable UDP library for .NET, Mono, and .NET Core")] [assembly: AssemblyFileVersion("1.3.1")] [assembly: AssemblyInformationalVersion("1.0.0+f57b9eafe72b924681a371d671af911478b6ab88")] [assembly: AssemblyProduct("LiteNetLib")] [assembly: AssemblyTitle("LiteNetLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/RevenantX/LiteNetLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.3.1.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } } namespace LiteNetLib { internal abstract class BaseChannel { protected readonly NetPeer Peer; protected readonly Queue<NetPacket> OutgoingQueue = new Queue<NetPacket>(64); private int _isAddedToPeerChannelSendQueue; public int PacketsInQueue => OutgoingQueue.Count; protected BaseChannel(NetPeer peer) { Peer = peer; } public void AddToQueue(NetPacket packet) { lock (OutgoingQueue) { OutgoingQueue.Enqueue(packet); } AddToPeerChannelSendQueue(); } protected void AddToPeerChannelSendQueue() { if (Interlocked.CompareExchange(ref _isAddedToPeerChannelSendQueue, 1, 0) == 0) { Peer.AddToReliableChannelSendQueue(this); } } public bool SendAndCheckQueue() { bool num = SendNextPackets(); if (!num) { Interlocked.Exchange(ref _isAddedToPeerChannelSendQueue, 0); } return num; } protected abstract bool SendNextPackets(); public abstract bool ProcessPacket(NetPacket packet); } internal enum ConnectionRequestResult { None, Accept, Reject, RejectForce } public class ConnectionRequest { private readonly NetManager _listener; private int _used; internal NetConnectRequestPacket InternalPacket; public readonly IPEndPoint RemoteEndPoint; public NetDataReader Data => InternalPacket.Data; internal ConnectionRequestResult Result { get; private set; } internal void UpdateRequest(NetConnectRequestPacket connectRequest) { if (connectRequest.ConnectionTime >= InternalPacket.ConnectionTime && (connectRequest.ConnectionTime != InternalPacket.ConnectionTime || connectRequest.ConnectionNumber != InternalPacket.ConnectionNumber)) { InternalPacket = connectRequest; } } private bool TryActivate() { return Interlocked.CompareExchange(ref _used, 1, 0) == 0; } internal ConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket, NetManager listener) { InternalPacket = requestPacket; RemoteEndPoint = remoteEndPoint; _listener = listener; } public NetPeer AcceptIfKey(string key) { if (!TryActivate()) { return null; } try { if (Data.GetString() == key) { Result = ConnectionRequestResult.Accept; } } catch { NetDebug.WriteError("[AC] Invalid incoming data"); } if (Result == ConnectionRequestResult.Accept) { return _listener.OnConnectionSolved(this, null, 0, 0); } Result = ConnectionRequestResult.Reject; _listener.OnConnectionSolved(this, null, 0, 0); return null; } public NetPeer Accept() { if (!TryActivate()) { return null; } Result = ConnectionRequestResult.Accept; return _listener.OnConnectionSolved(this, null, 0, 0); } public void Reject(byte[] rejectData, int start, int length, bool force) { if (TryActivate()) { Result = (force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject); _listener.OnConnectionSolved(this, rejectData, start, length); } } public void Reject(byte[] rejectData, int start, int length) { Reject(rejectData, start, length, force: false); } public void RejectForce(byte[] rejectData, int start, int length) { Reject(rejectData, start, length, force: true); } public void RejectForce() { Reject(null, 0, 0, force: true); } public void RejectForce(byte[] rejectData) { Reject(rejectData, 0, rejectData.Length, force: true); } public void RejectForce(NetDataWriter rejectData) { Reject(rejectData.Data, 0, rejectData.Length, force: true); } public void Reject() { Reject(null, 0, 0, force: false); } public void Reject(byte[] rejectData) { Reject(rejectData, 0, rejectData.Length, force: false); } public void Reject(NetDataWriter rejectData) { Reject(rejectData.Data, 0, rejectData.Length, force: false); } } public enum UnconnectedMessageType { BasicMessage, Broadcast } public enum DisconnectReason { ConnectionFailed, Timeout, HostUnreachable, NetworkUnreachable, RemoteConnectionClose, DisconnectPeerCalled, ConnectionRejected, InvalidProtocol, UnknownHost, Reconnect, PeerToPeerConnection, PeerNotFound } public struct DisconnectInfo { public DisconnectReason Reason; public SocketError SocketErrorCode; public NetPacketReader AdditionalData; } public interface INetEventListener { void OnPeerConnected(NetPeer peer); void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); void OnNetworkError(IPEndPoint endPoint, SocketError socketError); void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod); void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); void OnNetworkLatencyUpdate(NetPeer peer, int latency); void OnConnectionRequest(ConnectionRequest request); } public interface IDeliveryEventListener { void OnMessageDelivered(NetPeer peer, object userData); } public interface INtpEventListener { void OnNtpResponse(NtpPacket packet); } public interface IPeerAddressChangedListener { void OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress); } public class EventBasedNetListener : INetEventListener, IDeliveryEventListener, INtpEventListener, IPeerAddressChangedListener { public delegate void OnPeerConnected(NetPeer peer); public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError); public delegate void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod); public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency); public delegate void OnConnectionRequest(ConnectionRequest request); public delegate void OnDeliveryEvent(NetPeer peer, object userData); public delegate void OnNtpResponseEvent(NtpPacket packet); public delegate void OnPeerAddressChangedEvent(NetPeer peer, IPEndPoint previousAddress); public event OnPeerConnected PeerConnectedEvent; public event OnPeerDisconnected PeerDisconnectedEvent; public event OnNetworkError NetworkErrorEvent; public event OnNetworkReceive NetworkReceiveEvent; public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent; public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent; public event OnConnectionRequest ConnectionRequestEvent; public event OnDeliveryEvent DeliveryEvent; public event OnNtpResponseEvent NtpResponseEvent; public event OnPeerAddressChangedEvent PeerAddressChangedEvent; public void ClearPeerConnectedEvent() { this.PeerConnectedEvent = null; } public void ClearPeerDisconnectedEvent() { this.PeerDisconnectedEvent = null; } public void ClearNetworkErrorEvent() { this.NetworkErrorEvent = null; } public void ClearNetworkReceiveEvent() { this.NetworkReceiveEvent = null; } public void ClearNetworkReceiveUnconnectedEvent() { this.NetworkReceiveUnconnectedEvent = null; } public void ClearNetworkLatencyUpdateEvent() { this.NetworkLatencyUpdateEvent = null; } public void ClearConnectionRequestEvent() { this.ConnectionRequestEvent = null; } public void ClearDeliveryEvent() { this.DeliveryEvent = null; } public void ClearNtpResponseEvent() { this.NtpResponseEvent = null; } public void ClearPeerAddressChangedEvent() { this.PeerAddressChangedEvent = null; } void INetEventListener.OnPeerConnected(NetPeer peer) { if (this.PeerConnectedEvent != null) { this.PeerConnectedEvent(peer); } } void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { if (this.PeerDisconnectedEvent != null) { this.PeerDisconnectedEvent(peer, disconnectInfo); } } void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode) { if (this.NetworkErrorEvent != null) { this.NetworkErrorEvent(endPoint, socketErrorCode); } } void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod) { if (this.NetworkReceiveEvent != null) { this.NetworkReceiveEvent(peer, reader, channelNumber, deliveryMethod); } } void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType) { if (this.NetworkReceiveUnconnectedEvent != null) { this.NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType); } } void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency) { if (this.NetworkLatencyUpdateEvent != null) { this.NetworkLatencyUpdateEvent(peer, latency); } } void INetEventListener.OnConnectionRequest(ConnectionRequest request) { if (this.ConnectionRequestEvent != null) { this.ConnectionRequestEvent(request); } } void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object userData) { if (this.DeliveryEvent != null) { this.DeliveryEvent(peer, userData); } } void INtpEventListener.OnNtpResponse(NtpPacket packet) { if (this.NtpResponseEvent != null) { this.NtpResponseEvent(packet); } } void IPeerAddressChangedListener.OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress) { if (this.PeerAddressChangedEvent != null) { this.PeerAddressChangedEvent(peer, previousAddress); } } } internal sealed class NetConnectRequestPacket { public const int HeaderSize = 18; public readonly long ConnectionTime; public byte ConnectionNumber; public readonly byte[] TargetAddress; public readonly NetDataReader Data; public readonly int PeerId; private NetConnectRequestPacket(long connectionTime, byte connectionNumber, int localId, byte[] targetAddress, NetDataReader data) { ConnectionTime = connectionTime; ConnectionNumber = connectionNumber; TargetAddress = targetAddress; Data = data; PeerId = localId; } public static int GetProtocolId(NetPacket packet) { return BitConverter.ToInt32(packet.RawData, 1); } public static NetConnectRequestPacket FromData(NetPacket packet) { if (packet.ConnectionNumber >= 4) { return null; } long connectionTime = BitConverter.ToInt64(packet.RawData, 5); int localId = BitConverter.ToInt32(packet.RawData, 13); int num = packet.RawData[17]; if (num != 16 && num != 28) { return null; } byte[] array = new byte[num]; Buffer.BlockCopy(packet.RawData, 18, array, 0, num); NetDataReader netDataReader = new NetDataReader(null, 0, 0); if (packet.Size > 18 + num) { netDataReader.SetSource(packet.RawData, 18 + num, packet.Size); } return new NetConnectRequestPacket(connectionTime, packet.ConnectionNumber, localId, array, netDataReader); } public static NetPacket Make(NetDataWriter connectData, SocketAddress addressBytes, long connectTime, int localId) { NetPacket netPacket = new NetPacket(PacketProperty.ConnectRequest, connectData.Length + addressBytes.Size); FastBitConverter.GetBytes(netPacket.RawData, 1, 13); FastBitConverter.GetBytes(netPacket.RawData, 5, connectTime); FastBitConverter.GetBytes(netPacket.RawData, 13, localId); netPacket.RawData[17] = (byte)addressBytes.Size; for (int i = 0; i < addressBytes.Size; i++) { netPacket.RawData[18 + i] = addressBytes[i]; } Buffer.BlockCopy(connectData.Data, 0, netPacket.RawData, 18 + addressBytes.Size, connectData.Length); return netPacket; } } internal sealed class NetConnectAcceptPacket { public const int Size = 15; public readonly long ConnectionTime; public readonly byte ConnectionNumber; public readonly int PeerId; public readonly bool PeerNetworkChanged; private NetConnectAcceptPacket(long connectionTime, byte connectionNumber, int peerId, bool peerNetworkChanged) { ConnectionTime = connectionTime; ConnectionNumber = connectionNumber; PeerId = peerId; PeerNetworkChanged = peerNetworkChanged; } public static NetConnectAcceptPacket FromData(NetPacket packet) { if (packet.Size != 15) { return null; } long connectionTime = BitConverter.ToInt64(packet.RawData, 1); byte b = packet.RawData[9]; if (b >= 4) { return null; } byte b2 = packet.RawData[10]; if (b2 > 1) { return null; } int num = BitConverter.ToInt32(packet.RawData, 11); if (num < 0) { return null; } return new NetConnectAcceptPacket(connectionTime, b, num, b2 == 1); } public static NetPacket Make(long connectTime, byte connectNum, int localPeerId) { NetPacket netPacket = new NetPacket(PacketProperty.ConnectAccept, 0); FastBitConverter.GetBytes(netPacket.RawData, 1, connectTime); netPacket.RawData[9] = connectNum; FastBitConverter.GetBytes(netPacket.RawData, 11, localPeerId); return netPacket; } public static NetPacket MakeNetworkChanged(NetPeer peer) { NetPacket netPacket = new NetPacket(PacketProperty.PeerNotFound, 14); FastBitConverter.GetBytes(netPacket.RawData, 1, peer.ConnectTime); netPacket.RawData[9] = peer.ConnectionNum; netPacket.RawData[10] = 1; FastBitConverter.GetBytes(netPacket.RawData, 11, peer.RemoteId); return netPacket; } } internal static class NativeSocket { private static class WinSock { private const string LibName = "ws2_32.dll"; [DllImport("ws2_32.dll", SetLastError = true)] public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize); [DllImport("ws2_32.dll", SetLastError = true)] internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize); } private static class UnixSock { private const string LibName = "libc"; [DllImport("libc", SetLastError = true)] public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize); [DllImport("libc", SetLastError = true)] internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize); } public static readonly bool IsSupported; public static readonly bool UnixMode; public const int IPv4AddrSize = 16; public const int IPv6AddrSize = 28; public const int AF_INET = 2; public const int AF_INET6 = 10; private static readonly Dictionary<int, SocketError> NativeErrorToSocketError; static NativeSocket() { IsSupported = false; UnixMode = false; NativeErrorToSocketError = new Dictionary<int, SocketError> { { 13, SocketError.AccessDenied }, { 98, SocketError.AddressAlreadyInUse }, { 99, SocketError.AddressNotAvailable }, { 97, SocketError.AddressFamilyNotSupported }, { 11, SocketError.WouldBlock }, { 114, SocketError.AlreadyInProgress }, { 9, SocketError.OperationAborted }, { 125, SocketError.OperationAborted }, { 103, SocketError.ConnectionAborted }, { 111, SocketError.ConnectionRefused }, { 104, SocketError.ConnectionReset }, { 89, SocketError.DestinationAddressRequired }, { 14, SocketError.Fault }, { 112, SocketError.HostDown }, { 6, SocketError.HostNotFound }, { 113, SocketError.HostUnreachable }, { 115, SocketError.InProgress }, { 4, SocketError.Interrupted }, { 22, SocketError.InvalidArgument }, { 106, SocketError.IsConnected }, { 24, SocketError.TooManyOpenSockets }, { 90, SocketError.MessageSize }, { 100, SocketError.NetworkDown }, { 102, SocketError.NetworkReset }, { 101, SocketError.NetworkUnreachable }, { 23, SocketError.TooManyOpenSockets }, { 105, SocketError.NoBufferSpaceAvailable }, { 61, SocketError.NoData }, { 2, SocketError.AddressNotAvailable }, { 92, SocketError.ProtocolOption }, { 107, SocketError.NotConnected }, { 88, SocketError.NotSocket }, { 3440, SocketError.OperationNotSupported }, { 1, SocketError.AccessDenied }, { 32, SocketError.Shutdown }, { 96, SocketError.ProtocolFamilyNotSupported }, { 93, SocketError.ProtocolNotSupported }, { 91, SocketError.ProtocolType }, { 94, SocketError.SocketNotSupported }, { 108, SocketError.Disconnecting }, { 110, SocketError.TimedOut }, { 0, SocketError.Success } }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { IsSupported = true; UnixMode = true; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { IsSupported = true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int RecvFrom(IntPtr socketHandle, byte[] pinnedBuffer, int len, byte[] socketAddress, ref int socketAddressSize) { if (!UnixMode) { return WinSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize); } return UnixSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int SendTo(IntPtr socketHandle, byte* pinnedBuffer, int len, byte[] socketAddress, int socketAddressSize) { if (!UnixMode) { return WinSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize); } return UnixSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize); } public static SocketError GetSocketError() { int lastWin32Error = Marshal.GetLastWin32Error(); if (UnixMode) { if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value)) { return SocketError.SocketError; } return value; } return (SocketError)lastWin32Error; } public static SocketException GetSocketException() { int lastWin32Error = Marshal.GetLastWin32Error(); if (UnixMode) { if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value)) { return new SocketException(-1); } return new SocketException((int)value); } return new SocketException(lastWin32Error); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetNativeAddressFamily(IPEndPoint remoteEndPoint) { if (!UnixMode) { return (short)remoteEndPoint.AddressFamily; } return (short)((remoteEndPoint.AddressFamily == AddressFamily.InterNetwork) ? 2 : 10); } } public enum NatAddressType { Internal, External } public interface INatPunchListener { void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); } public class EventBasedNatPunchListener : INatPunchListener { public delegate void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); public delegate void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); public event OnNatIntroductionRequest NatIntroductionRequest; public event OnNatIntroductionSuccess NatIntroductionSuccess; void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token) { if (this.NatIntroductionRequest != null) { this.NatIntroductionRequest(localEndPoint, remoteEndPoint, token); } } void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token) { if (this.NatIntroductionSuccess != null) { this.NatIntroductionSuccess(targetEndPoint, type, token); } } } public sealed class NatPunchModule { private struct RequestEventData { public IPEndPoint LocalEndPoint; public IPEndPoint RemoteEndPoint; public string Token; } private struct SuccessEventData { public IPEndPoint TargetEndPoint; public NatAddressType Type; public string Token; } private class NatIntroduceRequestPacket { public IPEndPoint Internal { [Preserve] get; [Preserve] set; } public string Token { [Preserve] get; [Preserve] set; } } private class NatIntroduceResponsePacket { public IPEndPoint Internal { [Preserve] get; [Preserve] set; } public IPEndPoint External { [Preserve] get; [Preserve] set; } public string Token { [Preserve] get; [Preserve] set; } } private class NatPunchPacket { public string Token { [Preserve] get; [Preserve] set; } public bool IsExternal { [Preserve] get; [Preserve] set; } } private readonly NetManager _socket; private readonly ConcurrentQueue<RequestEventData> _requestEvents = new ConcurrentQueue<RequestEventData>(); private readonly ConcurrentQueue<SuccessEventData> _successEvents = new ConcurrentQueue<SuccessEventData>(); private readonly NetDataReader _cacheReader = new NetDataReader(); private readonly NetDataWriter _cacheWriter = new NetDataWriter(); private readonly NetPacketProcessor _netPacketProcessor = new NetPacketProcessor(256); private INatPunchListener _natPunchListener; public const int MaxTokenLength = 256; public bool UnsyncedEvents; internal NatPunchModule(NetManager socket) { _socket = socket; _netPacketProcessor.SubscribeReusable<NatIntroduceResponsePacket>(OnNatIntroductionResponse); _netPacketProcessor.SubscribeReusable<NatIntroduceRequestPacket, IPEndPoint>(OnNatIntroductionRequest); _netPacketProcessor.SubscribeReusable<NatPunchPacket, IPEndPoint>(OnNatPunch); } internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet) { lock (_cacheReader) { _cacheReader.SetSource(packet.RawData, 1, packet.Size); _netPacketProcessor.ReadAllPackets(_cacheReader, senderEndPoint); } } public void Init(INatPunchListener listener) { _natPunchListener = listener; } private void Send<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T packet, IPEndPoint target) where T : class, new() { _cacheWriter.Reset(); _cacheWriter.Put((byte)16); _netPacketProcessor.Write(_cacheWriter, packet); _socket.SendRaw(_cacheWriter.Data, 0, _cacheWriter.Length, target); } public void NatIntroduce(IPEndPoint hostInternal, IPEndPoint hostExternal, IPEndPoint clientInternal, IPEndPoint clientExternal, string additionalInfo) { NatIntroduceResponsePacket natIntroduceResponsePacket = new NatIntroduceResponsePacket { Token = additionalInfo }; natIntroduceResponsePacket.Internal = hostInternal; natIntroduceResponsePacket.External = hostExternal; Send(natIntroduceResponsePacket, clientExternal); natIntroduceResponsePacket.Internal = clientInternal; natIntroduceResponsePacket.External = clientExternal; Send(natIntroduceResponsePacket, hostExternal); } public void PollEvents() { if (!UnsyncedEvents && _natPunchListener != null && (!_successEvents.IsEmpty || !_requestEvents.IsEmpty)) { SuccessEventData result; while (_successEvents.TryDequeue(out result)) { _natPunchListener.OnNatIntroductionSuccess(result.TargetEndPoint, result.Type, result.Token); } RequestEventData result2; while (_requestEvents.TryDequeue(out result2)) { _natPunchListener.OnNatIntroductionRequest(result2.LocalEndPoint, result2.RemoteEndPoint, result2.Token); } } } public void SendNatIntroduceRequest(string host, int port, string additionalInfo) { SendNatIntroduceRequest(NetUtils.MakeEndPoint(host, port), additionalInfo); } public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, string additionalInfo) { string localIp = NetUtils.GetLocalIp(LocalAddrType.IPv4); if (string.IsNullOrEmpty(localIp) || masterServerEndPoint.AddressFamily == AddressFamily.InterNetworkV6) { localIp = NetUtils.GetLocalIp(LocalAddrType.IPv6); } Send(new NatIntroduceRequestPacket { Internal = NetUtils.MakeEndPoint(localIp, _socket.LocalPort), Token = additionalInfo }, masterServerEndPoint); } private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, IPEndPoint senderEndPoint) { if (UnsyncedEvents) { _natPunchListener.OnNatIntroductionRequest(req.Internal, senderEndPoint, req.Token); return; } _requestEvents.Enqueue(new RequestEventData { LocalEndPoint = req.Internal, RemoteEndPoint = senderEndPoint, Token = req.Token }); } private void OnNatIntroductionResponse(NatIntroduceResponsePacket req) { NatPunchPacket natPunchPacket = new NatPunchPacket { Token = req.Token }; Send(natPunchPacket, req.Internal); _socket.Ttl = 2; _socket.SendRaw(new byte[1] { 17 }, 0, 1, req.External); _socket.Ttl = 255; natPunchPacket.IsExternal = true; Send(natPunchPacket, req.External); } private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint) { if (UnsyncedEvents) { _natPunchListener.OnNatIntroductionSuccess(senderEndPoint, req.IsExternal ? NatAddressType.External : NatAddressType.Internal, req.Token); return; } _successEvents.Enqueue(new SuccessEventData { TargetEndPoint = senderEndPoint, Type = (req.IsExternal ? NatAddressType.External : NatAddressType.Internal), Token = req.Token }); } } public enum DeliveryMethod : byte { Unreliable = 4, ReliableUnordered = 0, Sequenced = 1, ReliableOrdered = 2, ReliableSequenced = 3 } public static class NetConstants { public const int DefaultWindowSize = 64; public const int SocketBufferSize = 1048576; public const int SocketTTL = 255; public const int HeaderSize = 1; public const int ChanneledHeaderSize = 4; public const int FragmentHeaderSize = 6; public const int FragmentedHeaderTotalSize = 10; public const ushort MaxSequence = 32768; public const ushort HalfMaxSequence = 16384; internal const int ProtocolId = 13; internal const int MaxUdpHeaderSize = 68; internal const int ChannelTypeCount = 4; internal static readonly int[] PossibleMtu = new int[6] { 1024, 1164, 1392, 1404, 1424, 1432 }; public static readonly int InitialMtu = PossibleMtu[0]; public static readonly int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1]; public static readonly int MaxUnreliableDataSize = MaxPacketSize - 1; public const byte MaxConnectionNumber = 4; } public class InvalidPacketException : ArgumentException { public InvalidPacketException(string message) : base(message) { } } public class TooBigPacketException : InvalidPacketException { public TooBigPacketException(string message) : base(message) { } } public enum NetLogLevel { Warning, Error, Trace, Info } public interface INetLogger { void WriteNet(NetLogLevel level, string str, params object[] args); } public static class NetDebug { public static INetLogger Logger = null; private static readonly object DebugLogLock = new object(); private static void WriteLogic(NetLogLevel logLevel, string str, params object[] args) { lock (DebugLogLock) { if (Logger == null) { Console.WriteLine(str, args); } else { Logger.WriteNet(logLevel, str, args); } } } [Conditional("DEBUG_MESSAGES")] internal static void Write(string str) { WriteLogic(NetLogLevel.Trace, str); } [Conditional("DEBUG_MESSAGES")] internal static void Write(NetLogLevel level, string str) { WriteLogic(level, str); } [Conditional("DEBUG_MESSAGES")] [Conditional("DEBUG")] internal static void WriteForce(string str) { WriteLogic(NetLogLevel.Trace, str); } [Conditional("DEBUG_MESSAGES")] [Conditional("DEBUG")] internal static void WriteForce(NetLogLevel level, string str) { WriteLogic(level, str); } internal static void WriteError(string str) { WriteLogic(NetLogLevel.Error, str); } } public sealed class NetPacketReader : NetDataReader { private NetPacket _packet; private readonly NetManager _manager; private readonly NetEvent _evt; internal NetPacketReader(NetManager manager, NetEvent evt) { _manager = manager; _evt = evt; } internal void SetSource(NetPacket packet, int headerSize) { if (packet != null) { _packet = packet; SetSource(packet.RawData, headerSize, packet.Size); } } internal void RecycleInternal() { Clear(); if (_packet != null) { _manager.PoolRecycle(_packet); } _packet = null; _manager.RecycleEvent(_evt); } public void Recycle() { if (!_manager.AutoRecycle) { RecycleInternal(); } } } internal sealed class NetEvent { public enum EType { Connect, Disconnect, Receive, ReceiveUnconnected, Error, ConnectionLatencyUpdated, Broadcast, ConnectionRequest, MessageDelivered, PeerAddressChanged } public NetEvent Next; public EType Type; public NetPeer Peer; public IPEndPoint RemoteEndPoint; public object UserData; public int Latency; public SocketError ErrorCode; public DisconnectReason DisconnectReason; public ConnectionRequest ConnectionRequest; public DeliveryMethod DeliveryMethod; public byte ChannelNumber; public readonly NetPacketReader DataReader; public NetEvent(NetManager manager) { DataReader = new NetPacketReader(manager, this); } } public class NetManager : IEnumerable<NetPeer>, IEnumerable { public struct NetPeerEnumerator : IEnumerator<NetPeer>, IEnumerator, IDisposable { private readonly NetPeer _initialPeer; private NetPeer _p; public NetPeer Current => _p; object IEnumerator.Current => _p; public NetPeerEnumerator(NetPeer p) { _initialPeer = p; _p = null; } public void Dispose() { } public bool MoveNext() { _p = ((_p == null) ? _initialPeer : _p.NextPeer); return _p != null; } public void Reset() { throw new NotSupportedException(); } } private struct IncomingData { public NetPacket Data; public IPEndPoint EndPoint; public DateTime TimeWhenGet; } private struct Slot { internal int HashCode; internal int Next; internal NetPeer Value; } private readonly List<IncomingData> _pingSimulationList = new List<IncomingData>(); private readonly Random _randomGenerator = new Random(); private const int MinLatencyThreshold = 5; private Thread _logicThread; private bool _manualMode; private readonly AutoResetEvent _updateTriggerEvent = new AutoResetEvent(initialState: true); private NetEvent _pendingEventHead; private NetEvent _pendingEventTail; private NetEvent _netEventPoolHead; private readonly INetEventListener _netEventListener; private readonly IDeliveryEventListener _deliveryEventListener; private readonly INtpEventListener _ntpEventListener; private readonly IPeerAddressChangedListener _peerAddressChangedListener; private readonly Dictionary<IPEndPoint, ConnectionRequest> _requestsDict = new Dictionary<IPEndPoint, ConnectionRequest>(); private readonly ConcurrentDictionary<IPEndPoint, NtpRequest> _ntpRequests = new ConcurrentDictionary<IPEndPoint, NtpRequest>(); private long _connectedPeersCount; private readonly List<NetPeer> _connectedPeerListCache = new List<NetPeer>(); private readonly PacketLayerBase _extraPacketLayer; private int _lastPeerId; private ConcurrentQueue<int> _peerIds = new ConcurrentQueue<int>(); private byte _channelsCount = 1; private readonly object _eventLock = new object(); private bool _dropPacket; public bool UnconnectedMessagesEnabled; public bool NatPunchEnabled; public int UpdateTime = 15; public int PingInterval = 1000; public int DisconnectTimeout = 5000; public bool SimulatePacketLoss; public bool SimulateLatency; public int SimulationPacketLossChance = 10; public int SimulationMinLatency = 30; public int SimulationMaxLatency = 100; public bool UnsyncedEvents; public bool UnsyncedReceiveEvent; public bool UnsyncedDeliveryEvent; public bool BroadcastReceiveEnabled; public int ReconnectDelay = 500; public int MaxConnectAttempts = 10; public bool ReuseAddress; public bool DontRoute; public readonly NetStatistics Statistics = new NetStatistics(); public bool EnableStatistics; public readonly NatPunchModule NatPunchModule; public bool AutoRecycle; public bool IPv6Enabled = true; public int MtuOverride; public bool MtuDiscovery; public bool UseNativeSockets; public bool DisconnectOnUnreachable; public bool AllowPeerAddressChange; private const int MaxPrimeArrayLength = 2147483587; private const int HashPrime = 101; private const int Lower31BitMask = int.MaxValue; private static readonly int[] Primes; private int[] _buckets; private Slot[] _slots; private int _count; private int _lastIndex; private int _freeList = -1; private NetPeer[] _peersArray = new NetPeer[32]; private readonly ReaderWriterLockSlim _peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private volatile NetPeer _headPeer; private NetPacket _poolHead; private int _poolCount; private readonly object _poolLock = new object(); public int PacketPoolSize = 1000; private const int ReceivePollingTime = 500000; private Socket _udpSocketv4; private Socket _udpSocketv6; private Thread _receiveThread; private IPEndPoint _bufferEndPointv4; private IPEndPoint _bufferEndPointv6; private const int SioUdpConnreset = -1744830452; private static readonly IPAddress MulticastAddressV6; public static readonly bool IPv6Support; internal bool NotConnected; public bool IsRunning { get; private set; } public int LocalPort { get; private set; } public NetPeer FirstPeer => _headPeer; public byte ChannelsCount { get { return _channelsCount; } set { if (value < 1 || value > 64) { throw new ArgumentException("Channels count must be between 1 and 64"); } _channelsCount = value; } } public List<NetPeer> ConnectedPeerList { get { GetPeersNonAlloc(_connectedPeerListCache, ConnectionState.Connected); return _connectedPeerListCache; } } public int ConnectedPeersCount => (int)Interlocked.Read(ref _connectedPeersCount); public int ExtraPacketSizeForLayer => _extraPacketLayer?.ExtraPacketSizeForLayer ?? 0; public int PoolCount => _poolCount; public short Ttl { get { return _udpSocketv4.Ttl; } internal set { _udpSocketv4.Ttl = value; } } public NetManager(INetEventListener listener, PacketLayerBase extraPacketLayer = null) { _netEventListener = listener; _deliveryEventListener = listener as IDeliveryEventListener; _ntpEventListener = listener as INtpEventListener; _peerAddressChangedListener = listener as IPeerAddressChangedListener; NatPunchModule = new NatPunchModule(this); _extraPacketLayer = extraPacketLayer; } internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency) { CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, null, SocketError.Success, latency, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } internal void MessageDelivered(NetPeer fromPeer, object userData) { if (_deliveryEventListener != null) { CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, null, userData); } } internal void DisconnectPeerForce(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, NetPacket eventData) { DisconnectPeer(peer, reason, socketErrorCode, force: true, null, 0, 0, eventData); } private void DisconnectPeer(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, bool force, byte[] data, int start, int count, NetPacket eventData) { switch (peer.Shutdown(data, start, count, force)) { case ShutdownResult.None: return; case ShutdownResult.WasConnected: Interlocked.Decrement(ref _connectedPeersCount); break; } CreateEvent(NetEvent.EType.Disconnect, peer, null, socketErrorCode, 0, reason, null, DeliveryMethod.Unreliable, 0, eventData); } private void CreateEvent(NetEvent.EType type, NetPeer peer = null, IPEndPoint remoteEndPoint = null, SocketError errorCode = SocketError.Success, int latency = 0, DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed, ConnectionRequest connectionRequest = null, DeliveryMethod deliveryMethod = DeliveryMethod.Unreliable, byte channelNumber = 0, NetPacket readerSource = null, object userData = null) { bool flag = UnsyncedEvents; switch (type) { case NetEvent.EType.Connect: Interlocked.Increment(ref _connectedPeersCount); break; case NetEvent.EType.MessageDelivered: flag = UnsyncedDeliveryEvent; break; } NetEvent netEvent; lock (_eventLock) { netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } } netEvent.Next = null; netEvent.Type = type; netEvent.DataReader.SetSource(readerSource, readerSource?.GetHeaderSize() ?? 0); netEvent.Peer = peer; netEvent.RemoteEndPoint = remoteEndPoint; netEvent.Latency = latency; netEvent.ErrorCode = errorCode; netEvent.DisconnectReason = disconnectReason; netEvent.ConnectionRequest = connectionRequest; netEvent.DeliveryMethod = deliveryMethod; netEvent.ChannelNumber = channelNumber; netEvent.UserData = userData; if (flag || _manualMode) { ProcessEvent(netEvent); return; } lock (_eventLock) { if (_pendingEventTail == null) { _pendingEventHead = netEvent; } else { _pendingEventTail.Next = netEvent; } _pendingEventTail = netEvent; } } private void ProcessEvent(NetEvent evt) { bool isNull = evt.DataReader.IsNull; switch (evt.Type) { case NetEvent.EType.Connect: _netEventListener.OnPeerConnected(evt.Peer); break; case NetEvent.EType.Disconnect: { DisconnectInfo disconnectInfo = default(DisconnectInfo); disconnectInfo.Reason = evt.DisconnectReason; disconnectInfo.AdditionalData = evt.DataReader; disconnectInfo.SocketErrorCode = evt.ErrorCode; DisconnectInfo disconnectInfo2 = disconnectInfo; _netEventListener.OnPeerDisconnected(evt.Peer, disconnectInfo2); break; } case NetEvent.EType.Receive: _netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, evt.ChannelNumber, evt.DeliveryMethod); break; case NetEvent.EType.ReceiveUnconnected: _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.BasicMessage); break; case NetEvent.EType.Broadcast: _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Broadcast); break; case NetEvent.EType.Error: _netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.ErrorCode); break; case NetEvent.EType.ConnectionLatencyUpdated: _netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.Latency); break; case NetEvent.EType.ConnectionRequest: _netEventListener.OnConnectionRequest(evt.ConnectionRequest); break; case NetEvent.EType.MessageDelivered: _deliveryEventListener.OnMessageDelivered(evt.Peer, evt.UserData); break; case NetEvent.EType.PeerAddressChanged: { _peersLock.EnterUpgradeableReadLock(); IPEndPoint iPEndPoint = null; if (ContainsPeer(evt.Peer)) { _peersLock.EnterWriteLock(); RemovePeerFromSet(evt.Peer); iPEndPoint = new IPEndPoint(evt.Peer.Address, evt.Peer.Port); evt.Peer.FinishEndPointChange(evt.RemoteEndPoint); AddPeerToSet(evt.Peer); _peersLock.ExitWriteLock(); } _peersLock.ExitUpgradeableReadLock(); if (iPEndPoint != null && _peerAddressChangedListener != null) { _peerAddressChangedListener.OnPeerAddressChanged(evt.Peer, iPEndPoint); } break; } } if (isNull) { RecycleEvent(evt); } else if (AutoRecycle) { evt.DataReader.RecycleInternal(); } } internal void RecycleEvent(NetEvent evt) { evt.Peer = null; evt.ErrorCode = SocketError.Success; evt.RemoteEndPoint = null; evt.ConnectionRequest = null; lock (_eventLock) { evt.Next = _netEventPoolHead; _netEventPoolHead = evt; } } private void UpdateLogic() { List<NetPeer> list = new List<NetPeer>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (IsRunning) { try { float num = (float)((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0); num = ((num <= 0f) ? 0.001f : num); stopwatch.Restart(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout) { list.Add(netPeer); } else { netPeer.Update(num); } } if (list.Count > 0) { _peersLock.EnterWriteLock(); for (int i = 0; i < list.Count; i++) { RemovePeer(list[i], enableWriteLock: false); } _peersLock.ExitWriteLock(); list.Clear(); } ProcessNtpRequests(num); int num2 = UpdateTime - (int)stopwatch.ElapsedMilliseconds; if (num2 > 0) { _updateTriggerEvent.WaitOne(num2); } } catch (ThreadAbortException) { return; } catch (Exception ex2) { NetDebug.WriteError("[NM] LogicThread error: " + ex2); } } stopwatch.Stop(); } [Conditional("DEBUG")] private void ProcessDelayedPackets() { if (!SimulateLatency) { return; } DateTime utcNow = DateTime.UtcNow; lock (_pingSimulationList) { for (int i = 0; i < _pingSimulationList.Count; i++) { IncomingData incomingData = _pingSimulationList[i]; if (incomingData.TimeWhenGet <= utcNow) { HandleMessageReceived(incomingData.Data, incomingData.EndPoint); _pingSimulationList.RemoveAt(i); i--; } } } } private void ProcessNtpRequests(float elapsedMilliseconds) { List<IPEndPoint> list = null; foreach (KeyValuePair<IPEndPoint, NtpRequest> ntpRequest in _ntpRequests) { ntpRequest.Value.Send(_udpSocketv4, elapsedMilliseconds); if (ntpRequest.Value.NeedToKill) { if (list == null) { list = new List<IPEndPoint>(); } list.Add(ntpRequest.Key); } } if (list == null) { return; } foreach (IPEndPoint item in list) { _ntpRequests.TryRemove(item, out var _); } } public void ManualUpdate(float elapsedMilliseconds) { if (!_manualMode) { return; } for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout) { RemovePeer(netPeer, enableWriteLock: false); } else { netPeer.Update(elapsedMilliseconds); } } ProcessNtpRequests(elapsedMilliseconds); } internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] rejectData, int start, int length) { NetPeer actualValue = null; if (request.Result == ConnectionRequestResult.RejectForce) { if (rejectData != null && length > 0) { NetPacket netPacket = PoolGetWithProperty(PacketProperty.Disconnect, length); netPacket.ConnectionNumber = request.InternalPacket.ConnectionNumber; FastBitConverter.GetBytes(netPacket.RawData, 1, request.InternalPacket.ConnectionTime); if (netPacket.Size >= NetConstants.PossibleMtu[0]) { NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU!"); } else { Buffer.BlockCopy(rejectData, start, netPacket.RawData, 9, length); } SendRawAndRecycle(netPacket, request.RemoteEndPoint); } lock (_requestsDict) { _requestsDict.Remove(request.RemoteEndPoint); } } else { lock (_requestsDict) { if (!TryGetPeer(request.RemoteEndPoint, out actualValue)) { if (request.Result == ConnectionRequestResult.Reject) { actualValue = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId()); actualValue.Reject(request.InternalPacket, rejectData, start, length); AddPeer(actualValue); } else { actualValue = new NetPeer(this, request, GetNextPeerId()); AddPeer(actualValue); CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } } _requestsDict.Remove(request.RemoteEndPoint); } } return actualValue; } private int GetNextPeerId() { if (!_peerIds.TryDequeue(out var result)) { return _lastPeerId++; } return result; } private void ProcessConnectRequest(IPEndPoint remoteEndPoint, NetPeer netPeer, NetConnectRequestPacket connRequest) { if (netPeer != null) { ConnectRequestResult connectRequestResult = netPeer.ProcessConnectRequest(connRequest); switch (connectRequestResult) { default: return; case ConnectRequestResult.Reconnection: DisconnectPeerForce(netPeer, DisconnectReason.Reconnect, SocketError.Success, null); RemovePeer(netPeer, enableWriteLock: true); break; case ConnectRequestResult.NewConnection: RemovePeer(netPeer, enableWriteLock: true); break; case ConnectRequestResult.P2PLose: DisconnectPeerForce(netPeer, DisconnectReason.PeerToPeerConnection, SocketError.Success, null); RemovePeer(netPeer, enableWriteLock: true); break; } if (connectRequestResult != ConnectRequestResult.P2PLose) { connRequest.ConnectionNumber = (byte)((netPeer.ConnectionNum + 1) % 4); } } ConnectionRequest value; lock (_requestsDict) { if (_requestsDict.TryGetValue(remoteEndPoint, out value)) { value.UpdateRequest(connRequest); return; } value = new ConnectionRequest(remoteEndPoint, connRequest, this); _requestsDict.Add(remoteEndPoint, value); } CreateEvent(NetEvent.EType.ConnectionRequest, null, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, value, DeliveryMethod.Unreliable, 0); } private void OnMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint) { if (packet.Size == 0) { PoolRecycle(packet); return; } _dropPacket = false; if (!_dropPacket) { HandleMessageReceived(packet, remoteEndPoint); } } [Conditional("DEBUG")] private void HandleSimulateLatency(NetPacket packet, IPEndPoint remoteEndPoint) { if (!SimulateLatency) { return; } int num = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency); if (num > 5) { lock (_pingSimulationList) { _pingSimulationList.Add(new IncomingData { Data = packet, EndPoint = remoteEndPoint, TimeWhenGet = DateTime.UtcNow.AddMilliseconds(num) }); } _dropPacket = true; } } [Conditional("DEBUG")] private void HandleSimulatePacketLoss() { if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100.0 < (double)SimulationPacketLossChance) { _dropPacket = true; } } private void HandleMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint) { int size = packet.Size; if (EnableStatistics) { Statistics.IncrementPacketsReceived(); Statistics.AddBytesReceived(size); } if (_ntpRequests.Count > 0 && _ntpRequests.TryGetValue(remoteEndPoint, out var _)) { if (packet.Size >= 48) { byte[] array = new byte[packet.Size]; Buffer.BlockCopy(packet.RawData, 0, array, 0, packet.Size); NtpPacket ntpPacket = NtpPacket.FromServerResponse(array, DateTime.UtcNow); try { ntpPacket.ValidateReply(); } catch (InvalidOperationException) { ntpPacket = null; } if (ntpPacket != null) { _ntpRequests.TryRemove(remoteEndPoint, out var _); _ntpEventListener?.OnNtpResponse(ntpPacket); } } return; } if (_extraPacketLayer != null) { _extraPacketLayer.ProcessInboundPacket(ref remoteEndPoint, ref packet.RawData, ref packet.Size); if (packet.Size == 0) { return; } } if (!packet.Verify()) { NetDebug.WriteError("[NM] DataReceived: bad!"); PoolRecycle(packet); return; } switch (packet.Property) { case PacketProperty.ConnectRequest: if (NetConnectRequestPacket.GetProtocolId(packet) != 13) { SendRawAndRecycle(PoolGetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint); return; } break; case PacketProperty.Broadcast: if (BroadcastReceiveEnabled) { CreateEvent(NetEvent.EType.Broadcast, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet); } return; case PacketProperty.UnconnectedMessage: if (UnconnectedMessagesEnabled) { CreateEvent(NetEvent.EType.ReceiveUnconnected, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet); } return; case PacketProperty.NatMessage: if (NatPunchEnabled) { NatPunchModule.ProcessMessage(remoteEndPoint, packet); } return; } NetPeer actualValue = remoteEndPoint as NetPeer; bool flag = actualValue != null || TryGetPeer(remoteEndPoint, out actualValue); if (flag && EnableStatistics) { actualValue.Statistics.IncrementPacketsReceived(); actualValue.Statistics.AddBytesReceived(size); } switch (packet.Property) { case PacketProperty.ConnectRequest: { NetConnectRequestPacket netConnectRequestPacket = NetConnectRequestPacket.FromData(packet); if (netConnectRequestPacket != null) { ProcessConnectRequest(remoteEndPoint, actualValue, netConnectRequestPacket); } break; } case PacketProperty.PeerNotFound: if (flag) { if (actualValue.ConnectionState == ConnectionState.Connected) { if (packet.Size == 1) { actualValue.ResetMtu(); SendRaw(NetConnectAcceptPacket.MakeNetworkChanged(actualValue), remoteEndPoint); } else if (packet.Size == 2 && packet.RawData[1] == 1) { DisconnectPeerForce(actualValue, DisconnectReason.PeerNotFound, SocketError.Success, null); } } } else { if (packet.Size <= 1) { break; } bool flag2 = false; if (AllowPeerAddressChange) { NetConnectAcceptPacket netConnectAcceptPacket = NetConnectAcceptPacket.FromData(packet); if (netConnectAcceptPacket != null && netConnectAcceptPacket.PeerNetworkChanged && netConnectAcceptPacket.PeerId < _peersArray.Length) { _peersLock.EnterUpgradeableReadLock(); NetPeer netPeer = _peersArray[netConnectAcceptPacket.PeerId]; _peersLock.ExitUpgradeableReadLock(); if (netPeer != null && netPeer.ConnectTime == netConnectAcceptPacket.ConnectionTime && netPeer.ConnectionNum == netConnectAcceptPacket.ConnectionNumber) { if (netPeer.ConnectionState == ConnectionState.Connected) { netPeer.InitiateEndPointChange(); CreateEvent(NetEvent.EType.PeerAddressChanged, netPeer, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } flag2 = true; } } } PoolRecycle(packet); if (!flag2) { NetPacket netPacket = PoolGetWithProperty(PacketProperty.PeerNotFound, 1); netPacket.RawData[1] = 1; SendRawAndRecycle(netPacket, remoteEndPoint); } } break; case PacketProperty.InvalidProtocol: if (flag && actualValue.ConnectionState == ConnectionState.Outgoing) { DisconnectPeerForce(actualValue, DisconnectReason.InvalidProtocol, SocketError.Success, null); } break; case PacketProperty.Disconnect: if (flag) { DisconnectResult disconnectResult = actualValue.ProcessDisconnect(packet); if (disconnectResult == DisconnectResult.None) { PoolRecycle(packet); break; } DisconnectPeerForce(actualValue, (disconnectResult == DisconnectResult.Disconnect) ? DisconnectReason.RemoteConnectionClose : DisconnectReason.ConnectionRejected, SocketError.Success, packet); } else { PoolRecycle(packet); } SendRawAndRecycle(PoolGetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint); break; case PacketProperty.ConnectAccept: if (flag) { NetConnectAcceptPacket netConnectAcceptPacket2 = NetConnectAcceptPacket.FromData(packet); if (netConnectAcceptPacket2 != null && actualValue.ProcessConnectAccept(netConnectAcceptPacket2)) { CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } } break; default: if (flag) { actualValue.ProcessPacket(packet); } else { SendRawAndRecycle(PoolGetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint); } break; } } internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod method, byte channelNumber, int headerSize, NetPeer fromPeer) { if (UnsyncedEvents || UnsyncedReceiveEvent || _manualMode) { NetEvent netEvent; lock (_eventLock) { netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } } netEvent.Next = null; netEvent.Type = NetEvent.EType.Receive; netEvent.DataReader.SetSource(packet, headerSize); netEvent.Peer = fromPeer; netEvent.DeliveryMethod = method; netEvent.ChannelNumber = channelNumber; ProcessEvent(netEvent); return; } lock (_eventLock) { NetEvent netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } netEvent.Next = null; netEvent.Type = NetEvent.EType.Receive; netEvent.DataReader.SetSource(packet, headerSize); netEvent.Peer = fromPeer; netEvent.DeliveryMethod = method; netEvent.ChannelNumber = channelNumber; if (_pendingEventTail == null) { _pendingEventHead = netEvent; } else { _pendingEventTail.Next = netEvent; } _pendingEventTail = netEvent; } } public void SendToAll(NetDataWriter writer, DeliveryMethod options) { SendToAll(writer.Data, 0, writer.Length, options); } public void SendToAll(byte[] data, DeliveryMethod options) { SendToAll(data, 0, data.Length, options); } public void SendToAll(byte[] data, int start, int length, DeliveryMethod options) { SendToAll(data, start, length, 0, options); } public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options) { SendToAll(writer.Data, 0, writer.Length, channelNumber, options); } public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options) { SendToAll(data, 0, data.Length, channelNumber, options); } public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { netPeer.Send(data, start, length, channelNumber, options); } } finally { _peersLock.ExitReadLock(); } } public void SendToAll(NetDataWriter writer, DeliveryMethod options, NetPeer excludePeer) { SendToAll(writer.Data, 0, writer.Length, 0, options, excludePeer); } public void SendToAll(byte[] data, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, data.Length, 0, options, excludePeer); } public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, start, length, 0, options, excludePeer); } public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { SendToAll(writer.Data, 0, writer.Length, channelNumber, options, excludePeer); } public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, data.Length, channelNumber, options, excludePeer); } public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer != excludePeer) { netPeer.Send(data, start, length, channelNumber, options); } } } finally { _peersLock.ExitReadLock(); } } public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options) { SendToAll(data, 0, options, null); } public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, options, excludePeer); } public void SendToAll(ReadOnlySpan<byte> data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer != excludePeer) { netPeer.Send(data, channelNumber, options); } } } finally { _peersLock.ExitReadLock(); } } public bool SendUnconnectedMessage(ReadOnlySpan<byte> message, IPEndPoint remoteEndPoint) { int headerSize = NetPacket.GetHeaderSize(PacketProperty.UnconnectedMessage); NetPacket netPacket = PoolGetPacket(message.Length + headerSize); netPacket.Property = PacketProperty.UnconnectedMessage; message.CopyTo(new Span<byte>(netPacket.RawData, headerSize, message.Length)); return SendRawAndRecycle(netPacket, remoteEndPoint) > 0; } public bool Start() { return Start(0); } public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port) { return Start(addressIPv4, addressIPv6, port, manualMode: false); } public bool Start(string addressIPv4, string addressIPv6, int port) { IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4); IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6); return Start(addressIPv7, addressIPv8, port); } public bool Start(int port) { return Start(IPAddress.Any, IPAddress.IPv6Any, port); } public bool StartInManualMode(IPAddress addressIPv4, IPAddress addressIPv6, int port) { return Start(addressIPv4, addressIPv6, port, manualMode: true); } public bool StartInManualMode(string addressIPv4, string addressIPv6, int port) { IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4); IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6); return StartInManualMode(addressIPv7, addressIPv8, port); } public bool StartInManualMode(int port) { return StartInManualMode(IPAddress.Any, IPAddress.IPv6Any, port); } public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint) { return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint); } public bool SendUnconnectedMessage(NetDataWriter writer, string address, int port) { IPEndPoint remoteEndPoint = NetUtils.MakeEndPoint(address, port); return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); } public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint) { return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); } public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint) { NetPacket packet = PoolGetWithData(PacketProperty.UnconnectedMessage, message, start, length); return SendRawAndRecycle(packet, remoteEndPoint) > 0; } public void TriggerUpdate() { _updateTriggerEvent.Set(); } public void PollEvents(int maxProcessedEvents = 0) { if (_manualMode) { if (_udpSocketv4 != null) { ManualReceive(_udpSocketv4, _bufferEndPointv4, maxProcessedEvents); } if (_udpSocketv6 != null && _udpSocketv6 != _udpSocketv4) { ManualReceive(_udpSocketv6, _bufferEndPointv6, maxProcessedEvents); } } else { if (UnsyncedEvents) { return; } NetEvent netEvent; lock (_eventLock) { netEvent = _pendingEventHead; _pendingEventHead = null; _pendingEventTail = null; } int num = 0; while (netEvent != null) { NetEvent next = netEvent.Next; ProcessEvent(netEvent); netEvent = next; num++; if (num == maxProcessedEvents) { break; } } } } public NetPeer Connect(string address, int port, string key) { return Connect(address, port, NetDataWriter.FromString(key)); } public NetPeer Connect(string address, int port, NetDataWriter connectionData) { IPEndPoint target; try { target = NetUtils.MakeEndPoint(address, port); } catch { CreateEvent(NetEvent.EType.Disconnect, null, null, SocketError.Success, 0, DisconnectReason.UnknownHost, null, DeliveryMethod.Unreliable, 0); return null; } return Connect(target, connectionData); } public NetPeer Connect(IPEndPoint target, string key) { return Connect(target, NetDataWriter.FromString(key)); } public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData) { if (!IsRunning) { throw new InvalidOperationException("Client is not running"); } lock (_requestsDict) { if (_requestsDict.ContainsKey(target)) { return null; } byte connectNum = 0; if (TryGetPeer(target, out var actualValue)) { ConnectionState connectionState = actualValue.ConnectionState; if (connectionState == ConnectionState.Outgoing || connectionState == ConnectionState.Connected) { return actualValue; } connectNum = (byte)((actualValue.ConnectionNum + 1) % 4); RemovePeer(actualValue, enableWriteLock: true); } actualValue = new NetPeer(this, target, GetNextPeerId(), connectNum, connectionData); AddPeer(actualValue); return actualValue; } } public void Stop() { Stop(sendDisconnectMessages: true); } public void Stop(bool sendDisconnectMessages) { if (IsRunning) { for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { netPeer.Shutdown(null, 0, 0, !sendDisconnectMessages); } CloseSocket(); _updateTriggerEvent.Set(); if (!_manualMode) { _logicThread.Join(); _logicThread = null; } ClearPeerSet(); _peerIds = new ConcurrentQueue<int>(); _lastPeerId = 0; _connectedPeersCount = 0L; _pendingEventHead = null; _pendingEventTail = null; } } [Conditional("DEBUG")] private void ClearPingSimulationList() { lock (_pingSimulationList) { _pingSimulationList.Clear(); } } public int GetPeersCount(ConnectionState peerState) { int num = 0; _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if ((netPeer.ConnectionState & peerState) != 0) { num++; } } _peersLock.ExitReadLock(); return num; } public void GetPeersNonAlloc(List<NetPeer> peers, ConnectionState peerState) { peers.Clear(); _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if ((netPeer.ConnectionState & peerState) != 0) { peers.Add(netPeer); } } _peersLock.ExitReadLock(); } public void DisconnectAll() { DisconnectAll(null, 0, 0); } public void DisconnectAll(byte[] data, int start, int count) { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { DisconnectPeer(netPeer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null); } _peersLock.ExitReadLock(); } public void DisconnectPeerForce(NetPeer peer) { DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, null); } public void DisconnectPeer(NetPeer peer) { DisconnectPeer(peer, null, 0, 0); } public void DisconnectPeer(NetPeer peer, byte[] data) { DisconnectPeer(peer, data, 0, data.Length); } public void DisconnectPeer(NetPeer peer, NetDataWriter writer) { DisconnectPeer(peer, writer.Data, 0, writer.Length); } public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count) { DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null); } public void CreateNtpRequest(IPEndPoint endPoint) { _ntpRequests.TryAdd(endPoint, new NtpRequest(endPoint)); } public void CreateNtpRequest(string ntpServerAddress, int port) { IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, port); _ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint)); } public void CreateNtpRequest(string ntpServerAddress) { IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, 123); _ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint)); } public NetPeerEnumerator GetEnumerator() { return new NetPeerEnumerator(_headPeer); } IEnumerator<NetPeer> IEnumerable<NetPeer>.GetEnumerator() { return new NetPeerEnumerator(_headPeer); } IEnumerator IEnumerable.GetEnumerator() { return new NetPeerEnumerator(_headPeer); } private static int HashSetGetPrime(int min) { int[] primes = Primes; foreach (int num in primes) { if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j) && (j - 1) % 101 != 0) { return j; } } return min; static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num2 = (int)Math.Sqrt(candidate); for (int k = 3; k <= num2; k += 2) { if (candidate % k == 0) { return false; } } return true; } return candidate == 2; } } private void ClearPeerSet() { _peersLock.EnterWriteLock(); _headPeer = null; if (_lastIndex > 0) { Array.Clear(_slots, 0, _lastIndex); Array.Clear(_buckets, 0, _buckets.Length); _lastIndex = 0; _count = 0; _freeList = -1; } _peersArray = new NetPeer[32]; _peersLock.ExitWriteLock(); } private bool ContainsPeer(NetPeer item) { if (item == null) { NetDebug.WriteError($"Contains peer null: {item}"); return false; } if (_buckets != null) { int num = item.GetHashCode() & 0x7FFFFFFF; for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(item)) { return true; } } } return false; } public NetPeer GetPeerById(int id) { if (id < 0 || id >= _peersArray.Length) { return null; } return _peersArray[id]; } public bool TryGetPeerById(int id, out NetPeer peer) { peer = GetPeerById(id); return peer != null; } private void AddPeer(NetPeer peer) { if (peer == null) { NetDebug.WriteError($"Add peer null: {peer}"); return; } _peersLock.EnterWriteLock(); if (_headPeer != null) { peer.NextPeer = _headPeer; _headPeer.PrevPeer = peer; } _headPeer = peer; AddPeerToSet(peer); if (peer.Id >= _peersArray.Length) { int num = _peersArray.Length * 2; while (peer.Id >= num) { num *= 2; } Array.Resize(ref _peersArray, num); } _peersArray[peer.Id] = peer; _peersLock.ExitWriteLock(); } private void RemovePeer(NetPeer peer, bool enableWriteLock) { if (enableWriteLock) { _peersLock.EnterWriteLock(); } if (!RemovePeerFromSet(peer)) { if (enableWriteLock) { _peersLock.ExitWriteLock(); } return; } if (peer == _headPeer) { _headPeer = peer.NextPeer; } if (peer.PrevPeer != null) { peer.PrevPeer.NextPeer = peer.NextPeer; } if (peer.NextPeer != null) { peer.NextPeer.PrevPeer = peer.PrevPeer; } peer.PrevPeer = null; _peersArray[peer.Id] = null; _peerIds.Enqueue(peer.Id); if (enableWriteLock) { _peersLock.ExitWriteLock(); } } private bool RemovePeerFromSet(NetPeer peer) { if (_buckets == null || peer == null) { return false; } int num = peer.GetHashCode() & 0x7FFFFFFF; int num2 = num % _buckets.Length; int num3 = -1; for (int num4 = _buckets[num2] - 1; num4 >= 0; num4 = _slots[num4].Next) { if (_slots[num4].HashCode == num && _slots[num4].Value.Equals(peer)) { if (num3 < 0) { _buckets[num2] = _slots[num4].Next + 1; } else { _slots[num3].Next = _slots[num4].Next; } _slots[num4].HashCode = -1; _slots[num4].Value = null; _slots[num4].Next = _freeList; _count--; if (_count == 0) { _lastIndex = 0; _freeList = -1; } else { _freeList = num4; } return true; } num3 = num4; } return false; } private bool TryGetPeer(IPEndPoint endPoint, out NetPeer actualValue) { if (_buckets != null) { int num = endPoint.GetHashCode() & 0x7FFFFFFF; _peersLock.EnterReadLock(); for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(endPoint)) { actualValue = _slots[num2].Value; _peersLock.ExitReadLock(); return true; } } _peersLock.ExitReadLock(); } actualValue = null; return false; } private bool TryGetPeer(SocketAddress saddr, out NetPeer actualValue) { if (_buckets != null) { int num = saddr.GetHashCode() & 0x7FFFFFFF; _peersLock.EnterReadLock(); for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Serialize().Equals(saddr)) { actualValue = _slots[num2].Value; _peersLock.ExitReadLock(); return true; } } _peersLock.ExitReadLock(); } actualValue = null; return false; } private bool AddPeerToSet(NetPeer value) { if (_buckets == null) { int num = HashSetGetPrime(0); _buckets = new int[num]; _slots = new Slot[num]; } int num2 = value.GetHashCode() & 0x7FFFFFFF; int num3 = num2 % _buckets.Length; for (int num4 = _buckets[num2 % _buckets.Length] - 1; num4 >= 0; num4 = _slots[num4].Next) { if (_slots[num4].HashCode == num2 && _slots[num4].Value.Equals(value)) { return false; } } int num5; if (_freeList >= 0) { num5 = _freeList; _freeList = _slots[num5].Next; } else { if (_lastIndex == _slots.Length) { int num6 = 2 * _count; num6 = (((uint)num6 > 2147483587u && 2147483587 > _count) ? 2147483587 : HashSetGetPrime(num6)); Slot[] array = new Slot[num6]; Array.Copy(_slots, 0, array, 0, _lastIndex); _buckets = new int[num6]; for (int i = 0; i < _lastIndex; i++) { int num7 = array[i].HashCode % num6; array[i].Next = _buckets[num7] - 1; _buckets[num7] = i + 1; } _slots = array; num3 = num2 % _buckets.Length; } num5 = _lastIndex; _lastIndex++; } _slots[num5].HashCode = num2; _slots[num5].Value = value; _slots[num5].Next = _buckets[num3] - 1; _buckets[num3] = num5 + 1; _count++; return true; } private NetPacket PoolGetWithData(PacketProperty property, byte[] data, int start, int length) { int headerSize = NetPacket.GetHeaderSize(property); NetPacket netPacket = PoolGetPacket(length + headerSize); netPacket.Property = property; Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length); return netPacket; } private NetPacket PoolGetWithProperty(PacketProperty property, int size) { NetPacket netPacket = PoolGetPacket(size + NetPacket.GetHeaderSize(property)); netPacket.Property = property; return netPacket; } private NetPacket PoolGetWithProperty(PacketProperty property) { NetPacket netPacket = PoolGetPacket(NetPacket.GetHeaderSize(property)); netPacket.Property = property; return netPacket; } internal NetPacket PoolGetPacket(int size) { if (size > NetConstants.MaxPacketSize) { return new NetPacket(size); } NetPacket poolHead; lock (_poolLock) { poolHead = _poolHead; if (poolHead == null) { return new NetPacket(size); } _poolHead = _poolHead.Next; _poolCount--; } poolHead.Size = size; if (poolHead.RawData.Length < size) { poolHead.RawData = new byte[size]; } return poolHead; } internal void PoolRecycle(NetPacket packet) { if (packet.RawData.Length > NetConstants.MaxPacketSize || _poolCount >= PacketPoolSize) { return; } packet.RawData[0] = 0; lock (_poolLock) { packet.Next = _poolHead; _poolHead = packet; _poolCount++; } } static NetManager() { Primes = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; MulticastAddressV6 = IPAddress.Parse("ff02::1"); IPv6Support = Socket.OSSupportsIPv6; } private bool ProcessError(SocketException ex) { switch (ex.SocketErrorCode) { case SocketError.NotConnected: NotConnected = true; return true; case SocketError.OperationAborted: case SocketError.Interrupted: case SocketError.NotSocket: return true; default: NetDebug.WriteError($"[R]Error code: {ex.SocketErrorCode} - {ex}"); CreateEvent(NetEvent.EType.Error, null, null, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); break; case SocketError.WouldBlock: case SocketError.MessageSize: case SocketError.NetworkReset: case SocketError.ConnectionReset: case SocketError.TimedOut: break; } return false; } private void ManualReceive(Socket socket, EndPoint bufferEndPoint, int maxReceive) { try { int num = 0; while (socket.Available > 0) { ReceiveFrom(socket, ref bufferEndPoint); num++; if (num == maxReceive) { break; } } } catch (SocketException ex) { ProcessError(ex); } catch (ObjectDisposedException) { } catch (Exception ex3) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex3); } } private void NativeReceiveLogic() { IntPtr handle = _udpSocketv4.Handle; IntPtr s2 = _udpSocketv6?.Handle ?? IntPtr.Zero; byte[] address2 = new byte[16]; byte[] address3 = new byte[28]; IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Any, 0); List<Socket> list = new List<Socket>(2); Socket udpSocketv = _udpSocketv4; Socket udpSocketv2 = _udpSocketv6; NetPacket packet = PoolGetPacket(NetConstants.MaxPacketSize); while (IsRunning) { try { if (udpSocketv2 == null) { if (!NativeReceiveFrom(handle, address2)) { break; } continue; } bool flag = false; if (udpSocketv.Available != 0 || list.Contains(udpSocketv)) { if (!NativeReceiveFrom(handle, address2)) { break; } flag = true; } if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2)) { if (!NativeReceiveFrom(s2, address3)) { break; } flag = true; } list.Clear(); if (!flag) { list.Add(udpSocketv); list.Add(udpSocketv2); Socket.Select(list, null, null, 500000); } } catch (SocketException ex) { if (ProcessError(ex)) { break; } } catch (ObjectDisposedException) { break; } catch (ThreadAbortException) { break; } catch (Exception ex4) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4); } } bool NativeReceiveFrom(IntPtr s, byte[] address) { int socketAddressSize = address.Length; packet.Size = NativeSocket.RecvFrom(s, packet.RawData, NetConstants.MaxPacketSize, address, ref socketAddressSize); if (packet.Size == 0) { return true; } if (packet.Size == -1) { return !ProcessError(new SocketException((int)NativeSocket.GetSocketError())); } short num = (short)((address[1] << 8) | address[0]); tempEndPoint.Port = (ushort)((address[2] << 8) | address[3]); if ((NativeSocket.UnixMode && num == 10) || (!NativeSocket.UnixMode && num == 23)) { uint num2 = (uint)((address[27] << 24) + (address[26] << 16) + (address[25] << 8) + address[24]); tempEndPoint.Address = new IPAddress(new ReadOnlySpan<byte>(address, 8, 16), num2); } else { long newAddress = (uint)((address[4] & 0xFF) | ((address[5] << 8) & 0xFF00) | ((address[6] << 16) & 0xFF0000) | (address[7] << 24)); tempEndPoint.Address = new IPAddress(newAddress); } if (TryGetPeer(tempEndPoint, out var actualValue)) { OnMessageReceived(packet, actualValue); } else { OnMessageReceived(packet, tempEndPoint); tempEndPoint = new IPEndPoint(IPAddress.Any, 0); } packet = PoolGetPacket(NetConstants.MaxPacketSize); return true; } } private void ReceiveFrom(Socket s, ref EndPoint bufferEndPoint) { NetPacket netPacket = PoolGetPacket(NetConstants.MaxPacketSize); netPacket.Size = s.ReceiveFrom(netPacket.RawData, 0, NetConstants.MaxPacketSize, SocketFlags.None, ref bufferEndPoint); OnMessageReceived(netPacket, (IPEndPoint)bufferEndPoint); } private void ReceiveLogic() { EndPoint bufferEndPoint = new IPEndPoint(IPAddress.Any, 0); EndPoint bufferEndPoint2 = new IPEndPoint(IPAddress.IPv6Any, 0); List<Socket> list = new List<Socket>(2); Socket udpSocketv = _udpSocketv4; Socket udpSocketv2 = _udpSocketv6; while (IsRunning) { try { if (udpSocketv2 == null) { if (udpSocketv.Available != 0 || udpSocketv.Poll(500000, SelectMode.SelectRead)) { ReceiveFrom(udpSocketv, ref bufferEndPoint); } continue; } bool flag = false; if (udpSocketv.Available != 0 || list.Contains(udpSocketv)) { ReceiveFrom(udpSocketv, ref bufferEndPoint); flag = true; } if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2)) { ReceiveFrom(udpSocketv2, ref bufferEndPoint2); flag = true; } list.Clear(); if (!flag) { list.Add(udpSocketv); list.Add(udpSocketv2); Socket.Select(list, null, null, 500000); } } catch (SocketException ex) { if (ProcessError(ex)) { break; } } catch (ObjectDisposedException) { break; } catch (ThreadAbortException) { break; } catch (Exception ex4) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4); } } } public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool manualMode) { if (IsRunning && !NotConnected) { return false; } NotConnected = false; _manualMode = manualMode; UseNativeSockets = UseNativeSockets && NativeSocket.IsSupported; _udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); if (!BindSocket(_udpSocketv4, new IPEndPoint(addressIPv4, port))) { return false; } LocalPort = ((IPEndPoint)_udpSocketv4.LocalEndPoint).Port; IsRunning = true; if (_manualMode) { _bufferEndPointv4 = new IPEndPoint(IPAddress.Any, 0); } if (IPv6Support && IPv6Enabled) { _udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort))) { if (_manualMode) { _bufferEndPointv6 = new IPEndPoint(IPAddress.IPv6Any, 0); } } else { _udpSocketv6 = null; } } if (!manualMode) { ThreadStart start = ReceiveLogic; if (UseNativeSockets) { start = NativeReceiveLogic; } _receiveThread = new Thread(start) { Name = $"ReceiveThread({LocalPort})", IsBackground = true }; _receiveThread.Start(); if (_logicThread == null) { _logicThread = new Thread(UpdateLogic) { Name = "LogicThread", IsBackground = true }; _logicThread.Start(); } } return true; } private bool BindSocket(Socket socket, IPEndPoint ep) { socket.ReceiveTimeout = 500; socket.SendTimeout = 500; socket.ReceiveBufferSize = 1048576; socket.SendBufferSize = 1048576; socket.Blocking = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { socket.IOControl(-1744830452, new byte[1], null); } catch { } } try { socket.ExclusiveAddressUse = !ReuseAddress; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, ReuseAddress); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, DontRoute); } catch { } if (ep.AddressFamily == AddressFamily.InterNetwork) { Ttl = 255; try { socket.EnableBroadcast = true; } catch (SocketException ex) { NetDebug.WriteError($"[B]Broadcast error: {ex.SocketErrorCode}"); } if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { socket.DontFragment = true; } catch (SocketException ex2) { NetDebug.WriteError($"[B]DontFragment error: {ex2.SocketErrorCode}"); } } } try { socket.Bind(ep); if (ep.AddressFamily == AddressFamily.InterNetworkV6) { try { socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(MulticastAddressV6)); } catch (Exception) { } } } catch (SocketException ex4) { switch (ex4.SocketErrorCode) { case SocketError.AddressAlreadyInUse: if (socket.AddressFamily == AddressFamily.InterNetworkV6) { try { socket.DualMode = false; socket.Bind(ep); } catch (SocketException ex5) { NetDebug.WriteError($"[B]Bind exception: {ex5}, errorCode: {ex5.SocketErrorCode}"); return false; } return true; } break; case SocketError.AddressFamilyNotSupported: return true; } NetDebug.WriteError($"[B]Bind exception: {ex4}, errorCode: {ex4.SocketErrorCode}"); return false; } return true; } internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndPoint) { int result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); PoolRecycle(packet); return result; } internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint) { return SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); } internal unsafe int SendRaw(byte[] message, int start, int length, IPEndPoint remoteEndPoint) { if (!IsRunning) { return 0; } NetPacket netPacket = null; if (_extraPacketLayer != null) { netPacket = PoolGetPacket(length + _extraPacketLayer.ExtraPacketSizeForLayer); Buffer.BlockCopy(message, start, netPacket.RawData, 0, length); start = 0; _extraPacketLayer.ProcessOutBoundPacket(ref remoteEndPoint, ref netPacket.RawData, ref start, ref length); message = netPacket.RawData; } Socket socket = _udpSocketv4; if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support) { socket = _udpSocketv6; if (socket == null) { return 0; } } int num; try { if (UseNativeSockets && remoteEndPoint is NetPeer netPeer) { fixed (byte* pinnedBuffer = &message[start]) { num = NativeSocket.SendTo(socket.Handle, pinnedBuffer, length, netPeer.NativeAddress, netPeer.NativeAddress.Length); } if (num == -1) { throw NativeSocket.GetSocketException(); } } else { num = socket.SendTo(message, start, length, SocketFlags.None, remoteEndPoint); } } catch (SocketException ex) { switch (ex.SocketErrorCode) { case SocketError.Interrupted: case SocketError.NoBufferSpaceAvailable: return 0; case SocketError.MessageSize: return 0; case SocketError.NetworkUnreachable: case SocketError.HostUnreachable: if (DisconnectOnUnreachable && remoteEndPoint is NetPeer peer) { DisconnectPeerForce(peer, (ex.SocketErrorCode == SocketError.HostUnreachable) ? DisconnectReason.HostUnreachable : DisconnectReason.NetworkUnreachable, ex.SocketErrorCode, null); } CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); return -1; case SocketError.Shutdown: CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); return -1; default: NetDebug.WriteError($"[S] {ex}"); return -1; } } catch (Exception value) { NetDebug.WriteError($"[S] {value}"); return 0; } finally { if (netPacket != null) { PoolRecycle(netPacket); } } if (num <= 0) { return 0; } if (EnableStatistics) { Statistics.IncrementPacketsSent(); Statistics.AddBytesSent(length); } return num; } public bool SendBroadcast(NetDataWriter writer, int port) { return SendBroadcast(writer.Data, 0, writer.Length, port); } public bool SendBroadcast(byte[] data, int port) { return SendBroadcast(data, 0, data.Length, port); } public bool SendBroadcast(byte[] data, int start, int length, int port) { if (!IsRunning) { return false; } NetPacket netPacket; if (_extraPacketLayer != null) { int headerSize = NetPacket.GetHeaderSize(PacketProperty.Broadcast); netPacket = PoolGetPacket(headerSize + length + _extraPacketLayer.ExtraPacketSizeForLayer); netPacket.Property = PacketProperty.Broadcast; Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length); int offset = 0; int length2 = length + headerSize; IPEndPoint endPoint = null; _extraPacketLayer.ProcessOutBoundPacket(ref endPoint, ref netPacket.RawData, ref offset, ref length2); } else { netPacket = PoolGetWithData(PacketProperty.Broadcast, data, start, length); } bool flag = false; bool flag2 = false; try { flag = _udpSocketv4.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port)) > 0; if (_udpSocketv6 != null) { flag2 = _udpSocketv6.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port)) > 0; } } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostUnreachable) { return flag; } NetDebug.WriteError($"[S][MCAST] {ex}"); return flag; } catch (Exception value) { NetDebug.WriteError($"[S][MCAST] {value}"); return flag; } finally { PoolRecycle(netPacket); } return flag || flag2; } private void CloseSocket() { IsRunning = false; _udpSocketv4?.Close(); _udpSocketv6?.Close(); _udpSocketv4 = null; _udpSocketv6 = null; if (_receiveThread != null && _receiveThread != Thread.CurrentThread) { _receiveThread.Join(); } _receiveThread = null; } } internal enum PacketProperty : byte { Unreliable, Channeled, Ack, Ping, Pong, ConnectRequest, ConnectAccept, Disconnect, UnconnectedMessage, MtuCheck, MtuOk, Broadcast, Merged, ShutdownOk, PeerNotFound, InvalidProtocol, NatMessage, Empty } internal sealed class NetPacket { private static readonly int PropertiesCount; private static readonly int[] HeaderSizes; public byte[] RawData; public int Size; public object UserData; public NetPacket Next; public PacketProperty Property { get { return (PacketProperty)(RawData[0] & 0x1Fu); } set { RawData[0] = (byte)((RawData[0] & 0xE0u) | (uint)value); } } public byte ConnectionNumber { get { return (byte)((RawData[0] & 0x60) >> 5); } set { RawData[0] = (byte)((RawData[0] & 0x9Fu) | (uint)(value << 5)); } } public ushort Sequence { get { return BitConverter.ToUInt16(RawData, 1); } set { FastBitConverter.GetBytes(RawData, 1, value); } } public bool IsFragmented => (RawData[0] & 0x80) != 0; public byte ChannelId { get { return RawData[3]; } set { RawData[3] = value; } } public ushort FragmentId { get { return BitConverter.ToUInt16(RawData, 4); } set { FastBitConverter.GetBytes(RawData, 4, value); } } public ushort FragmentPart { get { return BitConverter.ToUInt16(RawData, 6); } set { FastBitConverter.GetBytes(RawData, 6, value); } } public ushort FragmentsTotal { get { return BitConverter.ToUInt16(RawData, 8); } set { FastBitConverter.GetBytes(RawData, 8, value); } } static NetPacket() { PropertiesCount = Enum.GetValues(typeof(PacketProperty)).Length; HeaderSizes = NetUtils.AllocatePinnedUninitializedArray<int>(PropertiesCount); for (int i = 0; i < HeaderSizes.Length; i++) { switch ((PacketProperty)(byte)i) { case PacketProperty.Channeled: case PacketProperty.Ack: HeaderSizes[i] = 4; break; case PacketProperty.Ping: HeaderSizes[i] = 3; break; case PacketProperty.ConnectRequest: HeaderSizes[i] = 18; break; case PacketProperty.ConnectAccept: HeaderSizes[i] = 15; break; case PacketProperty.Disconnect: HeaderSizes[i] = 9; break; case PacketProperty.Pong: HeaderSizes[i] = 11; break; default: HeaderSizes[i] = 1; break; } } } public void MarkFragmented() { RawData[0] |= 128; } public NetPacket(int size) { RawData = new byte[size]; Size = size; } public NetPacket(PacketProperty property, int size) { size += GetHeaderSize(property); RawData = new byte[size]; Property = property; Size = size; } public static int GetHeaderSize(PacketProperty property) { return HeaderSizes[(uint)property]; } public int GetHeaderSize() { return HeaderSizes[RawData[0] & 0x1F]; } public bool Verify() { byte b = (byte)(RawData[0] & 0x1Fu); if (b >= PropertiesCount) { return false; } int num = HeaderSizes[b]; bool flag = (RawData[0] & 0x80) != 0; if (Size >= num) { if (flag) { return Size >= num + 6; } return true; } return false; } public static implicit operator Span<byte>(NetPacket p) { return new Span<byte>(p.RawData, 0, p.Size); } } [Flags] public enum ConnectionState : byte { Outgoing = 2, Connected = 4, ShutdownRequested = 8, Disconnected = 0x10, EndPointChange = 0x20, Any = 0x2E } internal enum ConnectRequestResult { None, P2PLose, Reconnection, NewConnection } internal enum DisconnectResult { None, Reject, Disconnect } internal enum ShutdownResult { None, Success, WasConnected } public class NetPeer : IPEndPoint { private class IncomingFragments { public NetPacket[] Fragments; public int ReceivedCount; public int TotalSize; public byte ChannelId; } private int _rtt; private int _avgRtt; private int _rttCount; private double _resendDelay = 27.0; private float _pingSendTimer; private float _rttResetTimer; private readonly Stopwatch _pingTimer = new Stopwatch(); private volatile float _timeSinceLastPacket; private long _remoteDelta; private readonly object _shutdownLock = new object(); internal volatile NetPeer NextPeer; internal NetPeer PrevPeer; private NetPacket[] _unreliableSecondQueue; private NetPacket[] _unreliableChannel; private int _unreliablePendingCount; private readonly object _unreliableChannelLock = new object(); private readonly ConcurrentQueue<BaseChannel> _channelSendQueue; private readonly BaseChannel[] _channels; private int _mtu; private int _mtuIdx; private bool _finishMtu; private float _mtuCheckTimer; private int _mtuCheckAttempts; private const int MtuCheckDelay = 1000; private const int MaxMtuCheckAttempts = 4; private readonly object _mtuMutex = new object(); private int _fragmentId; private readonly Dictionary<ushort, IncomingFragments> _holdedFragments; private readonly Dictionary<ushort, ushort> _deliveredFragments; private readonly NetPacket _mergeData; private int _mergePos; private int _mergeCount; private int _connectAttempts; private float _connectTimer; private long _connectTime; private byte _connectNum; private ConnectionState _connectionState; private NetPacket _shutdownPacket; private const int ShutdownDelay = 300; private float _shutdownTimer; private readonly NetPacket _pingPacket; private readonly NetPacket _pongPacket; private readonly NetPacket _connectRequestPacket; private readonly NetPacket _connectAcceptPacket; public readonly NetManager NetManager; public readonly int Id; public object Tag; public readonly NetStatistics Statistics; private SocketAddress _cachedSocketAddr; private int _cachedHashCode; internal byte[] NativeAddress; internal byte ConnectionNum { get { return _connectNum; } private set { _connectNum = value; _mergeData.ConnectionNumber = value; _pingPacket.ConnectionNumber = value; _pongPacket.ConnectionNumber = value; } } public ConnectionState ConnectionState => _connectionState; internal long ConnectTime => _connectTime; public int RemoteId { get; private set; } public int Ping => _avgRtt / 2; public int RoundTripTime => _avgRtt; public int Mtu => _mtu; public long RemoteTimeDelta => _remoteDelta; public DateTime RemoteUtcTime => new DateTime(DateTime.UtcNow.Ticks + _remoteDelta); public float TimeSinceLastPacket => _timeSinceLastPacket; internal double ResendDelay => _resendDelay; public override SocketAddress Serialize() { return _cachedSocketAddr; } public override int GetHashCode() { return _cachedHashCode; } internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id) : base(remoteEndPoint.Address, remoteEndPoint.Port) { Id = id; Statistics = new NetStatistics(); NetManager = netManager; _cachedSocketAddr = base.Serialize(); if (NetManager.UseNativeSockets) { NativeAddress = new byte[_cachedSocketAddr.Size]; for (int i = 0; i < _cachedSocketAddr.Size; i++) { NativeAddress[i] = _cachedSocketAddr[i]; } } _cachedHashCode = base.GetHashCode(); ResetMtu(); _connectionState = ConnectionState.Connected; _mergeData = new NetPacket(PacketProperty.Merged, NetConstants.MaxPacketSize); _pongPacket = new NetPacket(PacketProperty.Pong, 0); _pingPacket = new NetPacket(PacketProperty.Ping, 0) { Sequence = 1 }; _unreliableSecondQueue = new NetPacket[8]; _unreliableChannel = new NetPacket[8]; _holdedFragments = new Dictionary<ushort, IncomingFragments>(); _deliveredFragments = new Dictionary<ushort, ushort>(); _channels = new BaseChannel[netManager.ChannelsCount * 4]; _channelSendQueue = new ConcurrentQueue<BaseChannel>(); } internal void InitiateEndPointChange() { ResetMtu(); _connectionState = ConnectionState.EndPointChange; } internal void FinishEndPointChange(IPEndPoint newEndPoint) { if (_connectionState != ConnectionState.EndPointChange) { return; } _connectionState = ConnectionState.Connected; base.Address = newEndPoint.Address; base.Port = newEndPoint.Port; if (NetManager.UseNativeSockets) { NativeAddress = new byte[_cachedSocketAddr.Size]; for (int i = 0; i < _cachedSocketAddr.Size; i++) { NativeAddress[i] = _cachedSocketAddr[i]; } } _cachedSocketAddr = base.Serialize(); _cachedHashCode = base.GetHashCode(); } internal void ResetMtu() { _finishMtu = !NetManager.MtuDiscovery; if (NetManager.MtuOverride > 0) { OverrideMtu(NetManager.MtuOverride); } else { SetMtu(0); } } private void SetMtu(int mtuIdx) { _mtuIdx = mtuIdx; _mtu = NetConstants.PossibleMtu[mtuIdx] - NetManager.ExtraPacketSizeForLayer; } private void OverrideMtu(int mtuValue) { _mtu = mtuValue; _finishMtu = true; } public int GetPacketsCountInReliableQueue(byte channelNumber, bool ordered) { int num = channelNumber * 4 + (ordered ? 2 : 0); BaseChannel baseChannel = _channels[num]; if (baseChannel == null) { return 0; } return ((ReliableChannel)baseChannel).PacketsInQueue; } public PooledPacket CreatePacketFromPool(DeliveryMethod deliveryMethod, byte channelNumber) { int mtu = _mtu; NetPacket netPacket = NetManager.PoolGetPacket(mtu); if (deliveryMethod == DeliveryMethod.Unreliable) { netPacket.Property = PacketProperty.Unreliable; return new PooledPacket(netPacket, mtu, 0); } netPacket.Property = PacketProperty.Channeled; return new PooledPacket(netPacket, mtu, (byte)((uint)(channelNumber * 4) + (ui