Decompiled source of NestCoop v0.9.10

Mods/NestCoop.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using HarmonyLib;
using Il2Cpp;
using Il2CppHeathen.SteamworksIntegration;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppKamgam.UGUIComponentsForSettings;
using Il2CppNewtonsoft.Json;
using Il2CppSleepyNodes;
using Il2CppSteamTools;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Il2CppTMPro;
using LiteNetLib;
using LiteNetLib.Layers;
using LiteNetLib.Utils;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using NestCoop;
using NestCoop.Menu;
using NestCoop.Transport;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Mod), "NestCoop", "0.9.10", "TDWolff", null)]
[assembly: MelonGame("Iron Nest", "Iron Nest Heavy Turret Simulator")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("NestCoop")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e82546503fa532566be87983f21574fa30828d78")]
[assembly: AssemblyProduct("NestCoop")]
[assembly: AssemblyTitle("NestCoop")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 NestCoop
{
	internal static class CoopPause
	{
		public static int skippedRequests;

		public static int skippedGlobal;

		public static readonly HashSet<IntPtr> skippedTimePause = new HashSet<IntPtr>();

		public static bool Block => Net.Active;

		public static void Reset()
		{
			skippedRequests = (skippedGlobal = 0);
			skippedTimePause.Clear();
		}
	}
	[HarmonyPatch(typeof(PauseManager), "RequestPause")]
	internal static class Pause_Request
	{
		private static bool Prefix()
		{
			if (!CoopPause.Block)
			{
				return true;
			}
			CoopPause.skippedRequests++;
			PatchLog.Hit("PauseManager.RequestPause (skipped: co-op doesn't pause)");
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseManager), "ReleasePause")]
	internal static class Pause_Release
	{
		private static bool Prefix()
		{
			if (CoopPause.skippedRequests <= 0)
			{
				return true;
			}
			CoopPause.skippedRequests--;
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseManager), "RequestGlobalPause")]
	internal static class Pause_RequestGlobal
	{
		private static bool Prefix()
		{
			if (!CoopPause.Block)
			{
				return true;
			}
			CoopPause.skippedGlobal++;
			PatchLog.Hit("PauseManager.RequestGlobalPause (skipped: co-op doesn't pause)");
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseManager), "ReleaseGlobalPause")]
	internal static class Pause_ReleaseGlobal
	{
		private static bool Prefix()
		{
			if (CoopPause.skippedGlobal <= 0)
			{
				return true;
			}
			CoopPause.skippedGlobal--;
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseManager), "TogglePause")]
	internal static class Pause_Toggle
	{
		private static bool Prefix()
		{
			if (!CoopPause.Block)
			{
				return true;
			}
			PatchLog.Hit("PauseManager.TogglePause (skipped: co-op doesn't pause)");
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseManager), "OnApplicationFocus")]
	internal static class Pause_Focus
	{
		private static bool Prefix(bool hasFocus)
		{
			if (!CoopPause.Block)
			{
				return true;
			}
			PatchLog.Hit("PauseManager.OnApplicationFocus (skipped: co-op doesn't pause on focus loss)", $"hasFocus={hasFocus}");
			return false;
		}
	}
	[HarmonyPatch(typeof(TimePause), "OnEnable")]
	internal static class TimePause_Enable
	{
		private static bool Prefix(TimePause __instance)
		{
			if (!CoopPause.Block)
			{
				return true;
			}
			CoopPause.skippedTimePause.Add(((Il2CppObjectBase)__instance).Pointer);
			PatchLog.Hit("TimePause.OnEnable (skipped: co-op doesn't pause)", ((Object)((Component)__instance).gameObject).name);
			return false;
		}
	}
	[HarmonyPatch(typeof(TimePause), "OnDisable")]
	internal static class TimePause_Disable
	{
		private static bool Prefix(TimePause __instance)
		{
			return !CoopPause.skippedTimePause.Remove(((Il2CppObjectBase)__instance).Pointer);
		}
	}
	[HarmonyPatch(typeof(MissionManager), "MarkMissionComplete")]
	internal static class MM_MarkComplete
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("MarkMissionComplete (guest: waiting for the host's verdict)");
			return false;
		}

		private static void Postfix(bool forceSetState)
		{
			if (!Net.ApplyingRemote)
			{
				MissionSync.OnHostVerdict(MissionSync.EventKind.Complete, forceSetState);
			}
		}
	}
	[HarmonyPatch(typeof(MissionManager), "MarkMissionFailed")]
	internal static class MM_MarkFailed
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("MarkMissionFailed (guest: waiting for the host's verdict)");
			return false;
		}

		private static void Postfix(bool forceSetState)
		{
			if (!Net.ApplyingRemote)
			{
				MissionSync.OnHostVerdict(MissionSync.EventKind.Failed, forceSetState);
			}
		}
	}
	internal static class AvatarModel
	{
		private sealed class Group
		{
			public string Name;

			public Color Color;

			public float Metallic;

			public float Smoothness;

			public Mesh Mesh;

			public Material Shared;
		}

		private const string Resource = "NestCoop.avatar-head.mesh.txt";

		public const string TintGroup = "Band";

		private static List<Group> groups;

		private static bool tried;

		public static bool Build(Transform parent, Color tint, Func<Color, float, float, Material> makeMaterial)
		{
			//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_0041: 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)
			if (!Load(makeMaterial))
			{
				return false;
			}
			foreach (Group group in groups)
			{
				GameObject val = new GameObject("Head " + group.Name);
				val.transform.SetParent(parent, false);
				val.AddComponent<MeshFilter>().sharedMesh = group.Mesh;
				((Renderer)val.AddComponent<MeshRenderer>()).sharedMaterial = group.Shared ?? makeMaterial(tint, group.Metallic, group.Smoothness);
			}
			return true;
		}

		private static bool Load(Func<Color, float, float, Material> makeMaterial)
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Expected O, but got Unknown
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			if (groups != null)
			{
				return true;
			}
			if (tried)
			{
				return false;
			}
			tried = true;
			try
			{
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NestCoop.avatar-head.mesh.txt");
				if (stream == null)
				{
					Mod.Log.Warning("AvatarModel: resource NestCoop.avatar-head.mesh.txt missing; using capsules");
					return false;
				}
				using StreamReader streamReader = new StreamReader(stream);
				List<(Group, List<Vector3>)> list = new List<(Group, List<Vector3>)>();
				List<Vector3> list2 = null;
				string text;
				while ((text = streamReader.ReadLine()) != null)
				{
					if (text.Length == 0 || text[0] == '#')
					{
						continue;
					}
					string[] array = text.Split(' ');
					if (array[0] == "g")
					{
						Group item = new Group
						{
							Name = array[1],
							Color = new Color(F(array[2]), F(array[3]), F(array[4])),
							Metallic = F(array[5]),
							Smoothness = F(array[6])
						};
						list2 = new List<Vector3>();
						list.Add((item, list2));
					}
					else if (array[0] == "t" && list2 != null && array.Length == 10)
					{
						for (int i = 0; i < 3; i++)
						{
							list2.Add(new Vector3(F(array[1 + i * 3]), F(array[2 + i * 3]), F(array[3 + i * 3])));
						}
					}
				}
				List<Group> list3 = new List<Group>();
				int num = 0;
				foreach (var (obj, list4) in list)
				{
					if (list4.Count != 0)
					{
						int[] array2 = new int[list4.Count];
						for (int j = 0; j < array2.Length; j++)
						{
							array2[j] = j;
						}
						Mesh val = new Mesh
						{
							name = "NestCoop head " + obj.Name
						};
						val.vertices = Il2CppStructArray<Vector3>.op_Implicit(list4.ToArray());
						val.triangles = Il2CppStructArray<int>.op_Implicit(array2);
						val.RecalculateNormals();
						val.RecalculateBounds();
						((Object)val).hideFlags = (HideFlags)32;
						obj.Mesh = val;
						if (obj.Name != "Band")
						{
							obj.Shared = makeMaterial(obj.Color, obj.Metallic, obj.Smoothness);
							((Object)obj.Shared).hideFlags = (HideFlags)32;
						}
						list3.Add(obj);
						num += list4.Count / 3;
					}
				}
				groups = list3;
				Mod.Log.Msg($"AvatarModel: head loaded ({list3.Count} parts, {num} triangles)");
				return true;
			}
			catch (Exception value)
			{
				Mod.Log.Error($"AvatarModel: couldn't load the head model, using capsules: {value}");
				return false;
			}
		}

		private static float F(string s)
		{
			return float.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture);
		}
	}
	internal static class Avatars
	{
		private sealed class Avatar
		{
			public GameObject Root;

			public GameObject Body;

			public GameObject Head;

			public GameObject Shadow;

			public TextMeshPro Label;

			public Color Color;

			public Vector3 TargetFeet;

			public Quaternion TargetHead = Quaternion.identity;

			public bool Crouched;

			public float LastSeen;
		}

		private const int HostPlayerId = 0;

		private static readonly Dictionary<int, Avatar> avatars = new Dictionary<int, Avatar>();

		private static float nextSend;

		private static bool loggedFirstPose;

		private const float HeadScale = 1.25f;

		private static Shader litShader;

		private static bool shaderLookedUp;

		private static float standEye = 1.65f;

		private static float crouchEye = 1.15f;

		private static bool loggedStand;

		private static bool loggedCrouch;

		private static readonly Dictionary<int, string> names = new Dictionary<int, string>();

		public static string MyName
		{
			get
			{
				string text = Mod.PlayerName.Value?.Trim();
				if (string.IsNullOrEmpty(text) && SteamApi.Init(out var _))
				{
					text = SteamApi.MyName;
				}
				if (string.IsNullOrEmpty(text))
				{
					text = "Player";
				}
				if (text.Length <= 24)
				{
					return text;
				}
				return text.Substring(0, 24);
			}
		}

		public static void Update()
		{
			if (Net.Active)
			{
				SendOwnPose();
			}
			Smooth();
		}

		private static FirstPersonController Player()
		{
			return Registry.All<FirstPersonController>().FirstOrDefault();
		}

		private static void SendOwnPose()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			if (Net.CanSend && !(Time.unscaledTime < nextSend))
			{
				nextSend = Time.unscaledTime + 1f / (float)Mathf.Max(1, Mod.PoseHz.Value);
				FirstPersonController val = Player();
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.cameraRoot == (Object)null))
				{
					Vector3 position = ((Component)val).transform.position;
					Quaternion rotation = val.cameraRoot.rotation;
					bool isCrouched = val.isCrouched;
					Net.SendToSession(WritePose((Net.Role != Role.Host) ? (-1) : 0, position, rotation, isCrouched), reliable: false);
				}
			}
		}

		private static byte[] WritePose(int id, Vector3 feet, Quaternion head, bool crouch)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return Net.Write(MsgType.PlayerPose, delegate(BinaryWriter w)
			{
				w.Write(id);
				w.Write(feet.x);
				w.Write(feet.y);
				w.Write(feet.z);
				w.Write(head.x);
				w.Write(head.y);
				w.Write(head.z);
				w.Write(head.w);
				w.Write(crouch);
			});
		}

		public static void Handle(int from, BinaryReader r)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			int num = r.ReadInt32();
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
			Quaternion val2 = default(Quaternion);
			((Quaternion)(ref val2))..ctor(r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
			bool flag = r.ReadBoolean();
			if (Net.Role == Role.Host)
			{
				num = from;
				Net.Broadcast(WritePose(num, val, val2, flag), reliable: false, from);
			}
			Avatar orCreate = GetOrCreate(num);
			if (orCreate != null)
			{
				bool flag2 = orCreate.LastSeen == 0f;
				orCreate.TargetFeet = val;
				orCreate.TargetHead = val2;
				orCreate.Crouched = flag;
				orCreate.LastSeen = Time.unscaledTime;
				if (flag2)
				{
					orCreate.Root.transform.position = val;
					ApplyHead(orCreate, 1f);
				}
				if (!loggedFirstPose)
				{
					loggedFirstPose = true;
					Instance log = Mod.Log;
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(51, 3);
					defaultInterpolatedStringHandler.AppendLiteral("Avatars: first pose from player ");
					defaultInterpolatedStringHandler.AppendFormatted(num);
					defaultInterpolatedStringHandler.AppendLiteral(" at ");
					defaultInterpolatedStringHandler.AppendFormatted<Vector3>(val);
					defaultInterpolatedStringHandler.AppendLiteral(" (my position ");
					FirstPersonController obj = Player();
					defaultInterpolatedStringHandler.AppendFormatted((obj != null) ? new Vector3?(((Component)obj).transform.position) : ((Vector3?)null));
					defaultInterpolatedStringHandler.AppendLiteral(")");
					log.Msg(defaultInterpolatedStringHandler.ToStringAndClear());
				}
			}
		}

		private static Avatar GetOrCreate(int id)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: 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)
			//IL_0069: Expected O, but got Unknown
			//IL_0092: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			if (avatars.TryGetValue(id, out var value) && (Object)(object)value.Root != (Object)null)
			{
				return value;
			}
			try
			{
				GameObject val = new GameObject($"NestCoop Avatar {id}");
				Object.DontDestroyOnLoad((Object)(object)val);
				Color val2 = ColorFor(id);
				GameObject body = null;
				GameObject shadow = null;
				GameObject val3 = new GameObject("Head");
				val3.transform.SetParent(val.transform, false);
				val3.transform.localPosition = new Vector3(0f, 1.65f, 0f);
				val3.transform.localScale = Vector3.one * 1.25f;
				if (AvatarModel.Build(val3.transform, val2, MakeMaterial))
				{
					shadow = Part((PrimitiveType)2, val.transform, Vector3.zero, new Vector3(0.45f, 0.004f, 0.45f), new Color(0.04f, 0.04f, 0.04f));
				}
				else
				{
					Object.Destroy((Object)(object)val3);
					body = Part((PrimitiveType)1, val.transform, new Vector3(0f, 0.9f, 0f), new Vector3(0.5f, 0.9f, 0.5f), val2);
					val3 = Part((PrimitiveType)0, val.transform, new Vector3(0f, 1.65f, 0f), new Vector3(0.3f, 0.3f, 0.3f), val2);
					Part((PrimitiveType)3, val3.transform, new Vector3(0f, 0.05f, 0.42f), new Vector3(0.8f, 0.3f, 0.3f), Color.black);
				}
				value = new Avatar
				{
					Root = val,
					Body = body,
					Head = val3,
					Shadow = shadow,
					Color = val2
				};
				ApplyName(value, id);
				avatars[id] = value;
				Mod.Log.Msg($"Avatars: created avatar for player {id}");
				Overlay.Toast($"Player {id} avatar spawned");
				return value;
			}
			catch (Exception value2)
			{
				Mod.Log.Error($"Avatars: could not create avatar: {value2}");
				return null;
			}
		}

		private unsafe static GameObject Part(PrimitiveType type, Transform parent, Vector3 localPos, Vector3 scale, Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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)
			GameObject obj = GameObject.CreatePrimitive(type);
			((Object)obj).name = ((object)(*(PrimitiveType*)(&type))/*cast due to .constrained prefix*/).ToString();
			Collider component = obj.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			obj.transform.SetParent(parent, false);
			obj.transform.localPosition = localPos;
			obj.transform.localScale = scale;
			Tint(obj, color);
			return obj;
		}

		private static Shader LitShader()
		{
			if (!shaderLookedUp)
			{
				shaderLookedUp = true;
				litShader = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Universal Render Pipeline/Unlit") ?? Shader.Find("Standard");
				Mod.Log.Msg("Avatars: shader " + (((Object)(object)litShader != (Object)null) ? ((Object)litShader).name : "not found"));
			}
			return litShader;
		}

		private static Material MakeMaterial(Color color, float metallic, float smoothness)
		{
			//IL_0005: 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)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			Material val = new Material(LitShader());
			val.SetColor("_BaseColor", color);
			val.SetColor("_Color", color);
			val.SetFloat("_Metallic", metallic);
			val.SetFloat("_Smoothness", smoothness);
			val.SetFloat("_Glossiness", smoothness);
			return val;
		}

		private static void Tint(GameObject go, Color color)
		{
			//IL_0031: 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)
			Renderer component = go.GetComponent<Renderer>();
			if (!((Object)(object)component == (Object)null))
			{
				if ((Object)(object)LitShader() == (Object)null)
				{
					component.material.SetColor("_Color", color);
				}
				else
				{
					component.material = MakeMaterial(color, 0f, 0.2f);
				}
			}
		}

		private static Color ColorFor(int id)
		{
			//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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			return (Color)((id % 6) switch
			{
				0 => new Color(0.95f, 0.55f, 0.1f), 
				1 => new Color(0.2f, 0.6f, 1f), 
				2 => new Color(0.3f, 0.85f, 0.3f), 
				3 => new Color(0.9f, 0.25f, 0.6f), 
				4 => new Color(0.95f, 0.9f, 0.2f), 
				_ => new Color(0.6f, 0.4f, 1f), 
			});
		}

		private static void Smooth()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			if (avatars.Count == 0)
			{
				return;
			}
			float num = 1f - Mathf.Exp(-12f * Time.unscaledDeltaTime);
			Camera main = Camera.main;
			List<int> list = null;
			foreach (var (item, avatar2) in avatars)
			{
				if ((Object)(object)avatar2.Root == (Object)null || Time.unscaledTime - avatar2.LastSeen > Mod.AvatarTimeout.Value)
				{
					(list ?? (list = new List<int>())).Add(item);
					continue;
				}
				Transform transform = avatar2.Root.transform;
				transform.position = Vector3.Lerp(transform.position, avatar2.TargetFeet, num);
				ApplyHead(avatar2, num);
				if ((Object)(object)avatar2.Label != (Object)null && (Object)(object)main != (Object)null)
				{
					Transform transform2 = avatar2.Label.transform;
					transform2.localPosition = new Vector3(0f, EyeHeight(avatar2.Crouched) + 0.35f, 0f);
					transform2.rotation = Quaternion.LookRotation(transform2.position - ((Component)main).transform.position);
				}
				PlaceShadow(avatar2);
				if ((Object)(object)avatar2.Body != (Object)null)
				{
					float num3 = (avatar2.Crouched ? 0.6f : 0.9f);
					avatar2.Body.transform.localScale = new Vector3(0.5f, num3, 0.5f);
					avatar2.Body.transform.localPosition = new Vector3(0f, num3, 0f);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (int item2 in list)
			{
				Remove(item2, "timed out");
			}
		}

		private static void ApplyHead(Avatar a, float t)
		{
			//IL_000b: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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)
			Quaternion val = Quaternion.Euler(0f, ((Quaternion)(ref a.TargetHead)).eulerAngles.y, 0f);
			a.Root.transform.rotation = Quaternion.Slerp(a.Root.transform.rotation, val, t);
			a.Head.transform.rotation = Quaternion.Slerp(a.Head.transform.rotation, a.TargetHead, t);
			a.Head.transform.localPosition = new Vector3(0f, EyeHeight(a.Crouched), 0f);
		}

		private static void PlaceShadow(Avatar a)
		{
			//IL_001a: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)a.Shadow == (Object)null)
			{
				return;
			}
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(a.Root.transform.position + Vector3.up * 0.1f, Vector3.down, ref val, 3f, -5, (QueryTriggerInteraction)1))
			{
				if (!a.Shadow.activeSelf)
				{
					a.Shadow.SetActive(true);
				}
				a.Shadow.transform.position = ((RaycastHit)(ref val)).point + Vector3.up * 0.01f;
			}
			else if (a.Shadow.activeSelf)
			{
				a.Shadow.SetActive(false);
			}
		}

		private static float EyeHeight(bool crouched)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			FirstPersonController val = Player();
			if ((Object)(object)val != (Object)null && (Object)(object)val.cameraRoot != (Object)null)
			{
				float num = val.cameraRoot.position.y - ((Component)val).transform.position.y;
				if (num > 0.3f && num < 2.5f)
				{
					if (val.isCrouched)
					{
						crouchEye = num;
						if (!loggedCrouch)
						{
							loggedCrouch = true;
							Mod.Log.Msg($"Avatars: crouched eye height {num:0.00} m");
						}
					}
					else
					{
						standEye = num;
						if (!loggedStand)
						{
							loggedStand = true;
							Mod.Log.Msg($"Avatars: standing eye height {num:0.00} m");
						}
					}
				}
			}
			if (!crouched)
			{
				return standEye;
			}
			return crouchEye;
		}

		private static byte[] WriteInfo(int id, string name)
		{
			return Net.Write(MsgType.PlayerInfo, delegate(BinaryWriter w)
			{
				w.Write(id);
				w.Write(name);
			});
		}

		public static void SendMyName()
		{
			Net.SendToSession(WriteInfo(-1, MyName), reliable: true);
		}

		public static void SendNamesTo(int peer)
		{
			Net.SendTo(peer, WriteInfo(0, MyName), reliable: true);
			foreach (var (num2, name) in names)
			{
				if (num2 != peer)
				{
					Net.SendTo(peer, WriteInfo(num2, name), reliable: true);
				}
			}
		}

		public static void HandleInfo(int from, BinaryReader r)
		{
			int num = r.ReadInt32();
			string text = r.ReadString();
			if (text.Length > 24)
			{
				text = text.Substring(0, 24);
			}
			if (Net.Role == Role.Host)
			{
				num = from;
				Net.Broadcast(WriteInfo(num, text), reliable: true, from);
			}
			names[num] = text;
			Mod.Log.Msg($"Avatars: player {num} is '{text}'");
			if (avatars.TryGetValue(num, out var value))
			{
				ApplyName(value, num);
			}
		}

		public static string NameOf(int id)
		{
			if (!names.TryGetValue(id, out var value))
			{
				return $"Player {id}";
			}
			return value;
		}

		private static void ApplyName(Avatar a, int id)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)a.Root == (Object)null)
			{
				return;
			}
			string text = NameOf(id);
			if ((Object)(object)a.Label == (Object)null)
			{
				a.Label = Text3D.Create(a.Root.transform, text, 0.03f, Color.Lerp(a.Color, Color.white, 0.35f));
				if ((Object)(object)a.Label == (Object)null)
				{
					Mod.Log.Warning("Avatars: name tag template not found; no name tags");
				}
			}
			else
			{
				((TMP_Text)a.Label).text = text;
			}
		}

		public static void OnPeerLeft(int peer)
		{
			if (Net.Role == Role.Host)
			{
				Remove(peer, "left");
			}
		}

		public static void Reset()
		{
			names.Clear();
			foreach (int item in avatars.Keys.ToList())
			{
				Remove(item, "session ended");
			}
		}

		public static void RemovePlayer(int id, string why)
		{
			Remove(id, why);
		}

		private static void Remove(int id, string why)
		{
			if (why != "timed out")
			{
				names.Remove(id);
			}
			if (avatars.Remove(id, out var value))
			{
				if ((Object)(object)value.Root != (Object)null)
				{
					Object.Destroy((Object)(object)value.Root);
				}
				Mod.Log.Msg($"Avatars: removed player {id} ({why})");
			}
		}
	}
	internal static class Combat
	{
		private static readonly Dictionary<string, (int state, int health, int armour)> sentEntities = new Dictionary<string, (int, int, int)>();

		private static readonly Dictionary<string, float> sentValves = new Dictionary<string, float>();

		private static float nextScan;

		public static bool GuestLocal
		{
			get
			{
				if (Net.Role == Role.Guest && Net.Active)
				{
					return !Net.ApplyingRemote;
				}
				return false;
			}
		}

		public static void OnHostFired(GunController gun)
		{
			if (Net.Role != Role.Host || !Net.CanSend)
			{
				return;
			}
			int index = GunIndex(gun);
			if (index >= 0)
			{
				Net.Broadcast(Net.Write(MsgType.ShellFired, delegate(BinaryWriter w)
				{
					w.Write(index);
				}), reliable: true);
				if (Mod.DebugLog.Value)
				{
					Mod.Log.Msg($"Combat: host fired gun {index}");
				}
			}
		}

		private static int GunIndex(GunController gun)
		{
			TurretController obj = Turret();
			List<GunController> val = ((obj != null) ? obj.guns : null);
			if (val == null)
			{
				return -1;
			}
			for (int i = 0; i < val.Count; i++)
			{
				if ((Object)(object)val[i] != (Object)null && ((Il2CppObjectBase)val[i]).Pointer == ((Il2CppObjectBase)gun).Pointer)
				{
					return i;
				}
			}
			return -1;
		}

		private static TurretController Turret()
		{
			return Registry.All<TurretController>().FirstOrDefault();
		}

		public static void OnHostEntityState(MapEntity e)
		{
			if (Net.Role == Role.Host && Net.CanSend && e != null)
			{
				SendEntity(e, force: true);
			}
		}

		private static void SendEntity(MapEntity e, bool force)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected I4, but got Unknown
			(int, int Health, int Armour) now = ((int)e.State, Health: e.Health, Armour: e.Armour);
			if (!force && sentEntities.TryGetValue(e.ID, out (int, int, int) value))
			{
				(int, int, int) tuple = value;
				(int, int, int) tuple2 = now;
				if (tuple.Item1 == tuple2.Item1 && tuple.Item2 == tuple2.Item2 && tuple.Item3 == tuple2.Item3)
				{
					return;
				}
			}
			sentEntities[e.ID] = now;
			string id = e.ID;
			Net.Broadcast(Net.Write(MsgType.EntityState, delegate(BinaryWriter w)
			{
				w.Write(id);
				w.Write(now.Item1);
				w.Write(now.Health);
				w.Write(now.Armour);
			}), reliable: true);
		}

		public static void RequestMove(Vector3 pos, bool dodge)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Net.SendToSession(Net.Write(MsgType.TurretMove, delegate(BinaryWriter w)
			{
				w.Write(pos.x);
				w.Write(pos.y);
				w.Write(pos.z);
				w.Write(dodge);
			}), reliable: true);
			Overlay.Toast("Asked the host to move the turret");
		}

		public static void OnHostMoved(Vector3 pos, bool dodge)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (Net.Role == Role.Host && Net.Active)
			{
				Net.Broadcast(Net.Write(MsgType.TurretMove, delegate(BinaryWriter w)
				{
					w.Write(pos.x);
					w.Write(pos.y);
					w.Write(pos.z);
					w.Write(dodge);
				}), reliable: true);
			}
		}

		public static void Update()
		{
			if (Net.Role != Role.Host || !Net.CanSend || Time.unscaledTime < nextScan)
			{
				return;
			}
			nextScan = Time.unscaledTime + 1f;
			FireMission instance = FireMission.Instance;
			if ((Object)(object)instance != (Object)null && instance.Entities != null)
			{
				Enumerator<string, MapEntity> enumerator = instance.Entities.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<string, MapEntity> current = enumerator.Current;
					if (current.Value != null)
					{
						SendEntity(current.Value, force: false);
					}
				}
			}
			foreach (ValveController item in Registry.All<ValveController>())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				string id = Ids.Of((Component)(object)item);
				float d = item.GetDamage01();
				if (!sentValves.TryGetValue(id, out var value) || !(Mathf.Abs(value - d) < 0.01f))
				{
					sentValves[id] = d;
					Net.Broadcast(Net.Write(MsgType.ValveDamage, delegate(BinaryWriter w)
					{
						w.Write(id);
						w.Write(d);
					}), reliable: true);
				}
			}
		}

		public static void Reset()
		{
			sentEntities.Clear();
			sentValves.Clear();
		}

		public static void OnGuestJoined()
		{
			Reset();
		}

		public static void Handle(MsgType type, int from, BinaryReader r)
		{
			//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_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Invalid comparison between Unknown and I4
			switch (type)
			{
			case MsgType.ShellFired:
			{
				int index = r.ReadInt32();
				if (Net.Role != Role.Guest)
				{
					break;
				}
				TurretController obj = Turret();
				List<GunController> guns = ((obj != null) ? obj.guns : null);
				if (guns != null && index >= 0 && index < guns.Count)
				{
					Remote(delegate
					{
						guns[index].FireShell();
					});
					if (Mod.DebugLog.Value)
					{
						Mod.Log.Msg($"Combat: replayed host shot from gun {index}");
					}
				}
				break;
			}
			case MsgType.EntityState:
			{
				string text = r.ReadString();
				int state = r.ReadInt32();
				int health = r.ReadInt32();
				int armour = r.ReadInt32();
				if (Net.Role != Role.Guest)
				{
					break;
				}
				FireMission fm = FireMission.Instance;
				if ((Object)(object)fm == (Object)null)
				{
					break;
				}
				MapEntity e = null;
				if (!fm.TryGetMapEntity(text, ref e) || e == null)
				{
					break;
				}
				e.Health = health;
				e.Armour = armour;
				if ((int)e.State != state)
				{
					Remote(delegate
					{
						fm.SetEntityState(e, (MapEntityStates)state);
					});
				}
				break;
			}
			case MsgType.TurretMove:
			{
				Vector3 pos = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
				bool dodge = r.ReadBoolean();
				TurretController t = Turret();
				if (!((Object)(object)t == (Object)null))
				{
					Remote(delegate
					{
						//IL_0007: Unknown result type (might be due to invalid IL or missing references)
						t.MoveTurret(pos, dodge);
					});
				}
				break;
			}
			case MsgType.ValveDamage:
			{
				string id = r.ReadString();
				float d = r.ReadSingle();
				if (Net.Role != Role.Guest)
				{
					break;
				}
				ValveController v = Registry.Find<ValveController>(id);
				if ((Object)(object)v != (Object)null && Mathf.Abs(v.GetDamage01() - d) >= 0.01f)
				{
					Remote(delegate
					{
						v.SetDamage01(d);
					});
				}
				break;
			}
			}
		}

		private static void Remote(Action a)
		{
			Net.ApplyingRemote = true;
			try
			{
				a();
			}
			catch (Exception ex)
			{
				Mod.Log.Error("Combat: applying host state failed: " + ex.Message);
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
		}
	}
	[HarmonyPatch(typeof(GunController), "FireShell")]
	internal static class Combat_FireShell
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("Combat: guest FireShell skipped (host fires)");
			return false;
		}

		private static void Postfix(GunController __instance)
		{
			if (!Net.ApplyingRemote)
			{
				Combat.OnHostFired(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(FireMission), "SetEntityState")]
	internal static class Combat_SetEntityState
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("Combat: guest SetEntityState skipped (host decides)");
			return false;
		}

		private static void Postfix(MapEntity entity)
		{
			PatchLog.Hit("FireMission.SetEntityState");
			Combat.OnHostEntityState(entity);
		}
	}
	[HarmonyPatch(typeof(TurretController), "MoveTurret")]
	internal static class Combat_MoveTurret
	{
		private static bool Prefix(Vector3 worldPos, bool dodgeCounterBattery)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			PatchLog.Hit("TurretController.MoveTurret");
			if (!Combat.GuestLocal)
			{
				return true;
			}
			Combat.RequestMove(worldPos, dodgeCounterBattery);
			return false;
		}

		private static void Postfix(Vector3 worldPos, bool dodgeCounterBattery)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Combat.OnHostMoved(worldPos, dodgeCounterBattery);
		}
	}
	[HarmonyPatch(typeof(ValveController), "Damage")]
	internal static class Combat_ValveDamage
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("Combat: guest valve Damage skipped");
			return false;
		}
	}
	[HarmonyPatch(typeof(ValveController), "DamageValve")]
	internal static class Combat_ValveDamageValve
	{
		private static bool Prefix()
		{
			if (!Combat.GuestLocal)
			{
				return true;
			}
			PatchLog.Hit("Combat: guest DamageValve skipped");
			return false;
		}
	}
	internal static class ControlSync
	{
		private sealed class Control
		{
			public string Id;

			public DialInteractable Dial;

			public LinearSliderInteractable Slider;

			public float LastSent = float.NaN;

			public float Target;

			public bool Smoothing;

			public bool Verified;

			public bool Dragging
			{
				get
				{
					if (!((Object)(object)Dial != (Object)null))
					{
						return Slider.IsDragging;
					}
					return Dial.IsDragging;
				}
			}

			public bool Alive
			{
				get
				{
					if (!((Object)(object)Dial != (Object)null))
					{
						return (Object)(object)Slider != (Object)null;
					}
					return true;
				}
			}

			public float Get()
			{
				if (!((Object)(object)Dial != (Object)null))
				{
					return Slider.Value;
				}
				return Dial.AccumulatedValue;
			}
		}

		private const float Epsilon = 0.01f;

		private static readonly Dictionary<string, Control> controls = new Dictionary<string, Control>();

		private static int builtForRegistry = -1;

		private static readonly Dictionary<string, int> heldBy = new Dictionary<string, int>();

		private static float nextControlTick;

		private static float nextTurretTick;

		private static float nextStatsLog;

		private static int statSent;

		private static int statApplied;

		private static int statSnaps;

		private static int statBlends;

		private static float statMaxErr;

		private static readonly HashSet<string> remoteDragging = new HashSet<string>();

		private static bool loggedDriveCheck;

		private const float SmoothRate = 18f;

		private static void EnsureControls()
		{
			if (builtForRegistry == Registry.Version && controls.Count > 0)
			{
				return;
			}
			controls.Clear();
			foreach (DialInteractable item in Registry.All<DialInteractable>())
			{
				Add(new Control
				{
					Id = Ids.Of((Component)(object)item),
					Dial = item
				});
			}
			foreach (LinearSliderInteractable item2 in Registry.All<LinearSliderInteractable>())
			{
				Add(new Control
				{
					Id = Ids.Of((Component)(object)item2),
					Slider = item2
				});
			}
			builtForRegistry = Registry.Version;
			if (Mod.DebugLog.Value)
			{
				Mod.Log.Msg($"ControlSync: {controls.Count} shared controls");
			}
		}

		private static void Add(Control c)
		{
			if (SyncPolicy.IsShared(c.Id))
			{
				controls.TryAdd(c.Id, c);
			}
		}

		private static Control Find(string id)
		{
			EnsureControls();
			if (!controls.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		public static void Update()
		{
			if (!Net.Active)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			TurretProbe.Update(RemoteTraverseDrag());
			Glide();
			if (unscaledTime >= nextControlTick)
			{
				nextControlTick = unscaledTime + 1f / (float)Mathf.Max(1, Mod.SyncHz.Value);
				SendControlValues();
			}
			if (Net.Role == Role.Host && unscaledTime >= nextTurretTick)
			{
				nextTurretTick = unscaledTime + 1f / (float)Mathf.Max(1, Mod.TurretHz.Value);
				SendTurretState();
			}
			if (Mod.DebugLog.Value && unscaledTime >= nextStatsLog)
			{
				nextStatsLog = unscaledTime + 5f;
				if (statSent + statApplied + statSnaps + statBlends > 0)
				{
					Mod.Log.Msg($"ControlSync 5s: sent {statSent}, applied {statApplied}, turret snaps {statSnaps}, blends {statBlends}, max err {statMaxErr:0.##}°");
				}
				statSent = (statApplied = (statSnaps = (statBlends = 0)));
				statMaxErr = 0f;
			}
		}

		private static void SendControlValues()
		{
			if (!Net.CanSend)
			{
				return;
			}
			EnsureControls();
			foreach (Control c in controls.Values)
			{
				if (!c.Alive || !((Net.Role == Role.Host) ? (!heldBy.ContainsKey(c.Id)) : c.Dragging))
				{
					continue;
				}
				float v = c.Get();
				if (float.IsNaN(c.LastSent) || !(Mathf.Abs(v - c.LastSent) < 0.01f))
				{
					c.LastSent = v;
					Net.SendToSession(Net.Write(MsgType.ControlValue, delegate(BinaryWriter w)
					{
						w.Write(c.Id);
						w.Write(v);
					}), reliable: false);
					statSent++;
				}
			}
		}

		public static void OnLocalGrab(Component control, bool grabbed)
		{
			if (!Net.CanSend)
			{
				return;
			}
			string id = Ids.Of(control);
			Control control2 = Find(id);
			if (control2 != null)
			{
				float v = control2.Get();
				control2.LastSent = v;
				Net.SendToSession(Net.Write(MsgType.ControlGrab, delegate(BinaryWriter w)
				{
					w.Write(id);
					w.Write(grabbed);
					w.Write(v);
				}), reliable: true);
				if (Mod.DebugLog.Value)
				{
					Mod.Log.Msg($"ControlSync: {(grabbed ? "grab" : "release")} {id} = {v:0.###}");
				}
			}
		}

		private static bool HeldByOther(Control c, int peer)
		{
			if (!c.Dragging)
			{
				if (heldBy.TryGetValue(c.Id, out var value))
				{
					return value != peer;
				}
				return false;
			}
			return true;
		}

		public static void OnPeerLeft(int peer)
		{
			foreach (string id in (from kv in heldBy
				where kv.Value == peer
				select kv.Key).ToList())
			{
				heldBy.Remove(id);
				if (controls.TryGetValue(id, out var value))
				{
					SetRemoteDrag(value, begin: false);
					float v = value.Get();
					value.LastSent = v;
					Net.Broadcast(Net.Write(MsgType.ControlGrab, delegate(BinaryWriter w)
					{
						w.Write(id);
						w.Write(value: false);
						w.Write(v);
					}), reliable: true);
				}
			}
		}

		public static void Reset()
		{
			foreach (string item in remoteDragging.ToList())
			{
				if (controls.TryGetValue(item, out var value))
				{
					SetRemoteDrag(value, begin: false);
				}
			}
			remoteDragging.Clear();
			heldBy.Clear();
		}

		public static bool RemoteTraverseDrag()
		{
			if (remoteDragging.Count == 0)
			{
				return false;
			}
			TurretController val = Turret();
			if ((Object)(object)val != (Object)null && (Object)(object)val.rotationDial != (Object)null)
			{
				return remoteDragging.Contains(Ids.Of((Component)(object)val.rotationDial));
			}
			return false;
		}

		private static bool IsTraverseWheel(Control c)
		{
			if ((Object)(object)c.Dial == (Object)null)
			{
				return false;
			}
			TurretController val = Turret();
			if ((Object)(object)val != (Object)null && (Object)(object)val.rotationDial != (Object)null)
			{
				return c.Id == Ids.Of((Component)(object)val.rotationDial);
			}
			return false;
		}

		private static void OnRemoteTraverseValue(float wheel)
		{
			if (Net.Role == Role.Host)
			{
				TurretController obj = Turret();
				float value = (obj._DesiredRotation_k__BackingField = obj.MapDialToTurretRotation(wheel));
				if (!loggedDriveCheck)
				{
					loggedDriveCheck = true;
					Mod.Log.Msg($"ControlSync: remote traverse drive: wheel {wheel:0.##} -> desired {value:0.##} (wheel/720 = {wheel / 720f:0.##})");
				}
			}
		}

		private static void SetRemoteDrag(Control c, bool begin)
		{
			if (begin ? (!remoteDragging.Add(c.Id)) : (!remoteDragging.Remove(c.Id)))
			{
				return;
			}
			Net.ApplyingRemote = true;
			try
			{
				if ((Object)(object)c.Dial != (Object)null)
				{
					if (!IsTraverseWheel(c))
					{
						Action obj = (begin ? c.Dial.OnBeginDialDrag : c.Dial.OnEndDialDrag);
						if (obj != null)
						{
							obj.Invoke();
						}
					}
					UnityEvent obj2 = (begin ? c.Dial.OnGrab : c.Dial.OnRelease);
					if (obj2 != null)
					{
						obj2.Invoke();
					}
				}
				else
				{
					Action obj3 = (begin ? c.Slider.OnBeginSliderDrag : c.Slider.OnEndSliderDrag);
					if (obj3 != null)
					{
						obj3.Invoke();
					}
					UnityEvent obj4 = (begin ? c.Slider.OnGrab : c.Slider.OnRelease);
					if (obj4 != null)
					{
						obj4.Invoke();
					}
				}
			}
			catch (Exception ex)
			{
				Mod.Log.Error("ControlSync: drag event " + c.Id + " failed: " + ex.Message);
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
		}

		public static void SendSnapshot(int peer)
		{
			EnsureControls();
			int num = 0;
			foreach (Control c in controls.Values)
			{
				if (c.Alive)
				{
					float v = c.Get();
					Net.SendTo(peer, Net.Write(MsgType.ControlValue, delegate(BinaryWriter w)
					{
						w.Write(c.Id);
						w.Write(v);
					}), reliable: true);
					num++;
				}
			}
			Mod.Log.Msg($"ControlSync: sent {num} control values to guest #{peer}");
		}

		public static void Handle(MsgType type, int from, BinaryReader r, byte[] raw)
		{
			switch (type)
			{
			case MsgType.ControlValue:
			{
				string text2 = r.ReadString();
				float num2 = r.ReadSingle();
				Control control2 = Find(text2);
				if (control2 == null)
				{
					Mod.Log.Warning("ControlSync: unknown/non-shared control " + text2);
				}
				else
				{
					if (Net.Role == Role.Host && HeldByOther(control2, from))
					{
						break;
					}
					if (IsTraverseWheel(control2))
					{
						OnRemoteTraverseValue(num2);
						if (Net.Role == Role.Host)
						{
							heldBy.TryAdd(text2, from);
							control2.LastSent = num2;
							Net.Broadcast(raw, reliable: false, from);
						}
					}
					else if (Net.Role == Role.Host)
					{
						heldBy.TryAdd(text2, from);
						SetTarget(control2, num2);
						control2.LastSent = num2;
						Net.Broadcast(raw, reliable: false, from);
					}
					else if (!control2.Dragging)
					{
						SetTarget(control2, num2);
					}
				}
				break;
			}
			case MsgType.ControlGrab:
			{
				string text = r.ReadString();
				bool flag = r.ReadBoolean();
				float num = r.ReadSingle();
				Control control = Find(text);
				if (control == null)
				{
					break;
				}
				if (Net.Role == Role.Host && flag && HeldByOther(control, from))
				{
					Mod.Log.Msg($"ControlSync: guest #{from} tried to grab {text}, already held");
				}
				else
				{
					if (Net.Role == Role.Host && !flag && heldBy.TryGetValue(text, out var value) && value != from)
					{
						break;
					}
					bool flag2 = IsTraverseWheel(control);
					if (flag2)
					{
						OnRemoteTraverseValue(num);
					}
					if (Net.Role == Role.Host)
					{
						if (flag)
						{
							heldBy[text] = from;
						}
						else
						{
							heldBy.Remove(text);
						}
						if (!flag2)
						{
							Apply(control, num);
						}
						control.LastSent = num;
						Net.Broadcast(raw, reliable: true, from);
					}
					else if (!control.Dragging && !flag2)
					{
						Apply(control, num);
					}
					if (!control.Dragging)
					{
						SetRemoteDrag(control, flag);
					}
					if (Mod.DebugLog.Value)
					{
						Mod.Log.Msg($"ControlSync: remote {(flag ? "grab" : "release")} {text} = {num:0.###}");
					}
				}
				break;
			}
			case MsgType.TurretState:
				ApplyTurretState(r);
				break;
			}
		}

		private static float SnapDistance(Control c)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)c.Dial != (Object)null) || (int)c.Dial.dialMode != 0)
			{
				return 1E+09f;
			}
			return 720f;
		}

		private static void SetTarget(Control c, float v)
		{
			if (Mathf.Abs(v - c.Get()) > SnapDistance(c))
			{
				c.Smoothing = false;
				Apply(c, v);
			}
			else
			{
				c.Target = v;
				c.Smoothing = true;
			}
		}

		private static void Glide()
		{
			if (controls.Count == 0)
			{
				return;
			}
			float num = 1f - Mathf.Exp(-18f * Time.unscaledDeltaTime);
			foreach (Control value in controls.Values)
			{
				if (!value.Smoothing)
				{
					continue;
				}
				if (!value.Alive || value.Dragging)
				{
					value.Smoothing = false;
					continue;
				}
				float num2 = value.Get();
				float num3 = value.Target - num2;
				if (Mathf.Abs(num3) < 0.01f)
				{
					Apply(value, value.Target);
					value.Smoothing = false;
				}
				else
				{
					Apply(value, num2 + num3 * num);
				}
			}
		}

		private static void Apply(Control c, float v)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			float value = c.Get();
			Net.ApplyingRemote = true;
			try
			{
				if ((Object)(object)c.Slider != (Object)null)
				{
					c.Slider.SetSliderValue(v);
				}
				else if ((int)c.Dial.dialMode == 0)
				{
					c.Dial.SetAccumulatedValueUnlimited(v, true, true);
				}
				else
				{
					c.Dial.SetDialValue(v);
				}
			}
			catch (Exception ex)
			{
				Mod.Log.Error("ControlSync: apply " + c.Id + " failed: " + ex.Message);
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
			statApplied++;
			if (!c.Verified)
			{
				c.Verified = true;
				Mod.Log.Msg($"ControlSync: first apply {c.Id} ({(((Object)(object)c.Slider != (Object)null) ? "slider" : ((object)c.Dial.dialMode/*cast due to .constrained prefix*/).ToString())}): {value:0.###} -> target {v:0.###}, now {c.Get():0.###}");
			}
		}

		private static TurretController Turret()
		{
			return Registry.All<TurretController>().FirstOrDefault();
		}

		private static void SendTurretState()
		{
			if (!Net.CanSend)
			{
				return;
			}
			TurretController val = Turret();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float angle = val._CurrentAngle_k__BackingField;
			float desired = val._DesiredRotation_k__BackingField;
			float vel = val.rotationVelocity;
			List<GunController> guns = val.guns;
			int n = guns?.Count ?? 0;
			float[] elev = new float[n];
			for (int i = 0; i < n; i++)
			{
				elev[i] = guns[i]._CurrentElevation_k__BackingField;
			}
			Net.Broadcast(Net.Write(MsgType.TurretState, delegate(BinaryWriter w)
			{
				w.Write(angle);
				w.Write(desired);
				w.Write(vel);
				w.Write(n);
				float[] array = elev;
				foreach (float value in array)
				{
					w.Write(value);
				}
			}), reliable: false);
		}

		private static void ApplyTurretState(BinaryReader r)
		{
			float num = r.ReadSingle();
			float desiredRotation_k__BackingField = r.ReadSingle();
			float rotationVelocity = r.ReadSingle();
			int num2 = r.ReadInt32();
			float[] array = new float[num2];
			for (int i = 0; i < num2; i++)
			{
				array[i] = r.ReadSingle();
			}
			if (Net.Role != Role.Guest)
			{
				return;
			}
			TurretController val = Turret();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float num3 = Mathf.DeltaAngle(val._CurrentAngle_k__BackingField, num);
			statMaxErr = Mathf.Max(statMaxErr, Mathf.Abs(num3));
			val._DesiredRotation_k__BackingField = desiredRotation_k__BackingField;
			if (Mathf.Abs(num3) > Mod.TurretSnapDegrees.Value)
			{
				val._CurrentAngle_k__BackingField = num;
				val.rotationVelocity = rotationVelocity;
				statSnaps++;
			}
			else if (Mathf.Abs(num3) > 0.05f)
			{
				val._CurrentAngle_k__BackingField += num3 * 0.3f;
				statBlends++;
			}
			val.ApplyRotationToTransforms();
			List<GunController> guns = val.guns;
			for (int j = 0; j < num2; j++)
			{
				if (guns == null)
				{
					break;
				}
				if (j >= guns.Count)
				{
					break;
				}
				float currentElevation_k__BackingField = guns[j]._CurrentElevation_k__BackingField;
				float num4 = array[j] - currentElevation_k__BackingField;
				if (Mathf.Abs(num4) > 1f)
				{
					guns[j]._CurrentElevation_k__BackingField = array[j];
				}
				else if (Mathf.Abs(num4) > 0.02f)
				{
					guns[j]._CurrentElevation_k__BackingField = currentElevation_k__BackingField + num4 * 0.3f;
				}
			}
		}
	}
	internal static class DebugKeys
	{
		public static LookAtTarget LastPressed;

		private static bool loggedNoKeyboard;

		private static bool loggedKeyboardOk;

		public static void Update()
		{
			if (Pressed(Mod.MenuKey.Value))
			{
				CoopMenu.Toggle();
			}
			if (Mod.DebugLog.Value && Pressed(Mod.UiDumpKey.Value))
			{
				try
				{
					UiDump.Run();
				}
				catch (Exception value)
				{
					Mod.Log.Error($"UI dump failed: {value}");
				}
			}
			if (Pressed(Mod.HostKey.Value))
			{
				Net.StartHost();
			}
			if (Pressed(Mod.JoinKey.Value))
			{
				Net.Join();
			}
			if (Pressed(Mod.LeaveKey.Value))
			{
				Net.Stop("leave key");
			}
			if (Mod.DebugLog.Value && Pressed(Mod.ReplayKey.Value))
			{
				ReplayLastPress();
			}
			if (Mod.DebugLog.Value && Pressed(Mod.MissionReplayKey.Value))
			{
				MissionSync.DebugReplay();
			}
			if (Mod.DebugLog.Value && Pressed(Mod.CheckpointTestKey.Value))
			{
				Snapshot.DebugRoundTrip();
			}
			if (Mod.DebugLog.Value && Pressed(Mod.ItemReplayKey.Value))
			{
				ItemSync.DebugReplay();
			}
			if (Mod.DebugLog.Value && Pressed(Mod.SteamCheckKey.Value))
			{
				SteamCheck();
			}
		}

		private static bool Pressed(string keyName)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Keyboard current = Keyboard.current;
				if (current == null)
				{
					if (!loggedNoKeyboard)
					{
						loggedNoKeyboard = true;
						Mod.Log.Warning("DebugKeys: Keyboard.current is null");
					}
					return false;
				}
				if (!loggedKeyboardOk && ((ButtonControl)current.anyKey).wasPressedThisFrame)
				{
					loggedKeyboardOk = true;
					Mod.Log.Msg("DebugKeys: keyboard input OK");
				}
				Key result;
				return Enum.TryParse<Key>(keyName, ignoreCase: true, out result) && ((ButtonControl)current[result]).wasPressedThisFrame;
			}
			catch (Exception ex)
			{
				if (!loggedNoKeyboard)
				{
					loggedNoKeyboard = true;
					Mod.Log.Warning("DebugKeys: Input System read failed: " + ex.Message);
				}
				return false;
			}
		}

		private static void SteamCheck()
		{
			if (!SteamApi.Init(out var why))
			{
				Mod.Log.Warning("Steam check: " + why);
				Overlay.Toast("Steam: " + why);
				return;
			}
			List<(ulong, string)> list = SteamApi.FriendsInThisGame();
			string text = $"{SteamApi.MyName} ({SteamApi.MySteamId}), app {SteamApi.AppId}";
			string text2 = ((list.Count == 0) ? "none" : string.Join(", ", list.Select<(ulong, string), string>(((ulong id, string name) f) => $"{f.name} ({f.id})")));
			Mod.Log.Msg("Steam check: OK as " + text + ". Friends in IRON NEST: " + text2);
			Overlay.Toast($"Steam OK: {SteamApi.MyName}. Friends in game: {list.Count}", 6f);
		}

		private static void ReplayLastPress()
		{
			if ((Object)(object)LastPressed == (Object)null)
			{
				Mod.Log.Msg("Replay: press a button in-game first.");
				return;
			}
			Mod.Log.Msg("Replay: replaying OnClickDown on " + Ids.Of((Component)(object)LastPressed));
			Net.ApplyingRemote = true;
			try
			{
				LastPressed.OnClickDown();
			}
			catch (Exception value)
			{
				Mod.Log.Error($"Replay failed: {value}");
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
		}
	}
	internal static class Ids
	{
		public static string Of(Component c)
		{
			//IL_0015: 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)
			if ((Object)(object)c == (Object)null)
			{
				return "<null>";
			}
			Scene scene = c.gameObject.scene;
			string text = ((Scene)(ref scene)).name + ":" + NamePath(c.transform);
			int num = SameTypeIndex(c);
			if (num != 0)
			{
				return $"{text}~{num}";
			}
			return text;
		}

		private static int SameTypeIndex(Component c)
		{
			Type il2CppType = ((Object)c).GetIl2CppType();
			int num = 0;
			foreach (Component item in (Il2CppArrayBase<Component>)(object)c.GetComponents(il2CppType))
			{
				if ((Object)(object)item == (Object)(object)c)
				{
					return num;
				}
				num++;
			}
			return 0;
		}

		public static string NamePath(Transform t)
		{
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null)
			{
				list.Add(((Object)val).name + Occurrence(val));
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}

		private static string Occurrence(Transform t)
		{
			//IL_0018: 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 parent = t.parent;
			int num = 0;
			if ((Object)(object)parent == (Object)null)
			{
				Scene scene = ((Component)t).gameObject.scene;
				foreach (GameObject item in (Il2CppArrayBase<GameObject>)(object)((Scene)(ref scene)).GetRootGameObjects())
				{
					if ((Object)(object)item.transform == (Object)(object)t)
					{
						break;
					}
					if (((Object)item).name == ((Object)t).name)
					{
						num++;
					}
				}
			}
			else
			{
				for (int i = 0; i < parent.childCount; i++)
				{
					Transform child = parent.GetChild(i);
					if ((Object)(object)child == (Object)(object)t)
					{
						break;
					}
					if (((Object)child).name == ((Object)t).name)
					{
						num++;
					}
				}
			}
			if (num != 0)
			{
				return "#" + num;
			}
			return "";
		}

		public static Transform ResolveTransform(string id)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(id))
			{
				return null;
			}
			int num = id.IndexOf(':');
			if (num < 0)
			{
				return null;
			}
			string text = id.Substring(0, num);
			int num2 = num + 1;
			string text2 = id.Substring(num2, id.Length - num2);
			int num3 = text2.LastIndexOf('~');
			if (num3 > text2.LastIndexOf('/'))
			{
				text2 = text2.Substring(0, num3);
			}
			Scene sceneByName = SceneManager.GetSceneByName(text);
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			string[] array = text2.Split('/');
			(string name, int index) tuple = Segment(array[0]);
			string item = tuple.name;
			int item2 = tuple.index;
			Transform val = null;
			int num4 = 0;
			foreach (GameObject item5 in (Il2CppArrayBase<GameObject>)(object)((Scene)(ref sceneByName)).GetRootGameObjects())
			{
				if (((Object)item5).name == item && num4++ == item2)
				{
					val = item5.transform;
					break;
				}
			}
			for (int i = 1; i < array.Length; i++)
			{
				if (!((Object)(object)val != (Object)null))
				{
					break;
				}
				(string name, int index) tuple2 = Segment(array[i]);
				string item3 = tuple2.name;
				int item4 = tuple2.index;
				Transform val2 = null;
				int num5 = 0;
				for (int j = 0; j < val.childCount; j++)
				{
					Transform child = val.GetChild(j);
					if (((Object)child).name == item3 && num5++ == item4)
					{
						val2 = child;
						break;
					}
				}
				val = val2;
			}
			return val;
		}

		private static (string name, int index) Segment(string seg)
		{
			int num = seg.LastIndexOf('#');
			if (num > 0)
			{
				int num2 = num + 1;
				if (int.TryParse(seg.Substring(num2, seg.Length - num2), out var result))
				{
					return (name: seg.Substring(0, num), index: result);
				}
			}
			return (name: seg, index: 0);
		}
	}
	internal static class PatchLog
	{
		private static readonly HashSet<string> hit = new HashSet<string>();

		public static void Hit(string patch, string detail = null)
		{
			if (Mod.DebugLog.Value)
			{
				bool num = hit.Add(patch);
				string text = (Net.ApplyingRemote ? " [remote]" : "");
				if (num)
				{
					Mod.Log.Msg($"FIRST HIT {patch}{text} {detail}");
				}
				else if (detail != null)
				{
					Mod.Log.Msg(patch + text + " " + detail);
				}
			}
		}
	}
	internal static class ItemSync
	{
		private const byte LocDeck = 0;

		private const byte LocSurface = 1;

		private const byte LocSlot = 2;

		private const byte LocCarried = 3;

		private static readonly Dictionary<IntPtr, (DraggableItem item, float due)> pending = new Dictionary<IntPtr, (DraggableItem, float)>();

		private static readonly Dictionary<string, DraggableItem> byId = new Dictionary<string, DraggableItem>();

		private static readonly HashSet<IntPtr> hidden = new HashSet<IntPtr>();

		private static float nextRescan;

		private static readonly Dictionary<string, (byte[] previous, byte[] latest)> history = new Dictionary<string, (byte[], byte[])>();

		private static string lastItem;

		public static void Moved(DraggableItem item, string how)
		{
			if (!((Object)(object)item == (Object)null) && !Net.ApplyingRemote && (Net.Active || Mod.DebugLog.Value) && !((Object)(object)((Component)item).GetComponent<RecordItem>() != (Object)null))
			{
				PatchLog.Hit("DraggableItem." + how, ((Object)item).name);
				pending[((Il2CppObjectBase)item).Pointer] = (item, Time.unscaledTime + 0.35f);
			}
		}

		public static void Update()
		{
			if (pending.Count == 0)
			{
				return;
			}
			List<IntPtr> list = null;
			foreach (KeyValuePair<IntPtr, (DraggableItem, float)> item2 in pending)
			{
				item2.Deconstruct(out var key, out var value);
				(DraggableItem, float) tuple = value;
				IntPtr item = key;
				var (val, num) = tuple;
				if (Time.unscaledTime < num)
				{
					continue;
				}
				(list ?? (list = new List<IntPtr>())).Add(item);
				if (!((Object)(object)val == (Object)null) && !val.IsBeingDragged)
				{
					try
					{
						Send(val);
					}
					catch (Exception ex)
					{
						Mod.Log.Warning("ItemSync: couldn't send " + ((Object)val).name + ": " + ex.Message);
					}
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (IntPtr item3 in list)
			{
				pending.Remove(item3);
			}
		}

		private static void Send(DraggableItem item)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			bool canSend = Net.CanSend;
			if (!canSend && !Mod.DebugLog.Value)
			{
				return;
			}
			string id = IdOf(item);
			string container = "";
			string json = "";
			byte loc;
			if (OnOwnClipboard(item))
			{
				loc = 3;
			}
			else
			{
				loc = (byte)item.CurrentLocation;
				if (loc == 2 && (Object)(object)item.SlotRef != (Object)null)
				{
					container = Ids.Of((Component)(object)item.SlotRef);
				}
				else if (loc == 0 && (Object)(object)item.deckRef != (Object)null)
				{
					container = Ids.Of((Component)(object)item.deckRef);
				}
				DraggableSurfaceSaveState val = MissionSaveManager.CaptureDraggableSurfaceState(item);
				if (val != null)
				{
					json = JsonConvert.SerializeObject((Object)(object)val, ProgressionSaveUtility.JsonSettings);
				}
			}
			byte[] array = Net.Write(MsgType.ItemState, delegate(BinaryWriter w)
			{
				w.Write(id);
				w.Write(loc);
				w.Write(container);
				w.Write(json);
			});
			history[id] = (history.TryGetValue(id, out (byte[], byte[]) value) ? value.Item2 : null, array);
			lastItem = id;
			if (canSend)
			{
				Net.SendToSession(array, reliable: true);
			}
			if (Mod.DebugLog.Value)
			{
				Mod.Log.Msg($"ItemSync: {(canSend ? "sent" : "recorded (no session)")} {id} {LocName(loc)} {container}");
			}
		}

		private static string IdOf(DraggableItem item)
		{
			MissionSaveIdentity component = ((Component)item).GetComponent<MissionSaveIdentity>();
			if (!((Object)(object)component != (Object)null) || string.IsNullOrEmpty(component.Id))
			{
				return Ids.Of((Component)(object)item);
			}
			return "msi:" + component.Id;
		}

		private static bool OnOwnClipboard(DraggableItem item)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			DragSurface surfaceRef = item.surfaceRef;
			Camera main = Camera.main;
			if ((int)item.CurrentLocation == 1 && (Object)(object)surfaceRef != (Object)null && (Object)(object)main != (Object)null)
			{
				return ((Component)surfaceRef).transform.IsChildOf(((Component)main).transform);
			}
			return false;
		}

		public static void Handle(int from, BinaryReader r, byte[] data)
		{
			string id = r.ReadString();
			byte loc = r.ReadByte();
			string container = r.ReadString();
			string json = r.ReadString();
			if (Net.Role == Role.Host)
			{
				Net.Broadcast(data, reliable: true, from);
			}
			Apply(id, loc, container, json);
		}

		private static void Apply(string id, byte loc, string container, string json)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			DraggableItem val = Find(id);
			if ((Object)(object)val == (Object)null)
			{
				Mod.Log.Warning("ItemSync: item " + id + " not found here");
				return;
			}
			if (val.IsBeingDragged)
			{
				Mod.Log.Msg("ItemSync: ignored a remote move of " + ((Object)val).name + " (you're holding it)");
				return;
			}
			pending.Remove(((Il2CppObjectBase)val).Pointer);
			Net.ApplyingRemote = true;
			try
			{
				if (loc == 3)
				{
					SetHidden(val, hide: true);
					return;
				}
				SetHidden(val, hide: false);
				if (loc == 2)
				{
					Transform obj = Ids.ResolveTransform(container);
					ItemSlot val2 = ((obj != null) ? ((Component)obj).GetComponent<ItemSlot>() : null);
					if (val2 != null)
					{
						if ((Object)(object)val.SlotRef == (Object)null || ((Il2CppObjectBase)val.SlotRef).Pointer != ((Il2CppObjectBase)val2).Pointer)
						{
							val.MoveToSlot(val2);
						}
						goto IL_01ac;
					}
				}
				if (loc == 0)
				{
					Transform obj2 = Ids.ResolveTransform(container);
					DraggableItemDeckArea val3 = ((obj2 != null) ? ((Component)obj2).GetComponent<DraggableItemDeckArea>() : null);
					if (val3 != null)
					{
						if ((Object)(object)val.deckRef == (Object)null || ((Il2CppObjectBase)val.deckRef).Pointer != ((Il2CppObjectBase)val3).Pointer || (int)val.CurrentLocation != 0)
						{
							val.MoveToDeck(val3);
						}
						goto IL_01ac;
					}
				}
				if (!string.IsNullOrEmpty(json))
				{
					Object obj3 = JsonConvert.DeserializeObject(json, Il2CppType.Of<DraggableSurfaceSaveState>(), ProgressionSaveUtility.JsonSettings);
					DraggableSurfaceSaveState val4 = ((obj3 != null) ? ((Il2CppObjectBase)obj3).TryCast<DraggableSurfaceSaveState>() : null);
					if (val4 == null)
					{
						Mod.Log.Warning("ItemSync: bad state for " + id);
						return;
					}
					List<DragSurface> allSurfaces = DragSurface.AllSurfaces;
					DragSurface[] array = (DragSurface[])(object)new DragSurface[allSurfaces.Count];
					for (int i = 0; i < array.Length; i++)
					{
						array[i] = allSurfaces[i];
					}
					RestoreState(val, val4, new Il2CppReferenceArray<DragSurface>(array));
				}
				goto IL_01ac;
				IL_01ac:
				PatchLog.Hit("ItemSync.Apply", $"{((Object)val).name} -> {LocName(loc)} {container}");
			}
			catch (Exception value)
			{
				Mod.Log.Error($"ItemSync: applying {id} failed: {value}");
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
		}

		private static void RestoreState(DraggableItem item, DraggableSurfaceSaveState state, Il2CppReferenceArray<DragSurface> surfaces)
		{
			MissionSaveManager.RestoreDraggableSurfaceState(item, state, surfaces);
		}

		private static DraggableItem[] AllItems()
		{
			return Il2CppArrayBase<DraggableItem>.op_Implicit(Object.FindObjectsByType<DraggableItem>((FindObjectsInactive)1, (FindObjectsSortMode)0));
		}

		private static DraggableItem Find(string id)
		{
			if (byId.TryGetValue(id, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (!id.StartsWith("msi:"))
			{
				Transform val = Ids.ResolveTransform(id);
				if (!((Object)(object)val != (Object)null))
				{
					return null;
				}
				return ((Component)val).GetComponent<DraggableItem>();
			}
			if (Time.unscaledTime < nextRescan)
			{
				return null;
			}
			nextRescan = Time.unscaledTime + 0.5f;
			byId.Clear();
			DraggableItem[] array = AllItems();
			foreach (DraggableItem val2 in array)
			{
				MissionSaveIdentity component = ((Component)val2).GetComponent<MissionSaveIdentity>();
				if ((Object)(object)component != (Object)null && !string.IsNullOrEmpty(component.Id))
				{
					byId["msi:" + component.Id] = val2;
				}
			}
			if (!byId.TryGetValue(id, out value))
			{
				return null;
			}
			return value;
		}

		private static void SetHidden(DraggableItem item, bool hide)
		{
			bool flag = hidden.Contains(((Il2CppObjectBase)item).Pointer);
			if (hide == flag)
			{
				return;
			}
			foreach (Renderer componentsInChild in ((Component)item).GetComponentsInChildren<Renderer>(true))
			{
				componentsInChild.enabled = !hide;
			}
			foreach (Collider componentsInChild2 in ((Component)item).GetComponentsInChildren<Collider>(true))
			{
				componentsInChild2.enabled = !hide;
			}
			if (hide)
			{
				hidden.Add(((Il2CppObjectBase)item).Pointer);
			}
			else
			{
				hidden.Remove(((Il2CppObjectBase)item).Pointer);
			}
		}

		private static string LocName(byte loc)
		{
			return loc switch
			{
				0 => "deck", 
				1 => "surface", 
				2 => "slot", 
				3 => "carried", 
				_ => loc.ToString(), 
			};
		}

		public static void Reset()
		{
			pending.Clear();
			byId.Clear();
			DraggableItem[] array = AllItems();
			foreach (DraggableItem val in array)
			{
				if ((Object)(object)val != (Object)null && hidden.Contains(((Il2CppObjectBase)val).Pointer))
				{
					SetHidden(val, hide: false);
				}
			}
			hidden.Clear();
		}

		public static void DebugReplay()
		{
			if (lastItem == null || !history.TryGetValue(lastItem, out (byte[], byte[]) value) || value.Item1 == null)
			{
				Overlay.Toast("ItemSync: move the same item twice during a session first");
				return;
			}
			history[lastItem] = (null, value.Item1);
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(value.Item1));
			binaryReader.ReadByte();
			string text = binaryReader.ReadString();
			byte loc = binaryReader.ReadByte();
			string text2 = binaryReader.ReadString();
			string json = binaryReader.ReadString();
			Mod.Log.Msg($"ItemSync: replaying the previous state of {text} ({LocName(loc)} {text2})");
			Overlay.Toast("Moving it back to where you had it before (" + LocName(loc) + ")");
			Apply(text, loc, text2, json);
		}
	}
	[HarmonyPatch(typeof(DraggableItem), "EndDragInternal")]
	internal static class Item_EndDrag
	{
		private static void Postfix(DraggableItem __instance)
		{
			ItemSync.Moved(__instance, "EndDragInternal");
		}
	}
	[HarmonyPatch(typeof(DraggableItem), "EndDragFromManager")]
	internal static class Item_EndDragFromManager
	{
		private static void Postfix(DraggableItem __instance)
		{
			ItemSync.Moved(__instance, "EndDragFromManager");
		}
	}
	[HarmonyPatch(typeof(DraggableItem), "MoveToSlot", new Type[] { typeof(ItemSlot) })]
	internal static class Item_MoveToSlot
	{
		private static void Postfix(DraggableItem __instance)
		{
			ItemSync.Moved(__instance, "MoveToSlot");
		}
	}
	[HarmonyPatch(typeof(DraggableItem), "MoveToDeck", new Type[] { typeof(DraggableItemDeckArea) })]
	internal static class Item_MoveToDeck
	{
		private static void Postfix(DraggableItem __instance)
		{
			ItemSync.Moved(__instance, "MoveToDeck");
		}
	}
	[HarmonyPatch(typeof(DraggableItem), "HandlePickedUpToClipboard")]
	internal static class Item_ToClipboard
	{
		private static void Postfix(DraggableItem __instance)
		{
			ItemSync.Moved(__instance, "HandlePickedUpToClipboard");
		}
	}
	internal static class LeaderboardGuard
	{
		public static bool Tainted { get; private set; }

		public static void Update()
		{
			if (Net.Active && !Tainted)
			{
				Tainted = true;
				Mod.Log.Msg("Leaderboard: co-op session active — this run won't be submitted to leaderboards");
			}
		}

		public static void OnMissionRuntimeStarted()
		{
			if (!Net.Active && Tainted)
			{
				Tainted = false;
				Mod.Log.Msg("Leaderboard: solo run — leaderboard submission back to the game's own setting");
			}
		}
	}
	[HarmonyPatch(typeof(LeaderboardManager), "get_OptOut")]
	internal static class Leaderboard_OptOut
	{
		private static void Postfix(ref bool __result)
		{
			if (!(!LeaderboardGuard.Tainted | __result))
			{
				PatchLog.Hit("LeaderboardManager.OptOut (forced on for co-op)");
				__result = true;
			}
		}
	}
	[HarmonyPatch(typeof(SteamLeaderboardScoreController), "SubmitScoreInternal")]
	internal static class Leaderboard_SteamSubmit
	{
		private static bool Prefix()
		{
			if (!LeaderboardGuard.Tainted)
			{
				return true;
			}
			Mod.Log.Msg("Leaderboard: skipped a Steam leaderboard submit (co-op run)");
			return false;
		}
	}
	[HarmonyPatch(typeof(MissionManager), "StartMissionRuntime")]
	internal static class Leaderboard_RunStart
	{
		private static void Postfix()
		{
			LeaderboardGuard.OnMissionRuntimeStarted();
			MissionSync.OnMissionRuntimeStarted();
		}
	}
	internal static class LogSaver
	{
		private const int Keep = 20;

		private static DateTime sessionStart;

		private static string role = "";

		private static string players = "";

		public static string Folder => Path.Combine(MelonEnvironment.UserDataDirectory, "NestCoop", "logs");

		public static void OnSessionStarted(Role r)
		{
			sessionStart = DateTime.Now;
			role = r.ToString().ToLowerInvariant();
			players = "";
		}

		public static void NotePlayers(IEnumerable<(int id, string name)> peers)
		{
			players = string.Join(", ", peers.Select(((int id, string name) p) => p.name));
		}

		public static void OnSessionEnded(string why)
		{
			if (!string.IsNullOrEmpty(role))
			{
				try
				{
					Save(why);
				}
				catch (Exception ex)
				{
					Mod.Log.Warning("LogSaver: couldn't save the log: " + ex.Message);
				}
				role = "";
			}
		}

		private static void Save(string why)
		{
			string path = Path.Combine(MelonEnvironment.MelonLoaderDirectory, "Latest.log");
			if (!File.Exists(path))
			{
				return;
			}
			Directory.CreateDirectory(Folder);
			string text;
			using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
			{
				using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
				text = streamReader.ReadToEnd();
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("==== NestCoop session log ====");
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(31, 2, stringBuilder2);
			handler.AppendLiteral("Saved:      ");
			handler.AppendFormatted(DateTime.Now, "yyyy-MM-dd HH:mm:ss");
			handler.AppendLiteral("  (session ended: ");
			handler.AppendFormatted(why);
			handler.AppendLiteral(")");
			stringBuilder3.AppendLine(ref handler);
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder4 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(19, 2, stringBuilder2);
			handler.AppendLiteral("NestCoop:   ");
			handler.AppendFormatted("0.9.10");
			handler.AppendLiteral("   key ");
			handler.AppendFormatted(VersionCheck.Key);
			stringBuilder4.AppendLine(ref handler);
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder5 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(25, 2, stringBuilder2);
			handler.AppendLiteral("Role:       ");
			handler.AppendFormatted(role);
			handler.AppendLiteral("   transport ");
			handler.AppendFormatted(Mod.TransportName.Value);
			stringBuilder5.AppendLine(ref handler);
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder6 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(12, 1, stringBuilder2);
			handler.AppendLiteral("Players:    ");
			handler.AppendFormatted((players.Length > 0) ? players : "(none connected at the end)");
			stringBuilder6.AppendLine(ref handler);
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder7 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(22, 3, stringBuilder2);
			handler.AppendLiteral("Session:    ");
			handler.AppendFormatted(sessionStart, "HH:mm:ss");
			handler.AppendLiteral(" – ");
			handler.AppendFormatted(DateTime.Now, "HH:mm:ss");
			handler.AppendLiteral(" (");
			handler.AppendFormatted((DateTime.Now - sessionStart).TotalMinutes, "0.#");
			handler.AppendLiteral(" min)");
			stringBuilder7.AppendLine(ref handler);
			stringBuilder.AppendLine("==== MelonLoader Latest.log ====");
			string text2 = $"{sessionStart:yyyy-MM-dd_HH-mm-ss}_{role}_v{"0.9.10"}.log";
			string text3 = Path.Combine(Folder, text2);
			File.WriteAllText(text3, stringBuilder?.ToString() + text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			Mod.Log.Msg("LogSaver: session log saved to " + text3);
			Overlay.Toast("Session log saved: UserData/NestCoop/logs/" + text2, 6f);
			foreach (FileInfo item in (from f in new DirectoryInfo(Folder).GetFiles("*.log")
				orderby f.CreationTimeUtc descending
				select f).Skip(20))
			{
				try
				{
					item.Delete();
				}
				catch
				{
				}
			}
		}
	}
	internal static class MissionGate
	{
		public static bool Allow(string what)
		{
			if (Net.Role != Role.Guest || Net.ApplyingRemote)
			{
				return true;
			}
			Mod.Log.Msg("MissionGate: blocked guest " + what + " (host decides missions)");
			Overlay.Toast("Only the host can change missions");
			return false;
		}

		public static bool AllowOrLeave(string what)
		{
			if (Net.Role != Role.Guest || Net.ApplyingRemote)
			{
				return true;
			}
			Mod.Log.Msg("MissionGate: guest " + what + " — leaving the co-op session first");
			Net.Stop("you left the mission", quiet: true);
			Overlay.Toast("You left the co-op session", 6f);
			return true;
		}
	}
	[HarmonyPatch(typeof(MissionManager), "StartOperation", new Type[]
	{
		typeof(OperationGraph),
		typeof(MissionGraph)
	})]
	internal static class MM_StartOperation2
	{
		private static bool Prefix()
		{
			if (!MissionGate.Allow("StartOperation"))
			{
				return false;
			}
			MissionSync.BeforeLocalMissionLoad();
			return true;
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.StartOperation(op, mission)");
			MissionSync.OnMissionManagerChanged("StartOperation");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "StartOperation", new Type[]
	{
		typeof(OperationGraph),
		typeof(MissionGraph),
		typeof(MissionSaveData)
	})]
	internal static class MM_StartOperation3
	{
		private static bool Prefix(MissionSaveData checkpoint)
		{
			if (!MissionGate.Allow("StartOperation"))
			{
				return false;
			}
			MissionSync.BeforeLocalMissionLoad();
			if (checkpoint != null)
			{
				MissionSync.NoteHostResuming("starting from a checkpoint");
			}
			return true;
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.StartOperation(op, mission, checkpoint)");
			MissionSync.OnMissionManagerChanged("StartOperation+checkpoint");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "ResumeOperation")]
	internal static class MM_ResumeOperation
	{
		private static bool Prefix()
		{
			if (!MissionGate.Allow("ResumeOperation"))
			{
				return false;
			}
			MissionSync.BeforeLocalMissionLoad();
			MissionSync.NoteHostResuming("resuming an operation");
			return true;
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.ResumeOperation");
			MissionSync.OnMissionManagerChanged("ResumeOperation");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "LoadMission")]
	internal static class MM_LoadMission_Sync
	{
		private static bool Prefix()
		{
			if (!MissionGate.Allow("LoadMission"))
			{
				return false;
			}
			MissionSync.BeforeLocalMissionLoad();
			return true;
		}

		private static void Postfix()
		{
			MissionSync.OnMissionManagerChanged("LoadMission");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "ReloadCurrentMission")]
	internal static class MM_ReloadCurrentMission
	{
		private static bool Prefix()
		{
			if (!MissionGate.Allow("ReloadCurrentMission"))
			{
				return false;
			}
			MissionSync.NoteHostResuming("reloading the mission");
			return true;
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.ReloadCurrentMission");
			MissionSync.OnMissionManagerChanged("ReloadCurrentMission");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "EnterBrowsingMap")]
	internal static class MM_EnterBrowsingMap
	{
		private static bool Prefix()
		{
			return MissionGate.Allow("EnterBrowsingMap");
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.EnterBrowsingMap");
			MissionSync.OnMissionManagerChanged("EnterBrowsingMap");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "ReturnToMap")]
	internal static class MM_ReturnToMap
	{
		private static bool Prefix()
		{
			return MissionGate.AllowOrLeave("ReturnToMap");
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.ReturnToMap");
			MissionSync.OnMissionManagerChanged("ReturnToMap");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "EndOperationAndReturnToMenu")]
	internal static class MM_EndOperationAndReturnToMenu
	{
		private static bool Prefix()
		{
			return MissionGate.AllowOrLeave("EndOperationAndReturnToMenu");
		}

		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.EndOperationAndReturnToMenu");
			MissionSync.OnMissionManagerChanged("EndOperationAndReturnToMenu");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "FinishMission")]
	internal static class MM_FinishMission_Sync
	{
		private static bool Prefix()
		{
			return MissionGate.Allow("FinishMission");
		}

		private static void Postfix()
		{
			if (!Net.ApplyingRemote)
			{
				MissionSync.OnLocalFinish();
			}
			MissionSync.OnMissionManagerChanged("FinishMission");
		}
	}
	[HarmonyPatch(typeof(MissionManager), "SetPhase")]
	internal static class MM_SetPhase
	{
		private static void Postfix()
		{
			PatchLog.Hit("MissionManager.SetPhase");
			MissionSync.OnMissionManagerChanged("SetPhase");
		}
	}
	[HarmonyPatch(typeof(FireMission), "GenerateMission")]
	internal static class FireMission_GenerateMission
	{
		private static void Prefix(FireMission __instance, out (bool, int, bool) __state)
		{
			MissionSync.BeforeGenerate(__instance, out (bool, int, bool) saved);
			__state = saved;
		}

		private static void Postfix(FireMission __instance, (bool, int, bool) __state)
		{
			PatchLog.Hit("FireMission.GenerateMission");
			MissionSync.AfterGenerate(__instance, __state);
		}
	}
	internal static class MissionSync
	{
		public enum EventKind : byte
		{
			Finish = 1,
			Complete,
			Failed
		}

		private readonly struct State : IEquatable<State>
		{
			public readonly GamePhase Phase;

			public readonly string Op;

			public readonly string Mission;

			public readonly int Seed;

			public State(GamePhase p, string op, string m, int seed)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Phase = p;
				Op = op;
				Mission = m;
				Seed = seed;
			}

			public bool Equals(State o)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (Phase == o.Phase && Op == o.Op && Mission == o.Mission)
				{
					return Seed == o.Seed;
				}
				return false;
			}

			public override string ToString()
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				return $"{Phase} op='{Op}' mission='{Mission}' seed={Seed}";
			}
		}

		private static State? lastSent;

		private static State? lastMissionActive;

		public static int PendingSeed;

		public static bool HasPendingSeed;

		private static readonly Random seedSource = new Random();

		private static int seedFrame = -1;

		private static bool hostResuming;

		public static bool WaitingForCheckpoint;

		public static void BeforeLocalMissionLoad()
		{
			if (!Net.ApplyingRemote && Net.Role == Role.Host && seedFrame != Time.frameCount)
			{
				seedFrame = Time.frameCount;
				PendingSeed = seedSource.Next(1, int.MaxValue);
				HasPendingSeed = true;
				if (Mod.DebugLog.Value)
				{
					Mod.Log.Msg($"MissionSync: picked seed {PendingSeed}");
				}
			}
		}

		public static void OnMissionManagerChanged(string why)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			State? state = Current();
			if (!state.HasValue)
			{
				return;
			}
			State value = state.Value;
			if ((int)value.Phase == 2 && string.IsNullOrEmpty(value.Mission))
			{
				if (Mod.DebugLog.Value)
				{
					Mod.Log.Msg($"MissionSync: {why} -> skipped transitional {value}");
				}
				return;
			}
			if ((int)value.Phase == 2)
			{
				lastMissionActive = value;
			}
			State? state2 = lastSent;
			if (!state2.HasValue || !state2.GetValueOrDefault().Equals(value))
			{
				lastSent = value;
				Mod.Log.Msg($"MissionSync: {why} -> {value}");
				if (Net.Role == Role.Host && Net.CanSend)
				{
					Net.Broadcast(WriteState(value), reliable: true);
				}
			}
		}

		public static void OnHostVerdict(EventKind kind, bool force)
		{
			if (Net.Role == Role.Host && Net.CanSend)
			{
				Net.Broadcast(Net.Write(MsgType.MissionEvent, delegate(BinaryWriter w)
				{
					w.Write((byte)kind);
					w.Write(force);
				}), reliable: true);
				Mod.Log.Msg($"MissionSync: sent {kind}");
			}
		}

		public static void OnLocalFinish()
		{
			if (Net.Role == Role.Host && Net.CanSend)
			{
				Net.Broadcast(Net.Write(MsgType.MissionEvent, delegate(BinaryWriter w)
				{
					w.Write((byte)1);
				}), reliable: true);
				Mod.Log.Msg("MissionSync: sent FinishMission");
			}
		}

		public static void SendSnapshot(int peer)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			State? state = Current();
			if (state.HasValue && ((int)state.Value.Phase != 2 || !Snapshot.SendTo(peer)))
			{
				Net.SendTo(peer, WriteState(state.Value), reliable: true);
				Mod.Log.Msg($"MissionSync: sent state to guest #{peer}: {state.Value}");
			}
		}

		private static State? Current()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			MissionManager instance = MissionManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			GamePhase currentPhase = instance.CurrentPhase;
			OperationGraph currentOperation = instance.CurrentOperation;
			string op = ((currentOperation != null) ? currentOperation.OperationID : null) ?? "";
			MissionGraph currentMission = instance.CurrentMission;
			return new State(currentPhase, op, ((currentMission != null) ? currentMission.MissionID : null) ?? "", HasPendingSeed ? PendingSeed : 0);
		}

		private static byte[] WriteState(State st)
		{
			return Net.Write(MsgType.MissionState, delegate(BinaryWriter w)
			{
				//IL_0007: 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_0059: Invalid comparison between Unknown and I4
				w.Write((byte)st.Phase);
				w.Write(st.Op);
				w.Write(st.Mission);
				w.Write(st.Seed);
				w.Write(hostResuming && (int)st.Phase == 2);
			});
		}

		public static void NoteHostResuming(string why)
		{
			if (Net.Role == Role.Host && !Net.ApplyingRemote)
			{
				hostResuming = true;
				Mod.Log.Msg("MissionSync: host " + why + " — guests will get the checkpoint");
			}
		}

		public static void OnMissionRuntimeStarted()
		{
			if (hostResuming)
			{
				hostResuming = false;
				Snapshot.BroadcastSoon();
			}
		}

		public static void ApplyCheckpoint(string opId, string missionId, int seed, MissionSaveData data)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Invalid comparison between Unknown and I4
			MissionManager instance = MissionManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			MissionGraph mission = FindMission(missionId);
			if ((Object)(object)mission == (Object)null)
			{
				Mod.Log.Error("MissionSync: mission '" + missionId + "' not found on this machine");
				return;
			}
			OperationGraph op = FindOperation(opId);
			PendingSeed = seed;
			HasPendingSeed = seed != 0;
			WaitingForCheckpoint = false;
			if ((int)instance.CurrentPhase == 2)
			{
				MissionGraph currentMission = instance.CurrentMission;
				if (((currentMission != null) ? currentMission.MissionID : null) == missionId)
				{
					goto IL_0118;
				}
			}
			if ((Object)(object)op != (Object)null)
			{
				OperationGraph currentOperation = instance.CurrentOperation;
				if (((currentOperation != null) ? currentOperation.OperationID : null) != opId)
				{
					Run($"StartOperation({opId}, {missionId}, host checkpoint)", delegate(MissionManager m)
					{
						m.StartOperation(op, mission, data);
					});
					return;
				}
			}
			goto IL_0118;
			IL_0118:
			Run("LoadMission(" + missionId + ", host checkpoint)", delegate(MissionManager m)
			{
				m.LoadMission(mission, true, data);
			});
		}

		public static void Handle(MsgType type, BinaryReader r)
		{
			switch (type)
			{
			case MsgType.MissionState:
			{
				State state = new State((GamePhase)r.ReadByte(), r.ReadString(), r.ReadString(), r.ReadInt32());
				bool flag = r.BaseStream.Position < r.BaseStream.Length && r.ReadBoolean();
				if (Net.Role != Role.Guest)
				{
					Mod.Log.Warning($"MissionSync: ignored mission state from a guest ({state})");
				}
				else if (flag)
				{
					WaitingForCheckpoint = true;
					Mod.Log.Msg("MissionSync: host is resuming " + state.Mission + "; waiting for its checkpoint");
					Overlay.Toast("Host is loading a checkpoint…");
				}
				else
				{
					Apply(state, "host");
				}
				break;
			}
			case MsgType.MissionEvent:
			{
				EventKind eventKind = (EventKind)r.ReadByte();
				bool force = r.BaseStream.Position < r.BaseStream.Length && r.ReadBoolean();
				if (Net.Role != Role.Guest)
				{
					break;
				}
				switch (eventKind)
				{
				case EventKind.Finish:
					Run("FinishMission", delegate(MissionManager mm)
					{
						mm.FinishMission();
					});
					break;
				case EventKind.Complete:
					Run("MarkMissionComplete", delegate(MissionManager mm)
					{
						mm.MarkMissionComplete(force);
					});
					break;
				case EventKind.Failed:
					Run("MarkMissionFailed", delegate(MissionManager mm)
					{
						mm.MarkMissionFailed(force);
					});
					break;
				}
				break;
			}
			}
		}

		private static void Apply(State st, string source)
		{
			//IL_0065: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected I4, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Invalid comparison between Unknown and I4
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			MissionManager instance = MissionManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				Mod.Log.Warning("MissionSync: no MissionManager yet");
				return;
			}
			Instance log = Mod.Log;
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(44, 4);
			defaultInterpolatedStringHandler.AppendLiteral("MissionSync: apply (");
			defaultInterpolatedStringHandler.AppendFormatted(source);
			defaultInterpolatedStringHandler.AppendLiteral(") ");
			defaultInterpolatedStringHandler.AppendFormatted(st);
			defaultInterpolatedStringHandler.AppendLiteral("; local is ");
			defaultInterpolatedStringHandler.AppendFormatted<GamePhase>(instance.CurrentPhase);
			defaultInterpolatedStringHandler.AppendLiteral(" mission='");
			MissionGraph currentMission = instance.CurrentMission;
			defaultInterpolatedStringHandler.AppendFormatted((currentMission != null) ? currentMission.MissionID : null);
			defaultInterpolatedStringHandler.AppendLiteral("'");
			log.Msg(defaultInterpolatedStringHandler.ToStringAndClear());
			GamePhase phase = st.Phase;
			switch ((int)phase)
			{
			case 0:
				if ((int)instance.CurrentPhase != 0)
				{
					Run("EndOperationAndReturnToMenu", delegate(MissionManager m)
					{
						m.EndOperationAndReturnToMenu();
					});
				}
				break;
			case 1:
				if ((int)instance.CurrentPhase == 2)
				{
					Run("ReturnToMap", delegate(MissionManager m)
					{
						m.ReturnToMap();
					});
				}
				else if ((int)instance.CurrentPhase == 0)
				{
					Run("EnterBrowsingMap", delegate(MissionManager m)
					{
						m.EnterBrowsingMap();
					});
				}
				break;
			case 2:
			{
				if ((int)instance.CurrentPhase == 2)
				{
					MissionGraph currentMission2 = instance.CurrentMission;
					if (((currentMission2 != null) ? currentMission2.MissionID : null) == st.Mission)
					{
						break;
					}
				}
				if (string.IsNullOrEmpty(st.Mission))
				{
					Mod.Log.Warning("MissionSync: MissionActive without a mission id; ignored");
					break;
				}
				MissionGraph mission = FindMission(st.Mission);
				if ((Object)(object)mission == (Object)null)
				{
					Mod.Log.Error("MissionSync: mission '" + st.Mission + "' not found on this machine");
					break;
				}
				OperationGraph op = FindOperation(st.Op);
				PendingSeed = st.Seed;
				HasPendingSeed = st.Seed != 0;
				if ((Object)(object)op != (Object)null)
				{
					OperationGraph currentOperation = instance.CurrentOperation;
					if (((currentOperation != null) ? currentOperation.OperationID : null) != st.Op)
					{
						Run($"StartOperation({st.Op}, {st.Mission})", delegate(MissionManager m)
						{
							m.StartOperation(op, mission);
						});
						break;
					}
				}
				Run("LoadMission(" + st.Mission + ")", delegate(MissionManager m)
				{
					m.LoadMission(mission, false, (MissionSaveData)null);
				});
				break;
			}
			}
		}

		private static void Run(string what, Action<MissionManager> action)
		{
			MissionManager instance = MissionManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			Mod.Log.Msg("MissionSync: -> " + what);
			Overlay.Toast("Host: " + what);
			Net.ApplyingRemote = true;
			try
			{
				action(instance);
			}
			catch (Exception value)
			{
				Mod.Log.Error($"MissionSync: {what} failed: {value}");
			}
			finally
			{
				Net.ApplyingRemote = false;
			}
		}

		private static MissionGraph FindMission(string id)
		{
			return FindAsset<MissionGraph>((Func<MissionGraph, bool>)((MissionGraph g) => g.MissionID == id));
		}

		private static OperationGraph FindOperation(string id)
		{
			if (!string.IsNullOrEmpty(id))
			{
				return FindAsset<OperationGraph>((Func<OperationGraph, bool>)((OperationGraph g) => g.OperationID == id));
			}
			return null;
		}

		private static T FindAsset<T>(Func<T, bool> match) where T : Object
		{
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<T>()))
			{
				T val = ((Il2CppObjectBase)item).TryCast<T>();
				if ((Object)(object)val != (Object)null && match(val))
				{
					return val;
				}
			}
			return default(T);
		}

		public static void BeforeGenerate(FireMission fm, out (bool useFixed, int fixedSeed, bool forced) saved)
		{
			saved = (useFixed: fm.useFixedSeed, fixedSeed: fm.fixedSeed, forced: false);
			if (HasPendingSeed && !fm.useFixedSeed)
			{
				fm.useFixedSeed = true;
				fm.fixedSeed = PendingSeed;
				saved.forced = true;
			}
		}

		public static void AfterGenerate(FireMission fm, (bool useFixed, int fixedSeed, bool forced) saved)
		{
			Mod.Log.Msg($"MissionSync: FireMission.GenerateMission seed={fm.seed} (forced={saved.forced}, designerFixed={saved.useFixed && !saved.forced})");
			if (saved.forced)
			{
				fm.useFixedSeed = saved.useFixed;
				fm.fixedSeed = saved.fixedSeed;
			}
		}

		public static void DebugReplay()
		{
			State? state = lastMissionActive;
			if (state.HasValue)
			{
				State valueOrDefault = state.GetValueOrDefault();
				Apply(valueOrDefault, "debug replay");
			}
			else
			{
				Mod.Log.Msg

UserLibs/LiteNetLib.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
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.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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Ruslan Pyrch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2026 Ruslan Pyrch")]
[assembly: AssemblyDescription("Lite reliable UDP library for .NET, Mono, and .NET Core")]
[assembly: AssemblyFileVersion("2.1.5")]
[assembly: AssemblyInformationalVersion("1.0.0+aa6d03e548b8d23308905431be6f2273a5c0f363")]
[assembly: AssemblyProduct("LiteNetLib")]
[assembly: AssemblyTitle("LiteNetLib")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/RevenantX/LiteNetLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.5.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
}
namespace LiteNetLib
{
	internal abstract class BaseChannel
	{
		protected readonly LiteNetPeer Peer;

		protected readonly Queue<NetPacket> OutgoingQueue = new Queue<NetPacket>(64);

		private int _isAddedToPeerChannelSendQueue;

		public int PacketsInQueue => OutgoingQueue.Count;

		protected BaseChannel(LiteNetPeer 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;
		}

		public abstract bool SendNextPackets();

		public abstract bool ProcessPacket(NetPacket packet);
	}
	internal enum ConnectionRequestResult
	{
		None,
		Accept,
		Reject,
		RejectForce
	}
	public class LiteConnectionRequest
	{
		private readonly LiteNetManager _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 LiteConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket, LiteNetManager listener)
		{
			InternalPacket = requestPacket;
			RemoteEndPoint = remoteEndPoint;
			_listener = listener;
		}

		public LiteNetPeer 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, ReadOnlySpan<byte>.Empty);
			}
			Result = ConnectionRequestResult.Reject;
			_listener.OnConnectionSolved(this, ReadOnlySpan<byte>.Empty);
			return null;
		}

		public LiteNetPeer Accept()
		{
			if (!TryActivate())
			{
				return null;
			}
			Result = ConnectionRequestResult.Accept;
			return _listener.OnConnectionSolved(this, ReadOnlySpan<byte>.Empty);
		}

		public void Reject(ReadOnlySpan<byte> rejectData, bool force)
		{
			if (TryActivate())
			{
				Result = (force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject);
				_listener.OnConnectionSolved(this, rejectData);
			}
		}

		public void Reject(byte[] rejectData, int start, int length, bool force)
		{
			Reject(new ReadOnlySpan<byte>(rejectData, start, length), force);
		}

		public void Reject(byte[] rejectData, int start, int length)
		{
			Reject(new ReadOnlySpan<byte>(rejectData, start, length), force: false);
		}

		public void RejectForce(byte[] rejectData, int start, int length)
		{
			Reject(new ReadOnlySpan<byte>(rejectData, start, length), force: true);
		}

		public void RejectForce()
		{
			Reject(ReadOnlySpan<byte>.Empty, force: true);
		}

		public void RejectForce(byte[] rejectData)
		{
			Reject(new ReadOnlySpan<byte>(rejectData), force: true);
		}

		public void RejectForce(NetDataWriter rejectData)
		{
			Reject(rejectData.AsReadOnlySpan(), force: true);
		}

		public void RejectForce(ReadOnlySpan<byte> rejectData)
		{
			Reject(rejectData, force: true);
		}

		public void Reject()
		{
			Reject(ReadOnlySpan<byte>.Empty, force: false);
		}

		public void Reject(byte[] rejectData)
		{
			Reject(new ReadOnlySpan<byte>(rejectData), force: false);
		}

		public void Reject(NetDataWriter rejectData)
		{
			Reject(rejectData.AsReadOnlySpan(), force: false);
		}

		public void Reject(ReadOnlySpan<byte> rejectData)
		{
			Reject(rejectData, force: false);
		}
	}
	public class ConnectionRequest : LiteConnectionRequest
	{
		internal ConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket, LiteNetManager listener)
			: base(remoteEndPoint, requestPacket, listener)
		{
		}

		public new NetPeer AcceptIfKey(string key)
		{
			return (NetPeer)base.AcceptIfKey(key);
		}

		public new NetPeer Accept()
		{
			return (NetPeer)base.Accept();
		}
	}
	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);

		void OnMessageDelivered(NetPeer peer, object userData)
		{
		}

		void OnNtpResponse(NtpPacket packet)
		{
		}

		void OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress)
		{
		}
	}
	public interface ILiteNetEventListener
	{
		void OnPeerConnected(LiteNetPeer peer);

		void OnPeerDisconnected(LiteNetPeer peer, DisconnectInfo disconnectInfo);

		void OnNetworkError(IPEndPoint endPoint, SocketError socketError)
		{
		}

		void OnNetworkReceive(LiteNetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod);

		void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
		{
		}

		void OnNetworkLatencyUpdate(LiteNetPeer peer, int latency)
		{
		}

		void OnConnectionRequest(LiteConnectionRequest request);

		void OnPeerAddressChanged(LiteNetPeer peer, IPEndPoint previousAddress)
		{
		}

		void OnMessageDelivered(LiteNetPeer peer, object userData)
		{
		}
	}
	public class EventBasedNetListener : INetEventListener
	{
		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)
		{
			this.PeerConnectedEvent?.Invoke(peer);
		}

		void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
		{
			this.PeerDisconnectedEvent?.Invoke(peer, disconnectInfo);
		}

		void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode)
		{
			this.NetworkErrorEvent?.Invoke(endPoint, socketErrorCode);
		}

		void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod)
		{
			this.NetworkReceiveEvent?.Invoke(peer, reader, channelNumber, deliveryMethod);
		}

		void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
		{
			this.NetworkReceiveUnconnectedEvent?.Invoke(remoteEndPoint, reader, messageType);
		}

		void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
		{
			this.NetworkLatencyUpdateEvent?.Invoke(peer, latency);
		}

		void INetEventListener.OnConnectionRequest(ConnectionRequest request)
		{
			this.ConnectionRequestEvent?.Invoke(request);
		}

		void INetEventListener.OnMessageDelivered(NetPeer peer, object userData)
		{
			this.DeliveryEvent?.Invoke(peer, userData);
		}

		void INetEventListener.OnNtpResponse(NtpPacket packet)
		{
			this.NtpResponseEvent?.Invoke(packet);
		}

		void INetEventListener.OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress)
		{
			this.PeerAddressChangedEvent?.Invoke(peer, previousAddress);
		}
	}
	public class EventBasedLiteNetListener : ILiteNetEventListener
	{
		public delegate void OnPeerConnected(LiteNetPeer peer);

		public delegate void OnPeerDisconnected(LiteNetPeer peer, DisconnectInfo disconnectInfo);

		public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError);

		public delegate void OnNetworkReceive(LiteNetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod);

		public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType);

		public delegate void OnNetworkLatencyUpdate(LiteNetPeer peer, int latency);

		public delegate void OnConnectionRequest(LiteConnectionRequest request);

		public delegate void OnDeliveryEvent(LiteNetPeer peer, object userData);

		public delegate void OnPeerAddressChangedEvent(LiteNetPeer 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 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 ClearPeerAddressChangedEvent()
		{
			this.PeerAddressChangedEvent = null;
		}

		void ILiteNetEventListener.OnPeerConnected(LiteNetPeer peer)
		{
			this.PeerConnectedEvent?.Invoke(peer);
		}

		void ILiteNetEventListener.OnPeerDisconnected(LiteNetPeer peer, DisconnectInfo disconnectInfo)
		{
			this.PeerDisconnectedEvent?.Invoke(peer, disconnectInfo);
		}

		void ILiteNetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode)
		{
			this.NetworkErrorEvent?.Invoke(endPoint, socketErrorCode);
		}

		void ILiteNetEventListener.OnNetworkReceive(LiteNetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
		{
			this.NetworkReceiveEvent?.Invoke(peer, reader, deliveryMethod);
		}

		void ILiteNetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
		{
			this.NetworkReceiveUnconnectedEvent?.Invoke(remoteEndPoint, reader, messageType);
		}

		void ILiteNetEventListener.OnNetworkLatencyUpdate(LiteNetPeer peer, int latency)
		{
			this.NetworkLatencyUpdateEvent?.Invoke(peer, latency);
		}

		void ILiteNetEventListener.OnConnectionRequest(LiteConnectionRequest request)
		{
			this.ConnectionRequestEvent?.Invoke(request);
		}

		void ILiteNetEventListener.OnMessageDelivered(LiteNetPeer peer, object userData)
		{
			this.DeliveryEvent?.Invoke(peer, userData);
		}

		void ILiteNetEventListener.OnPeerAddressChanged(LiteNetPeer peer, IPEndPoint previousAddress)
		{
			this.PeerAddressChangedEvent?.Invoke(peer, previousAddress);
		}
	}
	public 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;
		}

		internal static int GetProtocolId(NetPacket packet)
		{
			return BitConverter.ToInt32(packet.RawData, 1);
		}

		internal 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);
		}

		internal static NetPacket Make(ReadOnlySpan<byte> 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];
			}
			connectData.CopyTo(netPacket.RawData.AsSpan(18 + addressBytes.Size));
			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(LiteNetPeer 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;
		}
	}
	public class LiteNetManager : IEnumerable<LiteNetPeer>, IEnumerable
	{
		public struct NetPeerEnumerator<T> : IEnumerator<T>, IEnumerator, IDisposable where T : LiteNetPeer
		{
			private readonly T _initialPeer;

			private T _p;

			public T Current => _p;

			object IEnumerator.Current => _p;

			public NetPeerEnumerator(T p)
			{
				_initialPeer = p;
				_p = null;
			}

			public void Dispose()
			{
			}

			public bool MoveNext()
			{
				_p = ((_p == null) ? _initialPeer : ((T)_p.NextPeer));
				return _p != null;
			}

			public void Reset()
			{
				throw new NotSupportedException();
			}
		}

		private struct Slot
		{
			internal int HashCode;

			internal int Next;

			internal LiteNetPeer Value;
		}

		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 ILiteNetEventListener _netEventListener;

		private readonly Dictionary<IPEndPoint, LiteConnectionRequest> _requestsDict = new Dictionary<IPEndPoint, LiteConnectionRequest>();

		private long _connectedPeersCount;

		private readonly PacketLayerBase _extraPacketLayer;

		private int _lastPeerId;

		private ConcurrentQueue<int> _peerIds = new ConcurrentQueue<int>();

		private readonly object _eventLock = new object();

		private volatile bool _isRunning;

		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 ushort MaxFragmentsCount = ushort.MaxValue;

		private readonly Lazy<NatPunchModule> _natPunchModule;

		public bool AutoRecycle;

		public bool IPv6Enabled = true;

		public int MtuOverride;

		public bool MtuDiscovery;

		public bool UseNativeSockets;

		public bool DisconnectOnUnreachable;

		public bool AllowPeerAddressChange;

		public int MaxPacketPerManualReceive = 256;

		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 LiteNetPeer[] _peersArray = new LiteNetPeer[32];

		protected readonly ReaderWriterLockSlim _peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

		protected volatile LiteNetPeer _headPeer;

		private NetPacket _poolHead;

		private int _poolCount;

		private readonly object _poolLock = new object();

		public int PacketPoolSize = 1000;

		protected 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 int ReceivePollingTime = 50000;

		public NatPunchModule NatPunchModule => _natPunchModule.Value;

		public bool IsRunning => _isRunning;

		public int LocalPort { get; private set; }

		public LiteNetPeer FirstPeer => _headPeer;

		public int ConnectedPeersCount => (int)Interlocked.Read(in _connectedPeersCount);

		public int ExtraPacketSizeForLayer => _extraPacketLayer?.ExtraPacketSizeForLayer ?? 0;

		public int PoolCount => _poolCount;

		public short Ttl
		{
			get
			{
				return _udpSocketv4.Ttl;
			}
			internal set
			{
				_udpSocketv4.Ttl = value;
			}
		}

		public LiteNetManager(ILiteNetEventListener listener, PacketLayerBase extraPacketLayer = null)
		{
			_netEventListener = listener;
			_natPunchModule = new Lazy<NatPunchModule>(() => new NatPunchModule(this));
			_extraPacketLayer = extraPacketLayer;
		}

		internal void ConnectionLatencyUpdated(LiteNetPeer fromPeer, int latency)
		{
			CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, null, SocketError.Success, latency, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
		}

		internal void MessageDelivered(LiteNetPeer fromPeer, object userData)
		{
			CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, null, userData);
		}

		internal void DisconnectPeerForce(LiteNetPeer peer, DisconnectReason reason, SocketError socketErrorCode, NetPacket eventData)
		{
			DisconnectPeer(peer, reason, socketErrorCode, force: true, ReadOnlySpan<byte>.Empty, eventData);
		}

		private void DisconnectPeer(LiteNetPeer peer, DisconnectReason reason, SocketError socketErrorCode, bool force, ReadOnlySpan<byte> data, NetPacket eventData)
		{
			switch (peer.Shutdown(data, 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, LiteNetPeer peer = null, IPEndPoint remoteEndPoint = null, SocketError errorCode = SocketError.Success, int latency = 0, DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed, LiteConnectionRequest 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?.HeaderSize ?? 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;
			}
		}

		protected virtual 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 = new DisconnectInfo
				{
					Reason = evt.DisconnectReason,
					AdditionalData = evt.DataReader,
					SocketErrorCode = evt.ErrorCode
				};
				_netEventListener.OnPeerDisconnected(evt.Peer, disconnectInfo);
				break;
			}
			case NetEvent.EType.Receive:
				_netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, 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:
				_netEventListener.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)
				{
					_netEventListener.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;
			}
		}

		protected virtual void ProcessNtpRequests(float elapsedMilliseconds)
		{
		}

		private void UpdateLogic()
		{
			List<LiteNetPeer> list = new List<LiteNetPeer>();
			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 (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
					{
						if (liteNetPeer.ConnectionState == ConnectionState.Disconnected && liteNetPeer.TimeSinceLastPacket > (float)DisconnectTimeout)
						{
							list.Add(liteNetPeer);
						}
						else
						{
							liteNetPeer.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")]
		[Conditional("SIMULATE_NETWORK")]
		private void ProcessDelayedPackets()
		{
			_ = SimulateLatency;
		}

		public void ManualUpdate(float elapsedMilliseconds)
		{
			if (!_manualMode)
			{
				return;
			}
			for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
			{
				if (liteNetPeer.ConnectionState == ConnectionState.Disconnected && liteNetPeer.TimeSinceLastPacket > (float)DisconnectTimeout)
				{
					RemovePeer(liteNetPeer, enableWriteLock: false);
				}
				else
				{
					liteNetPeer.Update(elapsedMilliseconds);
				}
			}
			ProcessNtpRequests(elapsedMilliseconds);
		}

		protected virtual LiteNetPeer CreateOutgoingPeer(IPEndPoint remoteEndPoint, int id, byte connectNum, ReadOnlySpan<byte> connectData)
		{
			return new LiteNetPeer(this, remoteEndPoint, id, connectNum, connectData);
		}

		protected virtual LiteNetPeer CreateIncomingPeer(LiteConnectionRequest request, int id)
		{
			return new LiteNetPeer(this, request, id);
		}

		protected virtual LiteNetPeer CreateRejectPeer(IPEndPoint remoteEndPoint, int id)
		{
			return new LiteNetPeer(this, remoteEndPoint, id);
		}

		protected virtual LiteConnectionRequest CreateConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket)
		{
			return new LiteConnectionRequest(remoteEndPoint, requestPacket, this);
		}

		internal LiteNetPeer OnConnectionSolved(LiteConnectionRequest request, ReadOnlySpan<byte> rejectData)
		{
			LiteNetPeer actualValue = null;
			if (request.Result == ConnectionRequestResult.RejectForce)
			{
				if (!rejectData.IsEmpty)
				{
					NetPacket netPacket = PoolGetWithProperty(PacketProperty.Disconnect, rejectData.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
					{
						rejectData.CopyTo(netPacket.RawData.AsSpan(9));
					}
					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 = CreateRejectPeer(request.RemoteEndPoint, GetNextPeerId());
							actualValue.Reject(request.InternalPacket, rejectData);
							AddPeer(actualValue);
						}
						else
						{
							actualValue = CreateIncomingPeer(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, LiteNetPeer 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);
				}
			}
			LiteConnectionRequest value;
			lock (_requestsDict)
			{
				if (_requestsDict.TryGetValue(remoteEndPoint, out value))
				{
					value.UpdateRequest(connRequest);
					return;
				}
				value = CreateConnectionRequest(remoteEndPoint, connRequest);
				_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")]
		[Conditional("SIMULATE_NETWORK")]
		private void HandleSimulateLatency(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			_ = SimulateLatency;
		}

		[Conditional("DEBUG")]
		[Conditional("SIMULATE_NETWORK")]
		private void HandleSimulatePacketLoss()
		{
			if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100.0 < (double)SimulationPacketLossChance)
			{
				_dropPacket = true;
			}
		}

		internal virtual bool CustomMessageHandle(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			return false;
		}

		private void HandleMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			int size = packet.Size;
			if (EnableStatistics)
			{
				Statistics.IncrementPacketsReceived();
				Statistics.AddBytesReceived(size);
			}
			if (CustomMessageHandle(packet, remoteEndPoint))
			{
				return;
			}
			if (_extraPacketLayer != null)
			{
				_extraPacketLayer.ProcessInboundPacket(ref remoteEndPoint, ref packet.RawData, ref packet.Size);
				if (packet.Size == 0)
				{
					PoolRecycle(packet);
					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;
			}
			LiteNetPeer actualValue = remoteEndPoint as LiteNetPeer;
			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();
							LiteNetPeer liteNetPeer = _peersArray[netConnectAcceptPacket.PeerId];
							_peersLock.ExitUpgradeableReadLock();
							if (liteNetPeer != null && liteNetPeer.ConnectTime == netConnectAcceptPacket.ConnectionTime && liteNetPeer.ConnectionNum == netConnectAcceptPacket.ConnectionNumber)
							{
								if (liteNetPeer.ConnectionState == ConnectionState.Connected)
								{
									liteNetPeer.InitiateEndPointChange();
									CreateEvent(NetEvent.EType.PeerAddressChanged, liteNetPeer, 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, LiteNetPeer 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)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
				{
					liteNetPeer.Send(data, start, length, options);
				}
			}
			finally
			{
				_peersLock.ExitReadLock();
			}
		}

		public void SendToAll(NetDataWriter writer, DeliveryMethod options, LiteNetPeer excludePeer)
		{
			SendToAll(writer.Data, 0, writer.Length, options, excludePeer);
		}

		public void SendToAll(byte[] data, DeliveryMethod options, LiteNetPeer excludePeer)
		{
			SendToAll(data, 0, data.Length, options, excludePeer);
		}

		public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, LiteNetPeer excludePeer)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
				{
					if (liteNetPeer != excludePeer)
					{
						liteNetPeer.Send(data, start, length, options);
					}
				}
			}
			finally
			{
				_peersLock.ExitReadLock();
			}
		}

		public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options)
		{
			SendToAll(data, options, null);
		}

		public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options, LiteNetPeer excludePeer)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
				{
					if (liteNetPeer != excludePeer)
					{
						liteNetPeer.Send(data, 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)
		{
			return SendUnconnectedMessage(writer.Data, 0, writer.Length, NetUtils.MakeEndPoint(address, port));
		}

		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()
		{
			if (_manualMode)
			{
				if (_udpSocketv4 != null)
				{
					ManualReceive(_udpSocketv4, _bufferEndPointv4);
				}
				if (_udpSocketv6 != null && _udpSocketv6 != _udpSocketv4)
				{
					ManualReceive(_udpSocketv6, _bufferEndPointv6);
				}
			}
			else if (!UnsyncedEvents)
			{
				NetEvent netEvent;
				lock (_eventLock)
				{
					netEvent = _pendingEventHead;
					_pendingEventHead = null;
					_pendingEventTail = null;
				}
				while (netEvent != null)
				{
					NetEvent next = netEvent.Next;
					ProcessEvent(netEvent);
					netEvent = next;
				}
			}
		}

		public LiteNetPeer Connect(string address, int port, string key)
		{
			return Connect(address, port, NetDataWriter.FromString(key));
		}

		public LiteNetPeer 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 LiteNetPeer Connect(IPEndPoint target, string key)
		{
			return Connect(target, NetDataWriter.FromString(key));
		}

		public LiteNetPeer 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 = CreateOutgoingPeer(target, GetNextPeerId(), connectNum, connectionData.AsReadOnlySpan());
				AddPeer(actualValue);
				return actualValue;
			}
		}

		public LiteNetPeer Connect(IPEndPoint target, ReadOnlySpan<byte> 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 = CreateOutgoingPeer(target, GetNextPeerId(), connectNum, connectionData);
				AddPeer(actualValue);
				return actualValue;
			}
		}

		public void Stop()
		{
			Stop(sendDisconnectMessages: true);
		}

		public void Stop(bool sendDisconnectMessages)
		{
			if (_isRunning)
			{
				bool simulateLatency = SimulateLatency;
				SimulateLatency = false;
				for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
				{
					liteNetPeer.Shutdown(ReadOnlySpan<byte>.Empty, !sendDisconnectMessages);
				}
				CloseSocket();
				SimulateLatency = simulateLatency;
				_updateTriggerEvent.Set();
				if (!_manualMode)
				{
					_logicThread.Join();
					_logicThread = null;
				}
				ClearPeerSet();
				_peerIds = new ConcurrentQueue<int>();
				_lastPeerId = 0;
				_connectedPeersCount = 0L;
				_pendingEventHead = null;
				_pendingEventTail = null;
			}
		}

		public int GetPeersCount(ConnectionState peerState)
		{
			int num = 0;
			_peersLock.EnterReadLock();
			for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
			{
				if ((liteNetPeer.ConnectionState & peerState) != 0)
				{
					num++;
				}
			}
			_peersLock.ExitReadLock();
			return num;
		}

		public void GetPeers(List<LiteNetPeer> peers, ConnectionState peerState)
		{
			peers.Clear();
			_peersLock.EnterReadLock();
			for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
			{
				if ((liteNetPeer.ConnectionState & peerState) != 0)
				{
					peers.Add(liteNetPeer);
				}
			}
			_peersLock.ExitReadLock();
		}

		public void GetConnectedPeers(List<LiteNetPeer> peers)
		{
			GetPeers(peers, ConnectionState.Connected);
		}

		public void DisconnectAll()
		{
			DisconnectAll(ReadOnlySpan<byte>.Empty);
		}

		public void DisconnectAll(byte[] data, int start, int count)
		{
			DisconnectAll(new ReadOnlySpan<byte>(data, start, count));
		}

		public void DisconnectAll(ReadOnlySpan<byte> data)
		{
			_peersLock.EnterReadLock();
			for (LiteNetPeer liteNetPeer = _headPeer; liteNetPeer != null; liteNetPeer = liteNetPeer.NextPeer)
			{
				DisconnectPeer(liteNetPeer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, null);
			}
			_peersLock.ExitReadLock();
		}

		public void DisconnectPeerForce(LiteNetPeer peer)
		{
			DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, null);
		}

		public void DisconnectPeer(LiteNetPeer peer)
		{
			DisconnectPeer(peer, ReadOnlySpan<byte>.Empty);
		}

		public void DisconnectPeer(LiteNetPeer peer, byte[] data)
		{
			DisconnectPeer(peer, new ReadOnlySpan<byte>(data));
		}

		public void DisconnectPeer(LiteNetPeer peer, NetDataWriter writer)
		{
			DisconnectPeer(peer, writer.AsReadOnlySpan());
		}

		public void DisconnectPeer(LiteNetPeer peer, byte[] data, int start, int count)
		{
			DisconnectPeer(peer, new ReadOnlySpan<byte>(data, start, count));
		}

		public void DisconnectPeer(LiteNetPeer peer, ReadOnlySpan<byte> data)
		{
			DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, null);
		}

		public NetPeerEnumerator<LiteNetPeer> GetEnumerator()
		{
			return new NetPeerEnumerator<LiteNetPeer>(_headPeer);
		}

		IEnumerator<LiteNetPeer> IEnumerable<LiteNetPeer>.GetEnumerator()
		{
			return new NetPeerEnumerator<LiteNetPeer>(_headPeer);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new NetPeerEnumerator<LiteNetPeer>(_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 ((candidate & 1) != 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 LiteNetPeer[32];
			_peersLock.ExitWriteLock();
		}

		protected bool ContainsPeer(LiteNetPeer 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 LiteNetPeer GetPeerById(int id)
		{
			if (id < 0 || id >= _peersArray.Length)
			{
				return null;
			}
			return _peersArray[id];
		}

		public bool TryGetPeerById(int id, out LiteNetPeer peer)
		{
			peer = GetPeerById(id);
			return peer != null;
		}

		private void AddPeer(LiteNetPeer 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(LiteNetPeer 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();
			}
		}

		protected bool RemovePeerFromSet(LiteNetPeer 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 LiteNetPeer 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 LiteNetPeer 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((object?)saddr))
					{
						actualValue = _slots[num2].Value;
						_peersLock.ExitReadLock();
						return true;
					}
				}
				_peersLock.ExitReadLock();
			}
			actualValue = null;
			return false;
		}

		protected bool AddPeerToSet(LiteNetPeer 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 LiteNetManager()
		{
			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: {(int)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)
		{
			try
			{
				int num = MaxPacketPerManualReceive;
				while ((num > 0 || MaxPacketPerManualReceive == 0) && (socket.Available != 0 || socket.Poll(0, SelectMode.SelectRead)))
				{
					ReceiveFrom(socket, ref bufferEndPoint);
					if (MaxPacketPerManualReceive > 0)
					{
						num--;
					}
				}
			}
			catch (SocketException ex)
			{
				ProcessError(ex);
			}
			catch (ObjectDisposedException)
			{
			}
			catch (Exception ex3)
			{
				NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex3);
			}
		}

		private void NativeReceiveLogic()
		{
			IntPtr handle = _udpSocketv4.Handle;
			IntPtr s = _udpSocketv6?.Handle ?? IntPtr.Zero;
			byte[] address = new byte[16];
			byte[] address2 = 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, address))
						{
							break;
						}
						continue;
					}
					bool flag = false;
					if (udpSocketv.Available != 0 || list.Contains(udpSocketv))
					{
						if (!NativeReceiveFrom(handle, address))
						{
							break;
						}
						flag = true;
					}
					if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2))
					{
						if (!NativeReceiveFrom(s, address2))
						{
							break;
						}
						flag = true;
					}
					list.Clear();
					if (!flag)
					{
						list.Add(udpSocketv);
						list.Add(udpSocketv2);
						Socket.Select(list, null, null, ReceivePollingTime);
					}
				}
				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 socketHandle, byte[] array)
			{
				int socketAddressSize = array.Length;
				packet.Size = NativeSocket.RecvFrom(socketHandle, packet.RawData, NetConstants.MaxPacketSize, array, ref socketAddressSize);
				if (packet.Size == 0)
				{
					return true;
				}
				if (packet.Size == -1)
				{
					return !ProcessError(new SocketException((int)NativeSocket.GetSocketError()));
				}
				short num = (short)((array[1] << 8) | array[0]);
				tempEndPoint.Port = (ushort)((array[2] << 8) | array[3]);
				if ((NativeSocket.UnixMode && num == NativeSocket.AF_INET6) || (!NativeSocket.UnixMode && num == 23))
				{
					uint num2 = (uint)((array[27] << 24) + (array[26] << 16) + (array[25] << 8) + array[24]);
					tempEndPoint.Address = new IPAddress(new ReadOnlySpan<byte>(array, 8, 16), num2);
				}
				else
				{
					long newAddress = (uint)((array[4] & 0xFF) | ((array[5] << 8) & 0xFF00) | ((array[6] << 16) & 0xFF0000) | (array[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 int 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);
			return netPacket.Size;
		}

		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(ReceivePollingTime, 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, ReceivePollingTime);
					}
				}
				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 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;
			}
			int result = SendRawCore(message, start, length, remoteEndPoint);
			if (netPacket != null)
			{
				PoolRecycle(netPacket);
			}
			return result;
		}

		internal unsafe int SendRawCore(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
		{
			if (!_isRunning)
			{
				return 0;
			}
			Socket socket = _udpSocketv4;
			if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
			{
				socket = _udpSocketv6;
				if (socket == null)
				{
					return 0;
				}
			}
			int num;
			try
			{
				if (UseNativeSockets && remoteEndPoint is LiteNetPeer liteNetPeer)
				{
					fixed (byte* pinnedBuffer = &message[start])
					{
						num = NativeSocket.SendTo(socket.Handle, pinnedBuffer, length, liteNetPeer.NativeAddress, liteNetPeer.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 LiteNetPeer 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 arg)
			{
				NetDebug.WriteError($"[S] {arg}");
				return 0;
			}
			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 arg)
			{
				NetDebug.WriteError($"[S][MCAST] {arg}");
				return flag;
			}
			finally
			{
				PoolRecycle(netPacket);
			}
			return flag || flag2;
		}

		private void CloseSocket()
		{
			_isRunning = false;
			if (_receiveThread != null && _receiveThread != Thread.CurrentThread)
			{
				_receiveThread.Join();
			}
			_receiveThread = null;
			_udpSocketv4?.Close();
			_udpSocketv6?.Close();
			_udpSocketv4 = null;
			_udpSocketv6 = null;
		}
	}
	[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 LiteNetPeer : IPEndPoint
	{
		private sealed class IncomingFragments
		{
			public readonly NetPacket[] Fragments;

			public readonly ushort TotalFragments;

			public readonly byte ChannelId;

			public int ReceivedCount;

			public int TotalSize;

			public IncomingFragments(ushort totalFragments, byte channelId)
			{
				TotalFragments = totalFragments;
				ChannelId = channelId;
				Fragments = new NetPacket[totalFragments];
			}

			public void RecycleAll(LiteNetManager netManager)
			{
				for (int i = 0; i < Fragments.Length; i++)
				{
					NetPacket netPacket = Fragments[i];
					if (netPacket != null)
					{
						netManager.PoolRecycle(netPacket);
						Fragments[i] = null;
					}
				}
			}
		}

		private int _rtt;

		private int _avgRtt;

		private int _rttCount;

		private float _resendDelay = 27f;

		private float _pingSendTimer;

		private float _rttResetTimer;

		private readonly Stopwatch _pingTimer = new Stopwatch();

		private float _timeSinceLastPacket;

		private long _remoteDelta;

		private readonly object _shutdownLock = new object();

		internal volatile LiteNetPeer NextPeer;

		internal LiteNetPeer PrevPeer;

		private NetPacket[] _unreliableSecondQueue;

		private NetPacket[] _unreliableChannel;

		private int _unreliablePendingCount;

		private readonly object _unreliableChannelLock = new object();

		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 LiteNetManager NetManager;

		public readonly int Id;

		public float ResendFixedDelay = 25f;

		public float ResendRttMultiplier = 2.1f;

		public object Tag;

		public readonly NetStatistics Statistics;

		private SocketAddress _cachedSocketAddr;

		private int _cachedHashCode;

		private ReliableChannel _reliableChannel;

		private ReliableChannel _reliableUnorderedChannel;

		private SequencedChannel _sequencedChannel;

		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 float ResendDelay => _resendDelay;

		protected virtual int ChannelsCount => 1;

		public override SocketAddress Serialize()
		{
			return _cachedSocketAddr;
		}

		public override int GetHashCode()
		{
			return _cachedHashCode;
		}

		internal LiteNetPeer(LiteNetManager 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>();
		}

		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;
			_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();
		}

		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(bool ordered)
		{
			return (ordered ? _reliableChannel : _reliableUnorderedChannel)?.PacketsInQueue ?? 0;
		}

		public PooledPacket CreatePacketFromPool(DeliveryMethod deliveryMethod)
		{
			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)deliveryMethod);
		}

		public void SendPooledPacket(PooledPacket packet, int userDataSize)
		{
			if (_connectionState != ConnectionState.Connected)
			{
				return;
			}
			packet._packet.Size = packet.UserDataOffset + userDataSize;
			if (packet._packet.Property == PacketProperty.Channeled)
			{
				CreateChannel(packet._channelNumber).AddToQueue(packet._packet);
				return;
			}
			lock (_unreliableChannelLock)
			{
				if (_unreliablePendingCount == _unreliableChannel.Length)
				{
					Array.Resize(ref _unreliableChannel, _unreliablePendingCount * 2);
				}
				_unreliableChannel[_unreliablePendingCount++] = packet._packet;
			}
		}

		internal virtual BaseChannel CreateChannel(byte channelNumber)
		{
			switch ((DeliveryMethod)channelNumber)
			{
			case DeliveryMethod.ReliableOrdered:
			case DeliveryMethod.ReliableSequenced:
				return _reliableChannel ?? (_reliableChannel = new ReliableChannel(this, ordered: true, 2));
			case DeliveryMethod.ReliableUnordered:
				return _reliableUnorderedChannel ?? (_reliableUnorderedChannel = new ReliableChannel(this, ordered: false, channelNumber));
			case DeliveryMethod.Sequenced:
				return _sequencedChannel ?? (_sequencedChannel = new SequencedChannel(this, reliable: true, channelNumber));
			default:
				throw new Exception("Invalid channel type");
			}
		}

		internal LiteNetPeer(LiteNetManager netManager, IPEndPoint remoteEndPoint, int id, byte connectNum, ReadOnlySpan<byte> connectData)
			: this(netManager, remoteEndPoint, id)
		{
			_connectTime = DateTime.UtcNow.Ticks;
			_connectionState = ConnectionState.Outgoing;
			ConnectionNum = connectNum;
			_connectRequestPacket = NetConnectRequestPacket.Make(connectData, remoteEndPoint.Serialize(), _connectTime, id);
			_connectRequestPacket.ConnectionNumber = connectNum;
			NetManager.SendRaw(_connectRequestPacket, this);
		}

		internal LiteNetPeer(LiteNetManager netManager, LiteConnectionRequest request, int id)
			: this(netManager, request.RemoteEndPoint, id)
		{
			_connectTime = request.InternalPacket.ConnectionTime;
			ConnectionNum = request.InternalPacket.ConnectionNumber;
			RemoteId = request.InternalPacket.PeerId;
			_connectAcceptPacket = NetConnectAcceptPacket.Make(_connectTime, ConnectionNum, id);
			_connectionState = ConnectionState.Connected;
			NetManager.SendRaw(_connectAcceptPacket, this);
		}

		internal void Reject(NetConnectRequestPacket requestData, ReadOnlySpan<byte> data)
		{
			_connectTime = requestData.ConnectionTime;
			_connectNum = requestData.ConnectionNumber;
			Shutdown(data, force: false);
		}

		internal bool ProcessConnectAccept(NetConnectAcceptPacket packet)
		{
			if (_connectionState != ConnectionState.Outgoing)
			{
				return false;
			}
			if (packet.ConnectionTime != _connectTime)
			{
				return false;
			}
			ConnectionNum = packet.ConnectionNumber;
			RemoteId = packet.PeerId;
			Interlocked.Exchange(ref _timeSinceLastPacket, 0f);
			_connectionState = ConnectionState.Connected;
			return true;
		}

		public int GetMaxSinglePacketSize(DeliveryMethod options)
		{
			return _mtu - NetPacket.GetHeaderSize((options != DeliveryMethod.Unreliable) ? PacketProperty.Channeled : PacketProperty.Unreliable);
		}

		public void SendWithDeliveryEvent(byte[] data, DeliveryMethod deliveryMethod, object userData)
		{
			if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
			{
				throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
			}
			SendInternal(new ReadOnlySpan<byte>(data, 0, data.Length), 0, deliveryMethod, userData);
		}

		public void SendWithDeliveryEvent(byte[] data, int start, int length, DeliveryMethod deliveryMethod, object userData)
		{
			if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
			{
				throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
			}
			SendInternal(new ReadOnlySpan<byte>(data, start, length), 0, deliveryMethod, userData);
		}

		public void SendWithDeliveryEvent(NetDataWriter dataWriter, DeliveryMethod deliveryMethod, object userData)
		{
			if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
			{
				throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
			}
			SendInternal(dataWriter.AsReadOnlySpan(), 0, deliveryMethod, userData);
		}

		public void Send(byte[] data, DeliveryMethod deliveryMethod)
		{
			SendInternal(new ReadOnlySpan<byte>(data, 0, data.Length), 0, deliveryMethod, null);
		}

		public void Send(NetDataWriter dataWriter, DeliveryMethod deliveryMethod)
		{
			SendInternal(dataWriter.AsReadOnlySpan(), 0, deliveryMethod, null);
		}

		public void Send(byte[] data, int start, int length, DeliveryMethod options)
		{
			SendInternal(new ReadOnlySpan<byte>(data, start, length), 0, options, null);
		}

		public void SendWithDeliveryEvent(ReadOnlySpan<byte> data, DeliveryMethod deliveryMethod, object userData)
		{
			if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
			{
				throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
			}
			SendInternal(data, 0, deliveryMethod, userData);
		}

		public void Send(ReadOnlySpan<byte> data, DeliveryMethod deliveryMethod)
		{
			SendInternal(data, 0, deliveryMethod, null);
		}

		protected void SendInternal(ReadOnlySpan<byte> data, byte channelNumber, DeliveryMethod deliveryMethod, object userData)
		{
			if (_connectionState != ConnectionState.Connected || channelNumber >= ChannelsCount)
			{
				return;
			}
			BaseChannel baseChannel = null;
			PacketProperty property;
			if (deliveryMethod == DeliveryMethod.Unreliable)
			{
				property = PacketProperty.Unreliable;
			}
			else
			{
				property = PacketProperty.Channeled;
				baseChannel = CreateChannel((byte)((uint)(channelNumber * 4) + (uint)deliveryMethod));
			}
			int headerSize = NetPacket.GetHeaderSize(property);
			int mtu = _mtu;
			int num = data.Length;
			if (num + headerSize > mtu)
			{
				if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
				{
					throw new TooBigPacketException("Unreliable or ReliableSequenced packet size exceeded maximum of " + (mtu - headerSize) + " bytes, Check allowed size by GetMaxSinglePacketSize()");
				}
				int num2 = mtu - headerSize - 6;
				int num3 = num / num2 + ((num % num2 != 0) ? 1 : 0);
				if (num3 > NetManager.MaxFragmentsCount)
				{
					throw new TooBigPacketException("Data was split in " + num3 + " fragments, which exceeds " + NetManager.MaxFragmentsCount);
				}
				ushort fragmentId = (ushort)Interlocked.Increment(ref _fragmentId);
				for (ushort num4 = 0; num4 < num3; num4++)
				{
					int num5 = ((num > num2) ? num2 : num);
					NetPacket netPacket = NetManager.PoolGetPacket(headerSize + num5 + 6);
					netPacket.Property = property;
					netPacket.UserData = userData;
					netPacket.FragmentId = fragmentId;
					netPacket.FragmentPart = num4;
					netPacket.FragmentsTotal = (ushort)num3;
					netPacket.MarkFragmented();
					data.Slice(num4 * num2, num5).CopyTo(new Span<byte>(netPacket.RawData, 10, num5));
					baseChannel.AddToQueue(netPacket);
					num -= num5;
				}
				return;
			}
			NetPacket netPacket2 = NetManager.PoolGetPacket(headerSize + num);
			netPacket2.Property = property;
			data.CopyTo(new Span<byte>(netPacket2.RawData, headerSize, num));
			netPacket2.UserData = userData;
			if (baseChannel == null)
			{
				lock (_unreliableChannelLock)
				{
					if (_unreliablePendingCount == _unreliableChannel.Length)
					{
						Array.Resize(ref _unreliableChannel, _unreliablePendingCount * 2);
					}
					_unreliableChannel[_unreliablePendingCount++] = netPacket2;
					return;
				}
			}
			baseChannel.AddToQueue(netPacket2);
		}

		public void Disconnect(byte[] data)
		{
			NetManager.DisconnectPeer(this, data);
		}

		public void Disconnect(NetDataWriter writer)
		{
			NetManager.DisconnectPeer(this, writer);
		}

		public void Disconnect(byte[] data, int start, int count)
		{
			NetManager.DisconnectPeer(this, data, start, count);
		}

		public void Disconnect(ReadOnlySpan<byte> data)
		{
			NetManager.DisconnectPeer(this, data);
		}

		public void Disconnect()
		{
			NetManager.DisconnectPeer(this);
		}

		internal DisconnectResult ProcessDisconnect(NetPacket packet)
		{
			if ((_connectionState == ConnectionState.Connected || _connectionState == ConnectionState.Outgoing) && packet.Size >= 9 && BitConverter.ToInt64(packet.RawData, 1) == _connectTime && packet.ConnectionNumber == _connectNum)
			{
				if (_connectionState != ConnectionState.Connected)
				{
					return DisconnectResult.Reject;
				}
				return DisconnectResult.Disconnect;
			}
			return DisconnectResult.None;
		}

		internal virtual void AddToReliableChannelSendQueue(BaseChannel channel)
		{
		}

		internal ShutdownResult Shutdown(ReadOnlySpan<byte> data, bool force)
		{
			lock (_shutdownLock)
			{
				if (_connectionState == ConnectionState.Disconnected || _connectionState == ConnectionState.ShutdownRequested)
				{
					return ShutdownResult.None;
				}
				ShutdownResult result = ((_connectionState != ConnectionState.Connected) ? ShutdownResult.Success : ShutdownResult.WasConnected);
				if (force)
				{
					_connectionState = ConnectionState.Disconnected;
					return result;
				}
				Interlocked.Exchange(ref _timeSinceLastPacket, 0f);
				_shutdownPacket = new NetPacket(PacketProperty.Disconnect, data.Length)
				{
					ConnectionNumber = _connectNum
				};
				FastBitConverter.GetBytes(_shutdownPacket.RawData, 1, _connectTime);
				if (_shutdownPacket.Size >= _mtu)
				{
					NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU - 8!");
				}
				else if (!data.IsEmpty)
				{
					data.CopyTo(_shutdownPacket.RawData.AsSpan(9));
				}
				_connectionState = ConnectionState.ShutdownRequested;
				NetManager.SendRaw(_shutdownPacket, this);
				return result;
			}
		}

		private void UpdateRoundTripTime(int roundTripTime)
		{
			_rtt += roundTripTime;
			_rttCount++;
			_avgRtt = _rtt / _rttCount;
			_resendDelay = ResendFixedDelay + (float)_avgRtt * ResendRttMultiplier;
		}

		internal void AddReliablePacket(DeliveryMethod method, NetPacket p)
		{
			ushort packetFragId;
			IncomingFragments incomingFragments;
			NetPacket resultingPacket;
			if (p.IsFragmented)
			{
				if (p.FragmentsTotal == 0 || p.FragmentsTotal > NetManager.MaxFragmentsCount)
				{
					NetManager.PoolRecycle(p);
					NetDebug.WriteError($"Invalid FragmentsTotal: {p.FragmentsTotal}");
					return;
				}
				if (p.FragmentPart >= p.FragmentsTotal)
				{
					NetManager.PoolRecycle(p);
					NetDebug.WriteError($"FragmentPart {p.FragmentPart} >= FragmentsTotal {p.FragmentsTotal}");
					return;
				}
				packetFragId = p.FragmentId;
				byte channelId = p.ChannelId;
				if (!_holdedFragments.TryGetValue(packetFragId, out incomingFragments))
				{
					if (_holdedFragments.Count >= 32 * ChannelsCount * 2)
					{
						NetManager.PoolRecycle(p);
						return;
					}
					incomingFragments = new IncomingFragments(p.FragmentsTotal, p.ChannelId);
					_holdedFragments.Add(packetFragId, incomingFragments);
				}
				else if (p.FragmentsTotal != incomingFragments.TotalFragments || p.ChannelId != incomingFragments.ChannelId)
				{
					NetManager.PoolRecycle(p);
					NetDebug.WriteError("Fragment metadata mismatch");
					return;
				}
				NetPacket[] fragments = incomingFragments.Fragments;
				if (fragments[p.FragmentPart] != null)
				{
					NetManager.PoolRecycle(p);
					NetDebug.WriteError("Invalid fragment packet");
					return;
				}
				fragments[p.FragmentPart] = p;
				incomingFragments.ReceivedCount++;
				incomingFragments.TotalSize += p.Size - 10;
				if (incomingFragments.ReceivedCount != incomingFragments.TotalFragments)
				{
					return;
				}
				resultingPacket = NetManager.PoolGetPacket(incomingFragments.TotalSize);
				int num = 0;
				for (ushort num2 = 0; num2 < incomingFragments.TotalFragments; num2++)
				{
					NetPacket netPacket = fragments[num2];
					if (netPacket == null)
					{
						AbortReassembly($"Fragment {num2} missing during reassembly");
						return;
					}
					if (netPacket.Size > netPacket.RawData.Length)
					{
						AbortReassembly($"Fragment error size: {netPacket.Size} > fragment.RawData.Length: {netPacket.RawData.Length}");
						return;
					}
					int num3 = netPacket.Size - 10;
					if (num + num3 > resultingPacket.RawData.Length)
					{
						AbortReassembly($"Fragment error pos: {num + num3} >= resultPacketSize: {resultingPacket.RawData.Length}");
						return;
					}
					Buffer.BlockCopy(netPacket.RawData, 10, resultingPacket.RawData, num, num3);
					num += num3;
					NetManager.PoolRecycle(netPacket);
					fragments[num2] = null;
				}
				_holdedFragments.Remove(packetFragId);
				NetManager.CreateReceiveEvent(resultingPacket, method, (byte)(channelId / 4), 0, this);
			}
			else
			{
				NetManager.CreateReceiveEvent(p, method, (byte)(p.ChannelId / 4), 4, this);
			}
			void AbortReassembly(string error)
			{
				_holdedFragments.Remove(packetFragId);
				incomingFragments.RecycleAll(NetManager);
				NetManager.PoolRecycle(resultingPacket);
				NetDebug.WriteError(error);
			}
		}

		private void ProcessMtuPacket(NetPacket packet)
		{
			if (packet.Size < NetConstants.PossibleMtu[0])
			{
				return;
			}
			int num = BitConverter.ToInt32(packet.RawData, 1);
			int num2 = BitConverter.ToInt32(packet.RawData, packet.Size - 4);
			if (num != packet.Size || num != num2 || num > NetConstants.MaxPacketSize)
			{
				NetDebug.WriteError($"[MTU] Broken packet. RMTU {num}, EMTU {num2}, PSIZE {packet.Size}");
			}
			else if (packet.Property == PacketProperty.MtuCheck)
			{
				_mtuCheckAttempts = 0;
				packet.Property = PacketProperty.MtuOk;
				NetManager.SendRawAndRecycle(packet, this);
			}
			else if (num > _mtu && !_finishMtu && num == NetConstants.PossibleMtu[_mtuIdx + 1] - NetManager.ExtraPacketSizeForLayer)
			{
				lock (_mtuMutex)
				{
					SetMtu(_mtuIdx + 1);
				}
				if (_mtuIdx == NetConstants.PossibleMtu.Length - 1)
				{
					_finishMtu = true;
				}
				NetManager.PoolRecycle(packet);
			}
		}

		private void UpdateMtuLogic(float deltaTime)
		{
			if (_finishMtu)
			{
				return;
			}
			_mtuCheckTimer += deltaTime;
			if (_mtuCheckTimer < 1000f)
			{
				return;
			}
			_mtuCheckTimer = 0f;
			_mtuCheckAttempts++;
			if (_mtuCheckAttempts >= 4)
			{
				_finishMtu = true;
				return;
			}
			lock (_mtuMutex)
			{
				if (_mtuIdx < NetConstants.PossibleMtu.Length - 1)
				{
					int num = NetConstants.PossibleMtu[_mtuIdx + 1] - NetManager.ExtraPacketSizeForLayer;
					NetPacket netPacket = NetManager.PoolGetPacket(num);
					netPacket.Property = PacketProperty.MtuCheck;
					FastBitConverter.GetBytes(netPacket.RawData, 1, num);
					FastBitConverter.GetBytes(netPacket.RawData, netPacket.Size - 4, num);
					if (NetManager.SendRawAndRecycle(netPacket, this) <= 0)
					{
						_finishMtu = true;
					}
				}
			}
		}

		internal ConnectRequestResult ProcessConnectRequest(NetConnectRequestPacket connRequest)
		{
			switch (_connectionState)
			{
			case ConnectionState.Outgoing:
			{
				if (connRequest.ConnectionTime < _connectTime)
				{
					return ConnectRequestResult.P2PLose;
				}
				if (connRequest.ConnectionTime != _connectTime)
				{
					break;
				}
				byte[] targetAddress = connRequest.TargetAddress;
				for (int num = _cachedSocketAddr.Size - 1; num >= 0; num--)
				{
					byte b = _cachedSocketAddr[num];
					if (b != targetAddress[num] && b < targetAddress[num])
					{
						return ConnectRequestResult.P2PLose;
					}
				}
				break;
			}
			case ConnectionState.Connected:
				if (connRequest.ConnectionTime == _connectTime)
				{
					NetManager.SendRaw(_connectAcceptPacket, this);
				}
				else if (connRequest.ConnectionTime > _connectTime)
				{
					return ConnectRequestResult.Reconnection;
				}
				break;
			case ConnectionState.ShutdownRequested:
			case ConnectionState.Disconnected:
				if (connRequest.ConnectionTime >= _connectTime)
				{
					return ConnectRequestResult.NewConnection;
				}
				break;
			}
			return ConnectRequestResult.None;
		}

		internal virtual void ProcessChanneled(NetPacket packet)
		{
			if (packet.ChannelId >= 4 || packet.ChannelId == 3)
			{
				NetManager.PoolRecycle(packet);
			}
			else if (!CreateChannel(packet.ChannelId).ProcessPacket(packet))
			{
				NetManager.PoolRecycle(packet);
			}
		}

		internal void ProcessPacket(NetPacket packet)
		{
			if (_connectionState == ConnectionState.Outgoing || _connectionState == ConnectionState.Disconnected)
			{
				NetManager.PoolRecycle(packet);
				return;
			}
			if (packet.Property == PacketProperty.ShutdownOk)
			{
				if (_connectionState == ConnectionState.ShutdownRequested)
				{
					_connectionState = ConnectionState.Disconnected;
				}
				NetManager.PoolRecycle(packet);
				return;
			}
			if (packet.ConnectionNumber != _connectNum)
			{
				NetManager.PoolRecycle(packet);
				return;
			}
			Interlocked.Exchange(ref _timeSinceLastPacket, 0f);
			switch (packet.Property)
			{
			case PacketProperty.Merged:
			{
				int num2 = 1;
				while (num2 < packet.Size)
				{
					ushort num3 = BitConverter.ToUInt16(packet.RawData, num2);
					if (num3 == 0)
					{
						break;
					}
					num2 += 2;
					if (packet.Size - num2 < num3)
					{
						break;
					}
					NetPacket netPacket = NetManager.PoolGetPacket(num3);
					Buffer.BlockCopy(packet.RawData, num2, netPacket.RawData, 0