Decompiled source of LANLab v0.2.0

LanLab.dll

Decompiled 7 hours ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BoneLib.BoneMenu;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using LanLab;
using MelonLoader;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(LanLabMod), "LANLab", "0.2.0", "LANLab", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LanLab")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LanLab")]
[assembly: AssemblyTitle("LanLab")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace LanLab
{
	internal enum NetworkMode
	{
		Off,
		Host,
		Client
	}
	internal sealed class LanConfig
	{
		public string Mode { get; set; } = "Off";

		public string HostAddress { get; set; } = "127.0.0.1";

		public int Port { get; set; } = 27077;

		public string PlayerName { get; set; } = Environment.UserName;

		public int SendRate { get; set; } = 30;

		public NetworkMode ParsedMode
		{
			get
			{
				if (!Enum.TryParse<NetworkMode>(Mode, ignoreCase: true, out var result) || !Enum.IsDefined(typeof(NetworkMode), result))
				{
					return NetworkMode.Off;
				}
				return result;
			}
		}

		public static LanConfig Load(string path)
		{
			if (!File.Exists(path))
			{
				Directory.CreateDirectory(Path.GetDirectoryName(path));
				LanConfig lanConfig = new LanConfig();
				lanConfig.Save(path);
				return lanConfig;
			}
			LanConfig lanConfig2 = new LanConfig();
			try
			{
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.Length == 0 || text.StartsWith("#"))
					{
						continue;
					}
					int num = text.IndexOf('=');
					if (num >= 1)
					{
						string text2 = text.Substring(0, num).Trim();
						string text3 = text.Substring(num + 1).Trim();
						int result;
						int result2;
						if (text2.Equals("Mode", StringComparison.OrdinalIgnoreCase))
						{
							lanConfig2.Mode = text3;
						}
						else if (text2.Equals("HostAddress", StringComparison.OrdinalIgnoreCase))
						{
							lanConfig2.HostAddress = text3;
						}
						else if (text2.Equals("Port", StringComparison.OrdinalIgnoreCase) && int.TryParse(text3, out result))
						{
							lanConfig2.Port = result;
						}
						else if (text2.Equals("PlayerName", StringComparison.OrdinalIgnoreCase))
						{
							lanConfig2.PlayerName = text3;
						}
						else if (text2.Equals("SendRate", StringComparison.OrdinalIgnoreCase) && int.TryParse(text3, out result2))
						{
							lanConfig2.SendRate = result2;
						}
					}
				}
			}
			catch
			{
			}
			return lanConfig2;
		}

		public void Save(string path)
		{
			string text = path + ".tmp";
			try
			{
				File.WriteAllLines(text, new string[6]
				{
					"# LANLab LAN connection settings",
					"Mode=" + Mode,
					"HostAddress=" + HostAddress,
					$"Port={Port}",
					"PlayerName=" + PlayerName,
					$"SendRate={SendRate}"
				});
				if (File.Exists(path))
				{
					File.Replace(text, path, null);
				}
				else
				{
					File.Move(text, path);
				}
			}
			finally
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
		}

		public void Validate()
		{
			int port = Port;
			if (port < 1024 || port > 65535)
			{
				throw new ArgumentException("Enter a port from 1024 to 65535.");
			}
			port = SendRate;
			if (port < 5 || port > 60)
			{
				throw new ArgumentException("Choose a send rate from 5 to 60.");
			}
			string[] array = HostAddress.Split('.');
			if (array.Length != 4 || array.Any((string s) => s.Length == 0 || s.Length > 3 || (s.Length > 1 && s[0] == '0') || s.Any((char c) => c < '0' || c > '9') || !byte.TryParse(s, out var _)))
			{
				throw new ArgumentException("Enter the host IPv4 address, for example 192.168.1.10.");
			}
			if (string.IsNullOrWhiteSpace(PlayerName) || PlayerName.Any(char.IsControl) || Encoding.UTF8.GetByteCount(PlayerName) > 80)
			{
				throw new ArgumentException("Enter a single-line player name of up to 80 UTF-8 bytes.");
			}
		}
	}
	internal sealed class GameReplicator
	{
		private readonly ConcurrentDictionary<uint, (WorldSnapshot State, DateTime Seen)> _received = new ConcurrentDictionary<uint, (WorldSnapshot, DateTime)>();

		private readonly Dictionary<uint, GameObject> _proxies = new Dictionary<uint, GameObject>();

		private readonly Dictionary<uint, Rigidbody> _localBodies = new Dictionary<uint, Rigidbody>();

		private readonly Dictionary<uint, uint> _entityOwners = new Dictionary<uint, uint>();

		private Transform? _rig;

		private Transform? _head;

		private Transform? _leftHand;

		private Transform? _rightHand;

		private int _scanFrames;

		private int _entityCursor;

		private long _tick;

		public void Receive(WorldSnapshot state)
		{
			_received[state.SenderId] = (state, DateTime.UtcNow);
		}

		public WorldSnapshot Capture(uint playerId, string playerName)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			if (++_scanFrames >= 15 || (Object)(object)_rig == (Object)null)
			{
				_scanFrames = 0;
				RefreshRigAndBodies();
			}
			Transform rig = _rig;
			Transform val = (Transform)(((Object)(object)_head != (Object)null) ? ((object)_head) : ((object)(((Object)(object)Camera.main != (Object)null) ? ((Component)Camera.main).transform : rig)));
			Vector3 zero = Vector3.zero;
			PlayerState player = new PlayerState(playerId, playerName, ToNumerics(((Object)(object)rig != (Object)null) ? rig.position : (((Object)(object)val != (Object)null) ? val.position : zero)), ToNumerics(((Object)(object)rig != (Object)null) ? rig.rotation : Quaternion.identity), ToNumerics(((Object)(object)val != (Object)null) ? val.position : zero), ToNumerics(((Object)(object)val != (Object)null) ? val.rotation : Quaternion.identity), ToNumerics(((Object)(object)_leftHand != (Object)null) ? _leftHand.position : zero), ToNumerics(((Object)(object)_leftHand != (Object)null) ? _leftHand.rotation : Quaternion.identity), ToNumerics(((Object)(object)_rightHand != (Object)null) ? _rightHand.position : zero), ToNumerics(((Object)(object)_rightHand != (Object)null) ? _rightHand.rotation : Quaternion.identity));
			List<EntityState> list = new List<EntityState>(4);
			KeyValuePair<uint, Rigidbody>[] array = _localBodies.ToArray();
			if (array.Length != 0)
			{
				_entityCursor %= array.Length;
			}
			int num = Math.Min(array.Length, 4);
			for (int i = 0; i < num; i++)
			{
				KeyValuePair<uint, Rigidbody> keyValuePair = array[(_entityCursor + i) % array.Length];
				try
				{
					Rigidbody value = keyValuePair.Value;
					if (!((Object)(object)value == (Object)null) && ((Component)value).gameObject.activeInHierarchy)
					{
						string name = ((Object)((Component)value).gameObject).name;
						bool flag = LooksLikeWeapon(name);
						bool num2 = LooksLikeNpc(((Component)value).transform);
						byte kind = (byte)(num2 ? 2 : ((!flag) ? 1 : 3));
						Animator val2 = (num2 ? ((Component)value).GetComponentInChildren<Animator>() : null);
						string text;
						if (!((Object)(object)val2 != (Object)null))
						{
							text = string.Empty;
						}
						else
						{
							AnimatorStateInfo currentAnimatorStateInfo = val2.GetCurrentAnimatorStateInfo(0);
							text = "anim=" + ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).shortNameHash.ToString("X8");
						}
						string action = text;
						if (flag)
						{
							string text2 = (IsUnder(((Component)value).transform, _leftHand) ? "left" : (IsUnder(((Component)value).transform, _rightHand) ? "right" : "none"));
							Gun componentInChildren = ((Component)value).GetComponentInChildren<Gun>();
							action = (((Object)(object)componentInChildren != (Object)null) ? $"held={text2};ammo={componentInChildren.AmmoCount()};loaded={componentInChildren.isLoaded};firing={componentInChildren.isFiring}" : ("held=" + text2));
						}
						byte flags = (byte)((value.isKinematic ? 1u : 0u) | (uint)(flag ? 2 : 0));
						list.Add(new EntityState(keyValuePair.Key, kind, name, ToNumerics(value.position), ToNumerics(value.rotation), ToNumerics(value.velocity), ToNumerics(value.angularVelocity), flags, action));
					}
				}
				catch
				{
				}
			}
			_entityCursor += num;
			return new WorldSnapshot(playerId, Interlocked.Increment(ref _tick), player, list.ToArray());
		}

		public void ApplyReceived()
		{
			KeyValuePair<uint, (WorldSnapshot, DateTime)>[] array = _received.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<uint, (WorldSnapshot, DateTime)> keyValuePair = array[i];
				if ((DateTime.UtcNow - keyValuePair.Value.Item2).TotalSeconds > 3.0)
				{
					_received.TryRemove(keyValuePair.Key, out (WorldSnapshot, DateTime) _);
					RemovePeerProxies(keyValuePair.Key);
					continue;
				}
				WorldSnapshot item = keyValuePair.Value.Item1;
				ApplyPlayer(item.Player);
				EntityState[] entities = item.Entities;
				foreach (EntityState entityState in entities)
				{
					_entityOwners[entityState.Id] = item.SenderId;
					ApplyEntity(entityState);
				}
			}
		}

		private void RemovePeerProxies(uint peerId)
		{
			DestroyProxy(peerId);
			DestroyProxy(peerId ^ 0x40000000);
			DestroyProxy(peerId ^ 0x20000000);
			DestroyProxy(peerId ^ 0x10000000);
			uint[] array = (from x in _entityOwners
				where x.Value == peerId
				select x.Key).ToArray();
			foreach (uint num2 in array)
			{
				_entityOwners.Remove(num2);
				DestroyProxy(num2);
			}
		}

		public void ClearProxies()
		{
			uint[] array = _proxies.Keys.ToArray();
			foreach (uint id in array)
			{
				DestroyProxy(id);
			}
		}

		private void DestroyProxy(uint id)
		{
			if (_proxies.TryGetValue(id, out GameObject value))
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)value);
				}
				_proxies.Remove(id);
			}
		}

		private void RefreshRigAndBodies()
		{
			try
			{
				Il2CppArrayBase<Transform> val = Object.FindObjectsOfType<Transform>();
				if ((Object)(object)_rig == (Object)null)
				{
					foreach (Transform item in val)
					{
						string name = ((Object)item).name;
						if (name.IndexOf("RigManager", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("PlayerRig", StringComparison.OrdinalIgnoreCase) >= 0)
						{
							_rig = item;
							break;
						}
					}
				}
				if ((Object)(object)_rig != (Object)null)
				{
					if (_head == null)
					{
						_head = FindDescendant(_rig, new string[2] { "head", "hmd" });
					}
					if (_leftHand == null)
					{
						_leftHand = FindDescendant(_rig, new string[3] { "lefthand", "hand_l", "handl" });
					}
					if (_rightHand == null)
					{
						_rightHand = FindDescendant(_rig, new string[3] { "righthand", "hand_r", "handr" });
					}
				}
				_localBodies.Clear();
				foreach (Rigidbody item2 in Object.FindObjectsOfType<Rigidbody>())
				{
					if (!((Object)(object)item2 == (Object)null) && ((Component)item2).gameObject.activeInHierarchy && !IsUnder(((Component)item2).transform, _rig))
					{
						uint num = StableId(((Component)item2).transform);
						if (num != 0 && !_localBodies.ContainsKey(num))
						{
							_localBodies[num] = item2;
						}
					}
				}
			}
			catch
			{
			}
		}

		private static Transform? FindDescendant(Transform root, string[] needles)
		{
			try
			{
				foreach (Transform componentsInChild in ((Component)root).GetComponentsInChildren<Transform>(true))
				{
					string text = ((Object)componentsInChild).name.Replace(" ", "").Replace("-", "").ToLowerInvariant();
					if (needles.Any(text.Contains))
					{
						return componentsInChild;
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private void ApplyPlayer(PlayerState state)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: 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)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			uint id = state.Id;
			uint id2 = state.Id ^ 0x40000000;
			uint id3 = state.Id ^ 0x20000000;
			uint id4 = state.Id ^ 0x10000000;
			if (!_proxies.TryGetValue(id, out GameObject value) || (Object)(object)value == (Object)null)
			{
				value = CreateProxy((PrimitiveType)1, "LANLab Remote Player " + state.Name, new Vector3(0.42f, 0.9f, 0.32f), new Color(0.2f, 0.72f, 1f));
				_proxies[id] = value;
			}
			value.transform.SetPositionAndRotation(ToUnity(state.Position), ToUnity(state.Rotation));
			GetProxy(id2, (PrimitiveType)0, "LANLab " + state.Name + " head", new Vector3(0.18f, 0.18f, 0.18f)).transform.SetPositionAndRotation(ToUnity(state.HeadPosition), ToUnity(state.HeadRotation));
			GetProxy(id3, (PrimitiveType)0, "LANLab " + state.Name + " left hand", new Vector3(0.1f, 0.1f, 0.1f)).transform.SetPositionAndRotation(ToUnity(state.LeftHandPosition), ToUnity(state.LeftHandRotation));
			GetProxy(id4, (PrimitiveType)0, "LANLab " + state.Name + " right hand", new Vector3(0.1f, 0.1f, 0.1f)).transform.SetPositionAndRotation(ToUnity(state.RightHandPosition), ToUnity(state.RightHandRotation));
		}

		private void ApplyEntity(EntityState state)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: 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_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_010a: Unknown result type (might be due to invalid IL or missing references)
			if (_localBodies.TryGetValue(state.Id, out Rigidbody value) && (Object)(object)value != (Object)null)
			{
				try
				{
					value.position = Vector3.Lerp(value.position, ToUnity(state.Position), 0.55f);
					value.rotation = Quaternion.Slerp(value.rotation, ToUnity(state.Rotation), 0.55f);
					if (!value.isKinematic)
					{
						value.velocity = ToUnity(state.Velocity);
					}
					return;
				}
				catch
				{
					return;
				}
			}
			if (!_proxies.TryGetValue(state.Id, out GameObject value2) || (Object)(object)value2 == (Object)null)
			{
				int num = ((state.Kind == 2) ? 1 : 3);
				value2 = CreateProxy(scale: (state.Kind == 2) ? new Vector3(0.45f, 0.9f, 0.35f) : new Vector3(0.2f, 0.12f, 0.35f), primitive: (PrimitiveType)num, name: "LANLab Replica " + state.Name, tint: (state.Kind == 2) ? new Color(1f, 0.55f, 0.2f) : new Color(0.9f, 0.8f, 0.25f));
				_proxies[state.Id] = value2;
			}
			value2.transform.SetPositionAndRotation(ToUnity(state.Position), ToUnity(state.Rotation));
		}

		private GameObject GetProxy(uint id, PrimitiveType primitive, string name, Vector3 scale)
		{
			//IL_001b: 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)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (_proxies.TryGetValue(id, out GameObject value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			GameObject val = CreateProxy(primitive, name, scale, new Color(0.2f, 0.72f, 1f));
			_proxies[id] = val;
			return val;
		}

		private static GameObject CreateProxy(PrimitiveType primitive, string name, Vector3 scale, Color tint)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive(primitive);
			((Object)obj).name = name;
			obj.transform.localScale = scale;
			Collider component = obj.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			Renderer component2 = obj.GetComponent<Renderer>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.material.color = tint;
			}
			return obj;
		}

		private static bool LooksLikeWeapon(string name)
		{
			if (!name.Contains("gun", StringComparison.OrdinalIgnoreCase) && !name.Contains("pistol", StringComparison.OrdinalIgnoreCase) && !name.Contains("rifle", StringComparison.OrdinalIgnoreCase) && !name.Contains("shotgun", StringComparison.OrdinalIgnoreCase))
			{
				return name.Contains("weapon", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private static bool LooksLikeNpc(Transform transform)
		{
			try
			{
				if ((Object)(object)((Component)transform).GetComponentInChildren<Animator>() != (Object)null)
				{
					return true;
				}
				string name = ((Object)transform).name;
				return name.Contains("nullbody", StringComparison.OrdinalIgnoreCase) || name.Contains("crablet", StringComparison.OrdinalIgnoreCase) || name.Contains("ford", StringComparison.OrdinalIgnoreCase) || name.Contains("npc", StringComparison.OrdinalIgnoreCase);
			}
			catch
			{
				return false;
			}
		}

		private static uint StableId(Transform transform)
		{
			Stack<string> stack = new Stack<string>();
			Transform val = transform;
			while ((Object)(object)val != (Object)null && stack.Count < 32)
			{
				stack.Push(((Object)val).name + "[" + val.GetSiblingIndex() + "]");
				val = val.parent;
			}
			uint num = 2166136261u;
			string text = string.Join("/", stack);
			foreach (char c in text)
			{
				num = (num ^ c) * 16777619;
			}
			if (num != 0)
			{
				return num;
			}
			return 1u;
		}

		private static bool IsUnder(Transform node, Transform? root)
		{
			while ((Object)(object)node != (Object)null)
			{
				if ((Object)(object)node == (Object)(object)root)
				{
					return true;
				}
				node = node.parent;
			}
			return false;
		}

		private static Vector3 ToNumerics(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(v.x, v.y, v.z);
		}

		private static Quaternion ToNumerics(Quaternion q)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Quaternion(q.x, q.y, q.z, q.w);
		}

		private static Vector3 ToUnity(Vector3 v)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(v.X, v.Y, v.Z);
		}

		private static Quaternion ToUnity(Quaternion q)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Quaternion(q.X, q.Y, q.Z, q.W);
		}
	}
	public sealed class LanLabMod : MelonMod
	{
		private LanConfig _config = new LanConfig();

		private readonly string _configPath = Path.Combine(Directory.GetCurrentDirectory(), "UserData", "LANLab.cfg");

		private LanTransport? _transport;

		private GameReplicator? _replicator;

		private float _sendTimer;

		public override void OnInitializeMelon()
		{
			try
			{
				_config = LanConfig.Load(_configPath);
				if (_config.ParsedMode != NetworkMode.Off)
				{
					Apply(_config, save: false);
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Error("Open BoneMenu > LANLab to update the connection settings. " + ex.Message);
			}
		}

		public override void OnLateInitializeMelon()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			Page obj = Page.Root.CreatePage("LANLab", Color.cyan, 0, true);
			NetworkMode mode = _config.ParsedMode;
			string address = _config.HostAddress;
			string portText = _config.Port.ToString();
			string name = _config.PlayerName;
			int rate = Math.Clamp(_config.SendRate, 5, 60);
			obj.CreateEnum("Mode", Color.white, (Enum)mode, (Action<Enum>)delegate(Enum value)
			{
				mode = (NetworkMode)(object)value;
			});
			obj.CreateString("Host IPv4 address", Color.white, address, (Action<string>)delegate(string value)
			{
				address = value.Trim();
			});
			obj.CreateString("UDP port", Color.white, portText, (Action<string>)delegate(string value)
			{
				portText = value.Trim();
			});
			obj.CreateString("Player name", Color.white, name, (Action<string>)delegate(string value)
			{
				name = value.Trim();
			});
			obj.CreateInt("Updates per second", Color.white, rate, 1, 5, 60, (Action<int>)delegate(int value)
			{
				rate = value;
			});
			obj.CreateFunction("Save and apply", Color.green, (Action)delegate
			{
				try
				{
					if (!int.TryParse(portText, out var result))
					{
						throw new ArgumentException("Enter a numeric UDP port.");
					}
					Apply(new LanConfig
					{
						Mode = mode.ToString(),
						HostAddress = address,
						Port = result,
						PlayerName = name,
						SendRate = rate
					}, save: true);
					ShowStatus();
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning(ex.Message);
					Menu.DisplayDialog("Could not apply settings", ex.Message, (Texture2D)null, (Action)delegate
					{
					}, (Action)null);
				}
			});
			obj.CreateFunction("Connection status", Color.white, (Action)ShowStatus);
		}

		private void ShowStatus()
		{
			string text = "LAN is off.";
			if (_transport != null && _config.ParsedMode == NetworkMode.Host)
			{
				text = $"Hosting on UDP port {_config.Port}.";
				try
				{
					IEnumerable<IPAddress> values = from ip in Dns.GetHostAddresses(Dns.GetHostName())
						where ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip)
						select ip;
					string text2 = string.Join(", ", values);
					if (text2.Length > 0)
					{
						text = text + "\nHost IPv4: " + text2;
					}
				}
				catch (SocketException)
				{
					text += "\nUse your PC's LAN IPv4 address to join.";
				}
			}
			else if (_transport != null)
			{
				string arg = ((_transport.LocalId == 0) ? "Joining" : "Joined");
				text = $"{arg} {_config.HostAddress}:{_config.Port}.";
			}
			Menu.DisplayDialog("LANLab", text, (Texture2D)null, (Action)delegate
			{
			}, (Action)null);
		}

		private void Apply(LanConfig next, bool save)
		{
			next.Validate();
			bool flag = _transport != null && _config.ParsedMode == next.ParsedMode && _config.Port == next.Port && (next.ParsedMode == NetworkMode.Host || (_config.HostAddress == next.HostAddress && _config.PlayerName == next.PlayerName));
			LanTransport lanTransport = null;
			try
			{
				if (!flag && next.ParsedMode != NetworkMode.Off)
				{
					lanTransport = new LanTransport(next);
				}
				if (save)
				{
					next.Save(_configPath);
				}
				if (!flag)
				{
					StopSession();
					if (lanTransport != null)
					{
						_replicator = new GameReplicator();
						lanTransport.SnapshotReceived += _replicator.Receive;
						_transport = lanTransport;
						lanTransport = null;
					}
				}
				_config = next;
			}
			finally
			{
				lanTransport?.Dispose();
			}
		}

		public override void OnUpdate()
		{
			if (_transport == null || _replicator == null)
			{
				return;
			}
			try
			{
				_transport.Pump();
				_replicator.ApplyReceived();
				_sendTimer += Time.unscaledDeltaTime;
				float num = 1f / (float)_config.SendRate;
				if (_sendTimer >= num && _transport.LocalId != 0)
				{
					_sendTimer %= num;
					_transport.Send(_replicator.Capture(_transport.LocalId, _config.PlayerName));
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("LAN frame sync skipped: " + ex.Message);
			}
		}

		private void StopSession()
		{
			_transport?.Dispose();
			_transport = null;
			_replicator?.ClearProxies();
			_replicator = null;
			_sendTimer = 0f;
		}

		public override void OnDeinitializeMelon()
		{
			StopSession();
		}
	}
	internal sealed class LanTransport : IDisposable
	{
		private readonly UdpClient _udp;

		private readonly bool _isHost;

		private readonly IPEndPoint? _server;

		private readonly ConcurrentDictionary<uint, IPEndPoint> _peers = new ConcurrentDictionary<uint, IPEndPoint>();

		private readonly ConcurrentQueue<(IPEndPoint From, PacketKind Kind, object Data)> _incoming = new ConcurrentQueue<(IPEndPoint, PacketKind, object)>();

		private readonly CancellationTokenSource _stop = new CancellationTokenSource();

		private readonly string _name;

		private uint _localId;

		public uint LocalId => _localId;

		public event Action<WorldSnapshot>? SnapshotReceived;

		public LanTransport(LanConfig config)
		{
			LanTransport lanTransport = this;
			_name = config.PlayerName;
			_isHost = config.ParsedMode == NetworkMode.Host;
			if (_isHost)
			{
				_udp = new UdpClient(new IPEndPoint(IPAddress.Any, config.Port));
			}
			else
			{
				_udp = new UdpClient(0);
				_server = new IPEndPoint(IPAddress.Parse(config.HostAddress), config.Port);
			}
			Task.Run((Func<Task?>)ReceiveLoop);
			if (!_isHost)
			{
				CancellationToken token = _stop.Token;
				Task.Run(() => lanTransport.HelloLoop(token));
			}
			else
			{
				_localId = 1u;
			}
		}

		public void Pump()
		{
			(IPEndPoint, PacketKind, object) result;
			while (_incoming.TryDequeue(out result))
			{
				if (_isHost)
				{
					HandleHostPacket(result.Item1, result.Item2, result.Item3);
				}
				else
				{
					HandleClientPacket(result.Item2, result.Item3);
				}
			}
		}

		public void Send(WorldSnapshot snapshot)
		{
			snapshot = snapshot with
			{
				SenderId = _localId,
				Player = snapshot.Player with
				{
					Id = _localId
				}
			};
			byte[] data = Protocol.Snapshot(snapshot);
			if (_isHost)
			{
				foreach (IPEndPoint value in _peers.Values)
				{
					SendTo(data, value);
				}
				return;
			}
			if (_server != null)
			{
				SendTo(data, _server);
			}
		}

		private async Task ReceiveLoop()
		{
			while (!_stop.IsCancellationRequested)
			{
				try
				{
					UdpReceiveResult udpReceiveResult = await _udp.ReceiveAsync().ConfigureAwait(continueOnCapturedContext: false);
					if (Protocol.TryRead(udpReceiveResult.Buffer, out PacketKind kind, out object data) && data != null)
					{
						_incoming.Enqueue((udpReceiveResult.RemoteEndPoint, kind, data));
					}
				}
				catch (ObjectDisposedException)
				{
					break;
				}
				catch (SocketException)
				{
					if (_stop.IsCancellationRequested)
					{
						break;
					}
					await Task.Delay(20).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch
				{
					await Task.Delay(20).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		private async Task HelloLoop(CancellationToken token)
		{
			while (!token.IsCancellationRequested)
			{
				if (_server != null)
				{
					SendTo(Protocol.Hello(_name), _server);
				}
				try
				{
					await Task.Delay(1000, token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					break;
				}
			}
		}

		private void HandleHostPacket(IPEndPoint from, PacketKind kind, object data)
		{
			switch (kind)
			{
			case PacketKind.Hello:
			{
				uint num = PeerId(from);
				_peers[num] = from;
				SendTo(Protocol.Welcome(num), from);
				return;
			}
			case PacketKind.Snapshot:
			{
				if (!(data is WorldSnapshot worldSnapshot) || !_peers.ContainsKey(worldSnapshot.SenderId))
				{
					break;
				}
				this.SnapshotReceived?.Invoke(worldSnapshot);
				byte[] data2 = Protocol.Snapshot(worldSnapshot);
				foreach (KeyValuePair<uint, IPEndPoint> peer in _peers)
				{
					if (peer.Key != worldSnapshot.SenderId)
					{
						SendTo(data2, peer.Value);
					}
				}
				break;
			}
			}
			if (kind == PacketKind.Leave && data is uint key)
			{
				_peers.TryRemove(key, out IPEndPoint _);
			}
		}

		private void HandleClientPacket(PacketKind kind, object data)
		{
			if (kind == PacketKind.Welcome && data is uint localId)
			{
				_localId = localId;
			}
			if (kind == PacketKind.Snapshot && data is WorldSnapshot worldSnapshot && worldSnapshot.SenderId != _localId)
			{
				this.SnapshotReceived?.Invoke(worldSnapshot);
			}
		}

		private static uint PeerId(IPEndPoint endpoint)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(endpoint.Address?.ToString() + ":" + endpoint.Port);
			uint num = 2166136261u;
			byte[] array = bytes;
			foreach (byte b in array)
			{
				num = (num ^ b) * 16777619;
			}
			if (num != 0)
			{
				return num;
			}
			return 2u;
		}

		private void SendTo(byte[] data, IPEndPoint endpoint)
		{
			try
			{
				_udp.SendAsync(data, data.Length, endpoint);
			}
			catch
			{
			}
		}

		public void Dispose()
		{
			if (!_stop.IsCancellationRequested && _localId != 0 && !_isHost && _server != null)
			{
				SendTo(Protocol.Leave(_localId), _server);
			}
			_stop.Cancel();
			_udp.Dispose();
			_stop.Dispose();
		}
	}
	internal enum PacketKind : byte
	{
		Hello = 1,
		Welcome,
		Snapshot,
		Leave
	}
	internal sealed record PlayerState(uint Id, string Name, Vector3 Position, Quaternion Rotation, Vector3 HeadPosition, Quaternion HeadRotation, Vector3 LeftHandPosition, Quaternion LeftHandRotation, Vector3 RightHandPosition, Quaternion RightHandRotation);
	internal sealed record EntityState(uint Id, byte Kind, string Name, Vector3 Position, Quaternion Rotation, Vector3 Velocity, Vector3 AngularVelocity, byte Flags, string Action);
	internal sealed record WorldSnapshot(uint SenderId, long Tick, PlayerState Player, EntityState[] Entities);
	internal static class Protocol
	{
		private const byte Version = 1;

		private const int MaxEntities = 4;

		private const int MaxStringBytes = 80;

		public static byte[] Hello(string name)
		{
			return Write(PacketKind.Hello, delegate(BinaryWriter w)
			{
				WriteString(w, name);
			});
		}

		public static byte[] Welcome(uint id)
		{
			return Write(PacketKind.Welcome, delegate(BinaryWriter w)
			{
				w.Write(id);
			});
		}

		public static byte[] Leave(uint id)
		{
			return Write(PacketKind.Leave, delegate(BinaryWriter w)
			{
				w.Write(id);
			});
		}

		public static byte[] Snapshot(WorldSnapshot s)
		{
			return Write(PacketKind.Snapshot, delegate(BinaryWriter w)
			{
				w.Write(s.SenderId);
				w.Write(s.Tick);
				WritePlayer(w, s.Player);
				int num = Math.Min(s.Entities.Length, 4);
				w.Write((ushort)num);
				for (int i = 0; i < num; i++)
				{
					WriteEntity(w, s.Entities[i]);
				}
			});
		}

		public static bool TryRead(byte[] bytes, out PacketKind kind, out object? data)
		{
			kind = (PacketKind)0;
			data = null;
			try
			{
				using MemoryStream memoryStream = new MemoryStream(bytes, writable: false);
				using BinaryReader binaryReader = new BinaryReader(memoryStream);
				if (binaryReader.ReadByte() != 1)
				{
					return false;
				}
				kind = (PacketKind)binaryReader.ReadByte();
				switch (kind)
				{
				case PacketKind.Hello:
					data = ReadString(binaryReader);
					break;
				case PacketKind.Welcome:
				case PacketKind.Leave:
					data = binaryReader.ReadUInt32();
					break;
				case PacketKind.Snapshot:
				{
					uint senderId = binaryReader.ReadUInt32();
					long tick = binaryReader.ReadInt64();
					PlayerState player = ReadPlayer(binaryReader);
					int num = Math.Min((int)binaryReader.ReadUInt16(), 4);
					EntityState[] array = new EntityState[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = ReadEntity(binaryReader);
					}
					data = new WorldSnapshot(senderId, tick, player, array);
					break;
				}
				default:
					return false;
				}
				return memoryStream.Position == memoryStream.Length;
			}
			catch
			{
				return false;
			}
		}

		private static byte[] Write(PacketKind kind, Action<BinaryWriter> body)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write((byte)1);
			binaryWriter.Write((byte)kind);
			body(binaryWriter);
			return memoryStream.ToArray();
		}

		private static void WritePlayer(BinaryWriter w, PlayerState p)
		{
			w.Write(p.Id);
			WriteString(w, p.Name);
			WriteVector(w, p.Position);
			WriteQuaternion(w, p.Rotation);
			WriteVector(w, p.HeadPosition);
			WriteQuaternion(w, p.HeadRotation);
			WriteVector(w, p.LeftHandPosition);
			WriteQuaternion(w, p.LeftHandRotation);
			WriteVector(w, p.RightHandPosition);
			WriteQuaternion(w, p.RightHandRotation);
		}

		private static PlayerState ReadPlayer(BinaryReader r)
		{
			return new PlayerState(r.ReadUInt32(), ReadString(r), ReadVector(r), ReadQuaternion(r), ReadVector(r), ReadQuaternion(r), ReadVector(r), ReadQuaternion(r), ReadVector(r), ReadQuaternion(r));
		}

		private static void WriteEntity(BinaryWriter w, EntityState e)
		{
			w.Write(e.Id);
			w.Write(e.Kind);
			WriteString(w, e.Name);
			WriteVector(w, e.Position);
			WriteQuaternion(w, e.Rotation);
			WriteVector(w, e.Velocity);
			WriteVector(w, e.AngularVelocity);
			w.Write(e.Flags);
			WriteString(w, e.Action);
		}

		private static EntityState ReadEntity(BinaryReader r)
		{
			return new EntityState(r.ReadUInt32(), r.ReadByte(), ReadString(r), ReadVector(r), ReadQuaternion(r), ReadVector(r), ReadVector(r), r.ReadByte(), ReadString(r));
		}

		private static void WriteString(BinaryWriter w, string s)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(s ?? string.Empty);
			int num = Math.Min(bytes.Length, 80);
			w.Write((byte)num);
			w.Write(bytes, 0, num);
		}

		private static string ReadString(BinaryReader r)
		{
			return Encoding.UTF8.GetString(r.ReadBytes(r.ReadByte()));
		}

		private static void WriteVector(BinaryWriter w, Vector3 v)
		{
			w.Write(v.X);
			w.Write(v.Y);
			w.Write(v.Z);
		}

		private static Vector3 ReadVector(BinaryReader r)
		{
			return new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
		}

		private static void WriteQuaternion(BinaryWriter w, Quaternion q)
		{
			w.Write(q.X);
			w.Write(q.Y);
			w.Write(q.Z);
			w.Write(q.W);
		}

		private static Quaternion ReadQuaternion(BinaryReader r)
		{
			return new Quaternion(r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
		}
	}
}