Decompiled source of Lethal Idiots v1.0.1

BepInEx/plugins/2018-LC_API/LC_API.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ClientAPI;
using LC_API.Comp;
using LC_API.Data;
using LC_API.Exceptions;
using LC_API.Extensions;
using LC_API.GameInterfaceAPI;
using LC_API.GameInterfaceAPI.Events;
using LC_API.GameInterfaceAPI.Events.Cache;
using LC_API.GameInterfaceAPI.Events.EventArgs.Player;
using LC_API.GameInterfaceAPI.Events.Handlers;
using LC_API.GameInterfaceAPI.Features;
using LC_API.ManualPatches;
using LC_API.Networking;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("2018")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("3.4.5.0")]
[assembly: AssemblyInformationalVersion("3.4.5+ae2de74676f4f0d6440c82067f4c1a22389fe27b")]
[assembly: AssemblyProduct("Lethal Company API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 LC_API
{
	internal static class CheatDatabase
	{
		private const string SIG_REQ_GUID = "LC_API_ReqGUID";

		private const string SIG_SEND_MODS = "LC_APISendMods";

		private static Dictionary<string, PluginInfo> PluginsLoaded = new Dictionary<string, PluginInfo>();

		public static void RunLocalCheatDetector()
		{
			PluginsLoaded = Chainloader.PluginInfos;
			using Dictionary<string, PluginInfo>.ValueCollection.Enumerator enumerator = PluginsLoaded.Values.GetEnumerator();
			while (enumerator.MoveNext())
			{
				switch (enumerator.Current.Metadata.GUID)
				{
				case "mikes.lethalcompany.mikestweaks":
				case "mom.llama.enhancer":
				case "Posiedon.GameMaster":
				case "LethalCompanyScalingMaster":
				case "verity.amberalert":
					ModdedServer.SetServerModdedOnly();
					break;
				}
			}
		}

		public static void OtherPlayerCheatDetector()
		{
			Plugin.Log.LogWarning((object)"Asking all other players for their mod list..");
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", "Asking all other players for installed mods..");
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", "Check the logs for more detailed results.\n<size=13>(Note that if someone doesnt show up on the list, they may not have LC_API installed)</size>");
			Network.Broadcast("LC_API_ReqGUID");
		}

		[NetworkMessage("LC_APISendMods", false)]
		internal static void ReceivedModListHandler(ulong senderId, List<string> mods)
		{
			string text = LC_API.GameInterfaceAPI.Features.Player.Get(senderId).Username + " responded with these mods:\n" + string.Join("\n", mods);
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", text);
			Plugin.Log.LogWarning((object)text);
		}

		[NetworkMessage("LC_API_ReqGUID", false)]
		internal static void ReceivedModListHandler(ulong senderId)
		{
			List<string> list = new List<string>();
			foreach (PluginInfo value in PluginsLoaded.Values)
			{
				list.Add(value.Metadata.GUID);
			}
			Network.Broadcast("LC_APISendMods", list);
		}
	}
	[BepInPlugin("LC_API", "Lethal Company API", "3.4.5")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		internal static ConfigEntry<bool> configVanillaSupport;

		internal static Harmony Harmony;

		internal static Plugin Instance { get; private set; }

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Expected O, but got Unknown
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Expected O, but got Unknown
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Expected O, but got Unknown
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Expected O, but got Unknown
			Instance = this;
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			configVanillaSupport = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "Vanilla Compatibility", false, "Allows you to join vanilla servers, but disables many networking-related things and could cause mods to not work properly.");
			CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix");
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____    _________           _____  __________ .___  \r\n|    |   \\_   ___ \\         /  _  \\ \\______   \\|   | \r\n|    |   /    \\  \\/        /  /_\\  \\ |     ___/|   | \r\n|    |___\\     \\____      /    |    \\|    |    |   | \r\n|_______ \\\\______  /______\\____|__  /|____|    |___| \r\n        \\/       \\//_____/        \\/                 \r\n                                                     ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up..");
			if (configOverrideModServer.Value)
			{
				ModdedServer.SetServerModdedOnly();
			}
			if (configVanillaSupport.Value)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API is starting with VANILLA SUPPORT ENABLED.");
			}
			Harmony = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null);
			MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null);
			MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null);
			Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Network.Init();
			Events.Patch(Harmony);
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			//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_003a: Expected O, but got Unknown
			if (!Initialized)
			{
				Initialized = true;
				if (!configDisableBundleLoader.Value)
				{
					BundleLoader.Load(configLegacyAssetLoading.Value);
				}
				GameObject val = new GameObject("API");
				Object.DontDestroyOnLoad((Object)val);
				val.AddComponent<LC_APIManager>();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!");
				CheatDatabase.RunLocalCheatDetector();
			}
		}

		internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public static class Utils
	{
		public static string ReplaceWithCase(this string input, string toReplace, string replacement)
		{
			Dictionary<string, string> map = new Dictionary<string, string> { { toReplace, replacement } };
			return input.ReplaceWithCase(map);
		}

		public static string ReplaceWithCase(this string input, Dictionary<string, string> map)
		{
			string text = input;
			foreach (KeyValuePair<string, string> item in map)
			{
				string key = item.Key;
				string value = item.Value;
				text = Regex.Replace(text, key, delegate(Match match)
				{
					string value2 = match.Value;
					char[] array = value2.ToCharArray();
					string[] source = value2.Split(' ');
					bool flag = char.IsUpper(array[0]);
					bool flag2 = source.All((string w) => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
					if (array.All((char c) => char.IsUpper(c) || !char.IsLetter(c)))
					{
						return value.ToUpper();
					}
					if (flag2)
					{
						return Regex.Replace(value, "\\b\\w", (Match charMatch) => charMatch.Value.ToUpper());
					}
					char[] array2 = value.ToCharArray();
					array2[0] = (flag ? char.ToUpper(array2[0]) : char.ToLower(array2[0]));
					return new string(array2);
				}, RegexOptions.IgnoreCase);
			}
			return text;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LC_API";

		public const string PLUGIN_NAME = "Lethal Company API";

		public const string PLUGIN_VERSION = "3.4.5";
	}
}
namespace LC_API.ServerAPI
{
	public static class ModdedServer
	{
		private static bool moddedOnly;

		[Obsolete("Use SetServerModdedOnly() instead. This will be removed/private in a future update.")]
		public static bool setModdedOnly;

		public static int GameVersion { get; internal set; }

		public static bool ModdedOnly => moddedOnly;

		public static void SetServerModdedOnly()
		{
			moddedOnly = true;
			Plugin.Log.LogMessage((object)"A plugin has set your game to only allow you to play with other people who have mods!");
		}

		public static void OnSceneLoaded()
		{
			if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly)
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				instance.gameVersionNum += 16440;
				setModdedOnly = true;
			}
		}
	}
	[Obsolete("ServerAPI.Networking is obsolete and will be removed in future versions. Use LC_API.Networking.Network.")]
	public static class Networking
	{
		private sealed class Data<T>
		{
			public readonly string Signature;

			public readonly T Value;

			public Data(string signature, T value)
			{
				Signature = signature;
				Value = value;
			}
		}

		private const string StringMessageRegistrationName = "LCAPI_NET_LEGACY_STRING";

		private const string ListStringMessageRegistrationName = "LCAPI_NET_LEGACY_LISTSTRING";

		private const string IntMessageRegistrationName = "LCAPI_NET_LEGACY_INT";

		private const string FloatMessageRegistrationName = "LCAPI_NET_LEGACY_FLOAT";

		private const string Vector3MessageRegistrationName = "LCAPI_NET_LEGACY_VECTOR3";

		private const string SyncVarMessageRegistrationName = "LCAPI_NET_LEGACY_SYNCVAR_SET";

		public static Action<string, string> GetString = delegate
		{
		};

		public static Action<List<string>, string> GetListString = delegate
		{
		};

		public static Action<int, string> GetInt = delegate
		{
		};

		public static Action<float, string> GetFloat = delegate
		{
		};

		public static Action<Vector3, string> GetVector3 = delegate
		{
		};

		private static Dictionary<string, string> syncStringVars = new Dictionary<string, string>();

		public static void Broadcast(string data, string signature)
		{
			if (data.Contains("/"))
			{
				Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
			}
			else
			{
				Network.Broadcast("LCAPI_NET_LEGACY_STRING", new Data<string>(signature, data));
			}
		}

		public static void Broadcast(List<string> data, string signature)
		{
			string text = "";
			foreach (string datum in data)
			{
				if (datum.Contains("/"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
					return;
				}
				if (datum.Contains("\n"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )");
					return;
				}
				text = text + datum + "\n";
			}
			Network.Broadcast("LCAPI_NET_LEGACY_LISTSTRING", new Data<string>(signature, text));
		}

		public static void Broadcast(int data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_INT", new Data<int>(signature, data));
		}

		public static void Broadcast(float data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_FLOAT", new Data<float>(signature, data));
		}

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Network.Broadcast("LCAPI_NET_LEGACY_VECTOR3", new Data<Vector3>(signature, data));
		}

		public static void RegisterSyncVariable(string name)
		{
			if (!syncStringVars.ContainsKey(name))
			{
				syncStringVars.Add(name, "");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot register Sync Variable! A Sync Variable has already been registered with name " + name));
			}
		}

		public static void SetSyncVariable(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
				Broadcast(new List<string> { name, value }, "LCAPI_NET_LEGACY_SYNCVAR_SET");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		private static void SetSyncVariableB(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		internal static void LCAPI_NET_SYNCVAR_SET(List<string> list, string arg2)
		{
			if (arg2 == "LCAPI_NET_LEGACY_SYNCVAR_SET")
			{
				SetSyncVariableB(list[0], list[1]);
			}
		}

		public static string GetSyncVariable(string name)
		{
			if (syncStringVars.ContainsKey(name))
			{
				return syncStringVars[name];
			}
			Plugin.Log.LogError((object)("Cannot get the value of Sync Variable " + name + " as it is not registered!"));
			return "";
		}

		internal static void InitializeLegacyNetworking()
		{
			GetListString = (Action<List<string>, string>)Delegate.Combine(GetListString, new Action<List<string>, string>(LCAPI_NET_SYNCVAR_SET));
			Network.RegisterMessage("LCAPI_NET_LEGACY_STRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetString(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_LISTSTRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetListString(data.Value.Split('\n').ToList(), data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_INT", relayToSelf: false, delegate(ulong senderId, Data<int> data)
			{
				GetInt(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_FLOAT", relayToSelf: false, delegate(ulong senderId, Data<float> data)
			{
				GetFloat(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_VECTOR3", relayToSelf: false, delegate(ulong senderId, Data<Vector3> data)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				GetVector3(data.Value, data.Signature);
			});
		}
	}
}
namespace LC_API.Networking
{
	public static class Network
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__35_2;

			public static Events.CustomEventHandler <>9__35_0;

			public static Events.CustomEventHandler <>9__35_1;

			internal void <Init>b__35_0()
			{
				//IL_0041: 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_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//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_003d: Unknown result type (might be due to invalid IL or missing references)
							//IL_0043: Unknown result type (might be due to invalid IL or missing references)
							//IL_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			}

			internal void <Init>b__35_2(ulong senderClientId, FastBufferReader reader)
			{
				//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_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				byte[] bytes = default(byte[]);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
				NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
				networkMessageWrapper.Sender = senderClientId;
				byte[] array = networkMessageWrapper.ToBytes();
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val, (NetworkDelivery)4);
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}

			internal void <Init>b__35_1()
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			}
		}

		internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE";

		private static MethodInfo _registerInfo = null;

		private static MethodInfo _registerInfoGeneric = null;

		internal static Dictionary<string, NetworkMessageFinalizerBase> NetworkMessageFinalizers { get; } = new Dictionary<string, NetworkMessageFinalizerBase>();


		internal static bool StartedNetworking { get; set; } = false;


		internal static MethodInfo RegisterInfo
		{
			get
			{
				if (_registerInfo == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && !methodInfo.IsGenericMethod)
						{
							_registerInfo = methodInfo;
							break;
						}
					}
				}
				return _registerInfo;
			}
		}

		internal static MethodInfo RegisterInfoGeneric
		{
			get
			{
				if (_registerInfoGeneric == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && methodInfo.IsGenericMethod)
						{
							_registerInfoGeneric = methodInfo;
							break;
						}
					}
				}
				return _registerInfoGeneric;
			}
		}

		public static event Events.CustomEventHandler RegisterNetworkMessages;

		internal static event Events.CustomEventHandler UnregisterNetworkMessages;

		internal static byte[] ToBytes(this object @object)
		{
			if (@object == null)
			{
				return null;
			}
			return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@object));
		}

		internal static T ToObject<T>(this byte[] bytes) where T : class
		{
			return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
		}

		internal static void OnRegisterNetworkMessages()
		{
			Network.RegisterNetworkMessages.InvokeSafely();
		}

		internal static void OnUnregisterNetworkMessages()
		{
			Network.UnregisterNetworkMessages.InvokeSafely();
		}

		internal static void RegisterAllMessages()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			foreach (NetworkMessageFinalizerBase value in NetworkMessageFinalizers.Values)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(value.UniqueName, new HandleNamedMessageDelegate(value.Read));
			}
		}

		internal static void UnregisterAllMessages()
		{
			foreach (string key in NetworkMessageFinalizers.Keys)
			{
				UnregisterMessage(key, andRemoveHandler: false);
			}
		}

		public static void RegisterAll()
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				RegisterAll(typesFromAssembly[i]);
			}
		}

		public static void RegisterAll(Type type)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				if (type.BaseType.Name == "NetworkMessageHandler`1")
				{
					Type type2 = type.BaseType.GetGenericArguments()[0];
					RegisterInfoGeneric.MakeGenericMethod(type2).Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), type2), Activator.CreateInstance(type))
					});
				}
				else if (type.BaseType.Name == "NetworkMessageHandler")
				{
					RegisterInfo.Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)), Activator.CreateInstance(type))
					});
				}
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				customAttribute = methodInfo.GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					if (!methodInfo.IsStatic)
					{
						throw new Exception("Detected NetworkMessage attribute on non-static method. All NetworkMessages on methods must be static.");
					}
					if (methodInfo.GetParameters().Length == 1)
					{
						RegisterInfo.Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)))
						});
					}
					else
					{
						Type parameterType = methodInfo.GetParameters()[1].ParameterType;
						RegisterInfoGeneric.MakeGenericMethod(parameterType).Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), parameterType))
						});
					}
				}
			}
		}

		public static void UnregisterAll(bool andRemoveHandler = true)
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				UnregisterAll(typesFromAssembly[i], andRemoveHandler);
			}
		}

		public static void UnregisterAll(Type type, bool andRemoveHandler = true)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				UnregisterMessage(customAttribute.UniqueName, andRemoveHandler);
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < methods.Length; i++)
			{
				customAttribute = methods[i].GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					UnregisterMessage(customAttribute.UniqueName, andRemoveHandler);
				}
			}
		}

		public static void RegisterMessage<T>(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived) where T : class
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer<T> networkMessageFinalizer = new NetworkMessageFinalizer<T>(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void RegisterMessage(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer networkMessageFinalizer = new NetworkMessageFinalizer(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void UnregisterMessage(string uniqueName, bool andRemoveHandler = true)
		{
			if ((!andRemoveHandler && NetworkMessageFinalizers.ContainsKey(uniqueName)) || (andRemoveHandler && NetworkMessageFinalizers.Remove(uniqueName)))
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName);
			}
		}

		public static void Broadcast<T>(string uniqueName, T @object) where T : class
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer<T> networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send(@object);
			}
		}

		public static void Broadcast(string uniqueName)
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send();
			}
		}

		internal static void Init()
		{
			RegisterNetworkMessages += delegate
			{
				//IL_0041: 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_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>c.<>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//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_003d: Unknown result type (might be due to invalid IL or missing references)
							//IL_0043: Unknown result type (might be due to invalid IL or missing references)
							//IL_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>c.<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			};
			UnregisterNetworkMessages += delegate
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			};
			SetupNetworking();
			RegisterAll();
			LC_API.ServerAPI.Networking.InitializeLegacyNetworking();
		}

		internal static void SetupNetworking()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	public class NetworkMessage : Attribute
	{
		public string UniqueName { get; }

		public bool RelayToSelf { get; }

		public NetworkMessage(string uniqueName, bool relayToSelf = false)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
		}
	}
	public abstract class NetworkMessageHandler<T> where T : class
	{
		public abstract void Handler(ulong sender, T message);
	}
	public abstract class NetworkMessageHandler
	{
		public abstract void Handler(ulong sender);
	}
	internal abstract class NetworkMessageFinalizerBase
	{
		internal abstract string UniqueName { get; }

		internal abstract bool RelayToSelf { get; }

		public abstract void Read(ulong sender, FastBufferReader reader);
	}
	internal class NetworkMessageFinalizer : NetworkMessageFinalizerBase
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send()
		{
			//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_0091: 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)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater());
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender);
			}
		}

		private IEnumerator SendLater()
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send();
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//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)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageFinalizer<T> : NetworkMessageFinalizerBase where T : class
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong, T> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send(T obj)
		{
			//IL_0069: 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_009d: 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)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj));
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender, networkMessageWrapper.Message.ToObject<T>());
			}
		}

		private IEnumerator SendLater(T obj)
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send(obj);
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//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)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageWrapper
	{
		public string UniqueName { get; set; }

		public ulong Sender { get; set; }

		public byte[] Message { get; set; }

		internal NetworkMessageWrapper(string uniqueName, ulong sender)
		{
			UniqueName = uniqueName;
			Sender = sender;
		}

		internal NetworkMessageWrapper(string uniqueName, ulong sender, byte[] message)
		{
			UniqueName = uniqueName;
			Sender = sender;
			Message = message;
		}

		internal NetworkMessageWrapper()
		{
		}
	}
	internal static class RegisterPatch
	{
		internal static void Postfix()
		{
			Network.OnRegisterNetworkMessages();
		}
	}
	internal static class UnregisterPatch
	{
		internal static void Postfix()
		{
			Network.OnUnregisterNetworkMessages();
		}
	}
}
namespace LC_API.Networking.Serializers
{
	public struct Vector2S
	{
		private Vector2? v2;

		public float x { get; set; }

		public float y { get; set; }

		[JsonIgnore]
		public Vector2 vector2
		{
			get
			{
				//IL_002f: 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 (!v2.HasValue)
				{
					v2 = new Vector2(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2S(float x, float y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2(Vector2S vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2S(Vector2 vector2)
		{
			//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)
			return new Vector2S(vector2.x, vector2.y);
		}
	}
	public struct Vector2IntS
	{
		private Vector2Int? v2;

		public int x { get; set; }

		public int y { get; set; }

		[JsonIgnore]
		public Vector2Int vector2
		{
			get
			{
				//IL_002f: 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 (!v2.HasValue)
				{
					v2 = new Vector2Int(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2IntS(int x, int y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2Int(Vector2IntS vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2IntS(Vector2Int vector2)
		{
			return new Vector2IntS(((Vector2Int)(ref vector2)).x, ((Vector2Int)(ref vector2)).y);
		}
	}
	public struct Vector3S
	{
		private Vector3? v3;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		[JsonIgnore]
		public Vector3 vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3S(float x, float y, float z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3(Vector3S vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3S(Vector3 vector3)
		{
			//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 Vector3S(vector3.x, vector3.y, vector3.z);
		}
	}
	public struct Vector3IntS
	{
		private Vector3Int? v3;

		public int x { get; set; }

		public int y { get; set; }

		public int z { get; set; }

		[JsonIgnore]
		public Vector3Int vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3Int(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3IntS(int x, int y, int z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3Int(Vector3IntS vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3IntS(Vector3Int vector3)
		{
			return new Vector3IntS(((Vector3Int)(ref vector3)).x, ((Vector3Int)(ref vector3)).y, ((Vector3Int)(ref vector3)).z);
		}
	}
	public struct Vector4S
	{
		private Vector4? v4;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Vector4 Vector4
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!v4.HasValue)
				{
					v4 = new Vector4(x, y, z, w);
				}
				return v4.Value;
			}
		}

		public Vector4S(float x, float y, float z, float w)
		{
			v4 = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Vector4(Vector4S vector4S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector4S.Vector4;
		}

		public static implicit operator Vector4S(Vector4 vector4)
		{
			//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 Vector4S(vector4.x, vector4.y, vector4.z, vector4.w);
		}
	}
	public struct QuaternionS
	{
		private Quaternion? q;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Quaternion Quaternion
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!q.HasValue)
				{
					q = new Quaternion(x, y, z, w);
				}
				return q.Value;
			}
		}

		public QuaternionS(float x, float y, float z, float w)
		{
			q = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Quaternion(QuaternionS quaternionS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return quaternionS.Quaternion;
		}

		public static implicit operator QuaternionS(Quaternion quaternion)
		{
			//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 QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
		}
	}
	public struct ColorS
	{
		private Color? c;

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

		[JsonIgnore]
		public Color Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color(r, g, b, a);
				}
				return c.Value;
			}
		}

		public ColorS(float r, float g, float b, float a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color(ColorS colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator ColorS(Color color)
		{
			//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 ColorS(color.r, color.g, color.b, color.a);
		}
	}
	public struct Color32S
	{
		private Color32? c;

		public byte r { get; set; }

		public byte g { get; set; }

		public byte b { get; set; }

		public byte a { get; set; }

		[JsonIgnore]
		public Color32 Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color32(r, g, b, a);
				}
				return c.Value;
			}
		}

		public Color32S(byte r, byte g, byte b, byte a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color32(Color32S colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator Color32S(Color32 color)
		{
			//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 Color32S(color.r, color.g, color.b, color.a);
		}
	}
	public struct RayS
	{
		private Ray? r;

		public Vector3S origin { get; set; }

		public Vector3S direction { get; set; }

		[JsonIgnore]
		public Ray Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray((Vector3)origin, (Vector3)direction);
				}
				return r.Value;
			}
		}

		public RayS(Vector3 origin, Vector3 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray(RayS rayS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return rayS.Ray;
		}

		public static implicit operator RayS(Ray ray)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return new RayS(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction);
		}
	}
	public struct Ray2DS
	{
		private Ray2D? r;

		public Vector2S origin { get; set; }

		public Vector2S direction { get; set; }

		[JsonIgnore]
		public Ray2D Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray2D((Vector2)origin, (Vector2)direction);
				}
				return r.Value;
			}
		}

		public Ray2DS(Vector2 origin, Vector2 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray2D(Ray2DS ray2DS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return ray2DS.Ray;
		}

		public static implicit operator Ray2DS(Ray2D ray2D)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return new Ray2DS(((Ray2D)(ref ray2D)).origin, ((Ray2D)(ref ray2D)).direction);
		}
	}
}
namespace LC_API.ManualPatches
{
	internal static class ServerPatch
	{
		internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if ((int)result != 1)
			{
				Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance);
			}
			__instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString();
			Plugin.Log.LogMessage((object)"server pre-setup success");
			return true;
		}

		internal static bool CacheMenuManager(MenuManager __instance)
		{
			LC_APIManager.MenuManager = __instance;
			return true;
		}

		internal static bool ChatCommands(HUDManager __instance, CallbackContext context)
		{
			if (__instance.chatTextField.text.ToLower().Contains("/modcheck"))
			{
				CheatDatabase.OtherPlayerCheatDetector();
				return false;
			}
			return true;
		}

		internal static void GameNetworkManagerAwake(GameNetworkManager __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				ModdedServer.GameVersion = __instance.gameVersionNum;
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI
{
	public static class GameState
	{
		private static readonly Action NothingAction = delegate
		{
		};

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

		internal static void GSUpdate()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				if (StartOfRound.Instance.shipHasLanded && ShipState != ShipState.OnMoon)
				{
					ShipState = ShipState.OnMoon;
					GameState.LandOnMoon.InvokeActionSafe();
				}
				if (StartOfRound.Instance.inShipPhase && ShipState != 0)
				{
					ShipState = ShipState.InOrbit;
					GameState.WentIntoOrbit.InvokeActionSafe();
				}
				if (StartOfRound.Instance.shipIsLeaving && ShipState != ShipState.LeavingMoon)
				{
					ShipState = ShipState.LeavingMoon;
					GameState.ShipStartedLeaving.InvokeActionSafe();
				}
				if (AlivePlayerCount < StartOfRound.Instance.livingPlayers)
				{
					GameState.PlayerDied.InvokeActionSafe();
				}
				AlivePlayerCount = StartOfRound.Instance.livingPlayers;
			}
		}

		static GameState()
		{
			GameState.PlayerDied = NothingAction;
			GameState.LandOnMoon = NothingAction;
			GameState.WentIntoOrbit = NothingAction;
			GameState.ShipStartedLeaving = NothingAction;
		}
	}
	[Obsolete("Use Player::QueueTip instead.")]
	public class GameTips
	{
		private static List<string> tipHeaders = new List<string>();

		private static List<string> tipBodys = new List<string>();

		private static float lastMessageTime;

		public static void ShowTip(string header, string body)
		{
			tipHeaders.Add(header);
			tipBodys.Add(body);
		}

		public static void UpdateInternal()
		{
			lastMessageTime -= Time.deltaTime;
			if ((tipHeaders.Count > 0) & (lastMessageTime < 0f))
			{
				lastMessageTime = 5f;
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1");
				}
				tipHeaders.RemoveAt(0);
				tipBodys.RemoveAt(0);
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI.Features
{
	public class Item : NetworkBehaviour
	{
		private bool hasNewProps;

		internal static GameObject ItemNetworkPrefab { get; set; }

		public static Dictionary<GrabbableObject, Item> Dictionary { get; } = new Dictionary<GrabbableObject, Item>();


		public static IReadOnlyCollection<Item> List => Dictionary.Values;

		public GrabbableObject GrabbableObject { get; private set; }

		public Item ItemProperties => GrabbableObject.itemProperties;

		public ScanNodeProperties ScanNodeProperties { get; set; }

		public bool IsHeld => GrabbableObject.isHeld;

		public bool IsTwoHanded => ItemProperties.twoHanded;

		public Player Holder
		{
			get
			{
				if (!IsHeld)
				{
					return null;
				}
				if (!Player.Dictionary.TryGetValue(GrabbableObject.playerHeldBy, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public string Name
		{
			get
			{
				return ItemProperties.itemName;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = value;
				OverrideTooltips(oldName, value.ToLower());
				ScanNodeProperties.headerText = value;
				SetGrabbableNameClientRpc(value);
			}
		}

		public Vector3 Position
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.position;
			}
			set
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: 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_0036: 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_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item position on client.");
				}
				GrabbableObject.startFallingPosition = value;
				GrabbableObject.targetFloorPosition = value;
				((Component)GrabbableObject).transform.position = value;
				SetItemPositionClientRpc(value);
			}
		}

		public Quaternion Rotation
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.rotation;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.rotation = value;
			}
		}

		public Vector3 Scale
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.localScale;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.localScale = value;
			}
		}

		public bool IsScrap
		{
			get
			{
				return ItemProperties.isScrap;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				CloneProperties();
				ItemProperties.isScrap = value;
				SetIsScrapClientRpc(value);
			}
		}

		public int ScrapValue
		{
			get
			{
				return GrabbableObject.scrapValue;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set scrap value on client.");
				}
				GrabbableObject.SetScrapValue(value);
				SetScrapValueClientRpc(value);
			}
		}

		[ClientRpc]
		private void SetGrabbableNameClientRpc(string name)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(66243798u, val, (RpcDelivery)0);
				bool flag = name != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(name, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 66243798u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = name;
				OverrideTooltips(oldName, name.ToLower());
				ScanNodeProperties.headerText = name;
			}
		}

		private void OverrideTooltips(string oldName, string newName)
		{
			for (int i = 0; i < ItemProperties.toolTips.Length; i++)
			{
				ItemProperties.toolTips[i] = ItemProperties.toolTips[i].ReplaceWithCase(oldName, newName);
			}
			if (IsHeld && (Object)(object)Holder == (Object)(object)Player.LocalPlayer)
			{
				GrabbableObject.SetControlTipsForItem();
			}
		}

		[ClientRpc]
		private void SetItemPositionClientRpc(Vector3 pos)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(949135576u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref pos);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 949135576u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.startFallingPosition = pos;
					GrabbableObject.targetFloorPosition = pos;
					((Component)GrabbableObject).transform.position = pos;
				}
			}
		}

		public void SetAndSyncRotation(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item rotation from client.");
			}
			SetItemRotationClientRpc(rotation);
		}

		[ClientRpc]
		private void SetItemRotationClientRpc(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1528367091u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref rotation);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1528367091u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Rotation = rotation;
				}
			}
		}

		public void SetAndSyncScale(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item scale from client.");
			}
			SetItemScaleClientRpc(scale);
		}

		[ClientRpc]
		private void SetItemScaleClientRpc(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2688253945u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref scale);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2688253945u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Scale = scale;
				}
			}
		}

		[ClientRpc]
		private void SetIsScrapClientRpc(bool isScrap)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4227417717u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref isScrap, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4227417717u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					CloneProperties();
					ItemProperties.isScrap = isScrap;
				}
			}
		}

		[ClientRpc]
		private void SetScrapValueClientRpc(int scrapValue)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3866863385u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, scrapValue);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3866863385u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.SetScrapValue(scrapValue);
				}
			}
		}

		public void RemoveFromHolder(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_004f: 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)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to remove item from player on client.");
			}
			if (IsHeld)
			{
				((NetworkBehaviour)this).NetworkObject.RemoveOwnership();
				Holder.Inventory.RemoveItem(this);
				RemoveFromHolderClientRpc();
				Position = position;
				Rotation = rotation;
			}
		}

		[ClientRpc]
		private void RemoveFromHolderClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1050513218u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1050513218u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && IsHeld)
				{
					Holder.Inventory.RemoveItem(this);
				}
			}
		}

		public void EnablePhysics(bool enable)
		{
			GrabbableObject.EnablePhysics(enable);
		}

		public void EnableMeshes(bool enable)
		{
			GrabbableObject.EnableItemMeshes(enable);
		}

		public void FallToGround(bool randomizePosition = false)
		{
			GrabbableObject.FallToGround(randomizePosition);
		}

		public bool PocketItem()
		{
			if (!IsHeld || (Object)(object)Holder.HeldItem != (Object)(object)this || IsTwoHanded)
			{
				return false;
			}
			GrabbableObject.PocketItem();
			return true;
		}

		public bool GiveTo(Player player, bool switchTo = true)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to give item to player on client.");
			}
			return player.Inventory.TryAddItem(this, switchTo);
		}

		public void InitializeScrap()
		{
			if (RoundManager.Instance.AnomalyRandom != null)
			{
				InitializeScrap((int)((float)RoundManager.Instance.AnomalyRandom.Next(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
			else
			{
				InitializeScrap((int)((float)Random.Range(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
		}

		public void InitializeScrap(int scrapValue)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to initialize scrap on client.");
			}
			ScrapValue = scrapValue;
			InitializeScrapClientRpc();
		}

		[ClientRpc]
		private void InitializeScrapClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1334565671u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1334565671u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			MeshFilter val3 = default(MeshFilter);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshFilter>(ref val3) && ItemProperties.meshVariants != null && ItemProperties.meshVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					val3.mesh = ItemProperties.meshVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.meshVariants.Length)];
				}
				else
				{
					val3.mesh = ItemProperties.meshVariants[0];
				}
			}
			MeshRenderer val4 = default(MeshRenderer);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshRenderer>(ref val4) && ItemProperties.materialVariants != null && ItemProperties.materialVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.materialVariants.Length)];
				}
				else
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[0];
				}
			}
		}

		public static Item CreateAndSpawnItem(string itemName, bool andInitialize = true, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and spawn item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, position, rotation);
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				return component;
			}
			return null;
		}

		public static Item CreateAndGiveItem(string itemName, Player player, bool andInitialize = true, bool switchTo = true)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and give item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, Vector3.zero, default(Quaternion));
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				component.GiveTo(player, switchTo);
				return component;
			}
			return null;
		}

		private void Awake()
		{
			GrabbableObject = ((Component)this).GetComponent<GrabbableObject>();
			ScanNodeProperties = ((Component)GrabbableObject).gameObject.GetComponentInChildren<ScanNodeProperties>();
			Dictionary.Add(GrabbableObject, this);
		}

		private void CloneProperties()
		{
			Item itemProperties = Object.Instantiate<Item>(ItemProperties);
			if (hasNewProps)
			{
				Object.Destroy((Object)(object)ItemProperties);
			}
			GrabbableObject.itemProperties = itemProperties;
			hasNewProps = true;
		}

		public override void OnDestroy()
		{
			Dictionary.Remove(GrabbableObject);
			((NetworkBehaviour)this).OnDestroy();
		}

		public static Item GetOrAdd(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return ((Component)grabbableObject).gameObject.AddComponent<Item>();
		}

		public static Item Get(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return null;
		}

		public static bool TryGet(GrabbableObject grabbableObject, out Item item)
		{
			return Dictionary.TryGetValue(grabbableObject, out item);
		}

		public static Item Get(ulong netId)
		{
			return List.FirstOrDefault((Item i) => ((NetworkBehaviour)i).NetworkObjectId == netId);
		}

		public static bool TryGet(ulong netId, out Item item)
		{
			item = Get(netId);
			return (Object)(object)item != (Object)null;
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_Item()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(66243798u, new RpcReceiveHandler(__rpc_handler_66243798));
			NetworkManager.__rpc_func_table.Add(949135576u, new RpcReceiveHandler(__rpc_handler_949135576));
			NetworkManager.__rpc_func_table.Add(1528367091u, new RpcReceiveHandler(__rpc_handler_1528367091));
			NetworkManager.__rpc_func_table.Add(2688253945u, new RpcReceiveHandler(__rpc_handler_2688253945));
			NetworkManager.__rpc_func_table.Add(4227417717u, new RpcReceiveHandler(__rpc_handler_4227417717));
			NetworkManager.__rpc_func_table.Add(3866863385u, new RpcReceiveHandler(__rpc_handler_3866863385));
			NetworkManager.__rpc_func_table.Add(1050513218u, new RpcReceiveHandler(__rpc_handler_1050513218));
			NetworkManager.__rpc_func_table.Add(1334565671u, new RpcReceiveHandler(__rpc_handler_1334565671));
		}

		private static void __rpc_handler_66243798(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string grabbableNameClientRpc = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref grabbableNameClientRpc, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetGrabbableNameClientRpc(grabbableNameClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_949135576(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemPositionClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemPositionClientRpc(itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1528367091(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Quaternion itemRotationClientRpc = default(Quaternion);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemRotationClientRpc(itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2688253945(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemScaleClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemScaleClientRpc(itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4227417717(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool isScrapClientRpc = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref isScrapClientRpc, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetIsScrapClientRpc(isScrapClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3866863385(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int scrapValueClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetScrapValueClientRpc(scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1050513218(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).RemoveFromHolderClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1334565671(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).InitializeScrapClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "Item";
		}
	}
	public class Player : NetworkBehaviour
	{
		public class PlayerInventory : NetworkBehaviour
		{
			public Player Player { get; private set; }

			public Item[] Items => Player.PlayerController.ItemSlots.Select((GrabbableObject i) => (!((Object)(object)i != (Object)null)) ? null : Item.Dictionary[i]).ToArray();

			public int CurrentSlot
			{
				get
				{
					return Player.PlayerController.currentItemSlot;
				}
				set
				{
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					if (Player.IsLocalPlayer)
					{
						SetSlotServerRpc(value);
					}
					else if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
					{
						SetSlotClientRpc(value);
					}
				}
			}

			[ServerRpc(RequireOwnership = false)]
			private void SetSlotServerRpc(int slot, ServerRpcParams serverRpcParams = default(ServerRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
					{
						FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val, slot);
						((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId)
					{
						SetSlotClientRpc(slot);
					}
				}
			}

			[ClientRpc]
			private void SetSlotClientRpc(int slot)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: 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)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						ClientRpcParams val = default(ClientRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2977994897u, val, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val2, slot);
						((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2977994897u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						Player.PlayerController.SwitchToItemSlot(slot, (GrabbableObject)null);
					}
				}
			}

			public int GetFirstEmptySlot()
			{
				return Player.PlayerController.FirstEmptyItemSlot();
			}

			public bool TryGetFirstEmptySlot(out int slot)
			{
				slot = Player.PlayerController.FirstEmptyItemSlot();
				return slot != -1;
			}

			public bool TryAddItem(Item item, bool switchTo = true)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (TryGetFirstEmptySlot(out var slot))
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true)
			{
				//IL_007a: 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_0083: 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)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null)
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
		

BepInEx/plugins/AlexCodesGames-AdditionalContentFramework/AdditionalContentFramework.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AdditionalContentFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdditionalContentFramework")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a49abfd9-fde7-4c8d-9798-d9cbe51418e3")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AdditionalContentFramework;

[Serializable]
public class AdditionalSuitDef
{
	public string suitID;

	public string suitName;

	public string suitTexture;
}
[Serializable]
public class AdditionalContentModule
{
	public string resourceFolder;

	public List<AdditionalSuitDef> suitDefList = new List<AdditionalSuitDef>();

	public AdditionalContentModule(string folder)
	{
		resourceFolder = folder;
	}
}
[BepInPlugin("ACS.AdditionalContentFramework", "AdditionalContentFramework", "1.0.3")]
public class AdditionalContentFrameworkBase : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class acgAdditionalContentPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void acsAdditionalContentPatch(StartOfRound __instance)
		{
			try
			{
				if (IsContentLoaded)
				{
					return;
				}
				AddLog("finding suit prefab...");
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val = __instance.unlockablesList.unlockables[i];
					if ((Object)(object)val.suitMaterial != (Object)null && val.alreadyUnlocked)
					{
						PrefabUnlockableSuit = val;
						AddLog("found suit prefab!");
						break;
					}
				}
				if (PrefabUnlockableSuit == null)
				{
					AddLog("ERROR: suit prefab was not found!");
					return;
				}
				AddLog("loading content modules...");
				string directoryName = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
				string[] directories = Directory.GetDirectories(directoryName);
				string[] array = directories;
				foreach (string path in array)
				{
					string[] directories2 = Directory.GetDirectories(path);
					string[] array2 = directories2;
					foreach (string path2 in array2)
					{
						DirectoryInfo directoryInfo = new DirectoryInfo(path2);
						if (directoryInfo.Name.StartsWith("res"))
						{
							LoadContentModule(path2);
						}
					}
					DirectoryInfo directoryInfo2 = new DirectoryInfo(path);
					if (directoryInfo2.Name.StartsWith("res"))
					{
						LoadContentModule(path);
					}
				}
				AddLog("loaded content modules! (count=" + ContentModules.Count + ")");
				AddLog("applying content modules...");
				foreach (AdditionalContentModule contentModule in ContentModules)
				{
					ApplyContentModule(__instance, contentModule);
				}
				AddLog("applied content modules!");
				IsContentLoaded = true;
			}
			catch (Exception ex)
			{
				AddLog("failed to load suits into lobby!\nERROR: " + ex);
			}
		}
	}

	private static AdditionalContentFrameworkBase Instance;

	private const string modGUID = "ACS.AdditionalContentFramework";

	private const string modName = "AdditionalContentFramework";

	private const string modVersion = "1.0.3";

	private readonly Harmony harmony = new Harmony("ACS.AdditionalContentFramework");

	private static ManualLogSource mls;

	public static bool IsContentLoaded = false;

	public static UnlockableItem PrefabUnlockableSuit = null;

	public static List<AdditionalContentModule> ContentModules = new List<AdditionalContentModule>();

	public string ModGUID => "ACS.AdditionalContentFramework";

	public string ModName => "AdditionalContentFramework";

	public string ModVersion => "1.0.3";

	public static void AddLog(string log)
	{
		mls.LogInfo((object)("AdditionalContentFramework - " + log));
	}

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		mls = Logger.CreateLogSource("ACS.AdditionalContentFramework");
		AddLog("initializing...");
		harmony.PatchAll();
		AddLog("initialized!");
	}

	public static AdditionalSuitDef LoadContentPiece_Suit(string defStr)
	{
		try
		{
			return JsonUtility.FromJson<AdditionalSuitDef>(defStr);
		}
		catch (Exception ex)
		{
			AddLog("failed to load content module piece (suitDef='" + defStr + "')!\nERROR: " + ex);
			return null;
		}
	}

	public static void LoadContentModule(string path)
	{
		try
		{
			AddLog("attempting to load suits from path:" + path);
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path);
			string text2 = Path.Combine(text, "suit-defs.json");
			AddLog("attempting to parse json file: " + text2);
			string text3 = File.ReadAllText(text2);
			if (text3 == null)
			{
				AddLog("ERROR: json file was not found or invalid");
				return;
			}
			AdditionalContentModule additionalContentModule = new AdditionalContentModule(text);
			string[] array = text3.Split(new char[1] { '[' });
			array = array[1].Split(new char[1] { ']' });
			array = array[0].Split(new char[1] { '{' });
			for (int i = 1; i < array.Length; i++)
			{
				string text4 = "{" + array[i].Trim();
				if (i != array.Length - 1)
				{
					text4 = text4.Substring(0, text4.Length - 1);
				}
				try
				{
					AdditionalSuitDef additionalSuitDef = JsonUtility.FromJson<AdditionalSuitDef>(text4);
					if (additionalSuitDef != null)
					{
						additionalContentModule.suitDefList.Add(additionalSuitDef);
						AddLog("\tloaded suit def: " + additionalSuitDef.suitName);
					}
				}
				catch (Exception ex)
				{
					AddLog("failed to load content module piece (json='" + text4 + "')!\nERROR: " + ex);
				}
			}
			ContentModules.Add(additionalContentModule);
			AddLog("finished loading suits from path:" + path);
		}
		catch (Exception ex2)
		{
			AddLog("failed to load content module!\nERROR: " + ex2);
		}
	}

	public static void ApplyContentModule(StartOfRound __instance, AdditionalContentModule suitDefManifest)
	{
		AddLog("applying additional content module from: " + suitDefManifest.resourceFolder + "...");
		foreach (AdditionalSuitDef suitDef in suitDefManifest.suitDefList)
		{
			AddSuitToRack(__instance, suitDef, suitDefManifest.resourceFolder);
		}
		AddLog("applyed additional content module from: " + suitDefManifest.resourceFolder + "!");
	}

	public static void AddSuitToRack(StartOfRound __instance, AdditionalSuitDef suitDef, string resourcePath)
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected O, but got Unknown
		AddLog("adding suit to rack {id=" + suitDef.suitID + ", name=" + suitDef.suitName + "}...");
		UnlockableItem val = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)PrefabUnlockableSuit));
		Texture2D val2 = new Texture2D(2, 2);
		ImageConversion.LoadImage(val2, File.ReadAllBytes(Path.Combine(resourcePath, suitDef.suitTexture)));
		Material val3 = Object.Instantiate<Material>(val.suitMaterial);
		val3.mainTexture = (Texture)(object)val2;
		val.suitMaterial = val3;
		val.unlockableName = suitDef.suitName;
		__instance.unlockablesList.unlockables.Add(val);
		AddLog("added suit to rack {id=" + suitDef.suitID + ", name=" + suitDef.suitName + "}! (new unlockable count is " + __instance.unlockablesList.unlockables.Count + ")");
	}
}

BepInEx/plugins/anormaltwig-LateCompany/LateCompanyV1.0.11.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("LateCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+878b025de15dcb31ad8b18422be344d7a766ca40")]
[assembly: AssemblyProduct("LateCompany")]
[assembly: AssemblyTitle("LateCompany")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 LateCompany
{
	public static class PluginInfo
	{
		public const string GUID = "twig.latecompany";

		public const string PrintName = "Late Company";

		public const string Version = "1.0.11";
	}
	[BepInPlugin("twig.latecompany", "Late Company", "1.0.11")]
	internal class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<bool> configLateJoinOrbitOnly;

		public static bool AllowJoiningWhileLanded = false;

		public static bool LobbyJoinable = true;

		public void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			configLateJoinOrbitOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Allow joining while landed", false, "Allow players to join while the ship is landed. (Will probably break some things)");
			AllowJoiningWhileLanded = configLateJoinOrbitOnly.Value;
			Harmony val = new Harmony("twig.latecompany");
			val.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)"Late Company loaded!");
		}

		public static void SetLobbyJoinable(bool joinable)
		{
			LobbyJoinable = joinable;
			GameNetworkManager.Instance.SetLobbyJoinable(joinable);
			QuickMenuManager val = Object.FindObjectOfType<QuickMenuManager>();
			if (Object.op_Implicit((Object)(object)val))
			{
				val.inviteFriendsTextAlpha.alpha = (joinable ? 1f : 0.2f);
			}
		}
	}
}
namespace LateCompany.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager), "LeaveLobbyAtGameStart")]
	[HarmonyWrapSafe]
	internal static class LeaveLobbyAtGameStart_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
	[HarmonyWrapSafe]
	internal static class ConnectionApproval_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(ref ConnectionApprovalRequest request, ref ConnectionApprovalResponse response)
		{
			if (request.ClientNetworkId != NetworkManager.Singleton.LocalClientId && Plugin.LobbyJoinable && response.Reason == "Game has already started!")
			{
				response.Reason = "";
				response.Approved = true;
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "DisableInviteFriendsButton")]
	internal static class DisableInviteFriendsButton_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")]
	internal static class InviteFriendsButton_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (Plugin.LobbyJoinable && !GameNetworkManager.Instance.disableSteam)
			{
				GameNetworkManager.Instance.InviteFriendsUI();
			}
			return false;
		}
	}
	internal class RpcEnum : NetworkBehaviour
	{
		public static int None => 0;

		public static int Client => 2;

		public static int Server => 1;
	}
	internal static class WeatherSync
	{
		public static bool DoOverride = false;

		public static LevelWeatherType CurrentWeather = (LevelWeatherType)(-1);
	}
	[HarmonyPatch(typeof(RoundManager), "__rpc_handler_1193916134")]
	[HarmonyWrapSafe]
	internal static class __rpc_handler_1193916134_Patch
	{
		public static FieldInfo RPCExecStage = typeof(NetworkBehaviour).GetField("__rpc_exec_stage", BindingFlags.Instance | BindingFlags.NonPublic);

		[HarmonyPrefix]
		private static bool Prefix(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0082: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if ((Object)(object)networkManager != (Object)null && networkManager.IsListening && !networkManager.IsHost)
			{
				try
				{
					int num = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref num);
					int num2 = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref num2);
					if (((FastBufferReader)(ref reader)).Position < ((FastBufferReader)(ref reader)).Length)
					{
						int num3 = default(int);
						ByteUnpacker.ReadValueBitPacked(reader, ref num3);
						num3 -= 255;
						if (num3 < 0)
						{
							throw new Exception("In case of emergency, break glass.");
						}
						WeatherSync.CurrentWeather = (LevelWeatherType)num3;
						WeatherSync.DoOverride = true;
					}
					RPCExecStage.SetValue(target, RpcEnum.Client);
					((RoundManager)((target is RoundManager) ? target : null)).GenerateNewLevelClientRpc(num, num2);
					RPCExecStage.SetValue(target, RpcEnum.None);
					return false;
				}
				catch
				{
					WeatherSync.DoOverride = false;
					((FastBufferReader)(ref reader)).Seek(0);
					return true;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SetToCurrentLevelWeather")]
	internal static class SetToCurrentLevelWeather_Patch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (WeatherSync.DoOverride)
			{
				RoundManager.Instance.currentLevel.currentWeather = WeatherSync.CurrentWeather;
				WeatherSync.DoOverride = false;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
	[HarmonyWrapSafe]
	internal static class OnPlayerConnectedClientRpc_Patch
	{
		public static MethodInfo BeginSendClientRpc = typeof(RoundManager).GetMethod("__beginSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic);

		public static MethodInfo EndSendClientRpc = typeof(RoundManager).GetMethod("__endSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic);

		[HarmonyPostfix]
		private static void Postfix(ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed)
		{
			//IL_0066: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_0093: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: 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_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected I4, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB val = instance.allPlayerScripts[assignedPlayerObjectId];
			if (instance.connectedPlayersAmount + 1 >= instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: false);
			}
			val.DisablePlayerModel(instance.allPlayerObjects[assignedPlayerObjectId], true, true);
			if (((NetworkBehaviour)instance).IsServer && !instance.inShipPhase)
			{
				RoundManager instance2 = RoundManager.Instance;
				ClientRpcParams val2 = default(ClientRpcParams);
				val2.Send = new ClientRpcSendParams
				{
					TargetClientIds = new List<ulong> { clientId }
				};
				ClientRpcParams val3 = val2;
				FastBufferWriter val4 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 1193916134u, val3, 0 });
				BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.randomMapSeed);
				BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.currentLevelID);
				BytePacker.WriteValueBitPacked(val4, instance2.currentLevel.currentWeather + 255);
				EndSendClientRpc.Invoke(instance2, new object[4] { val4, 1193916134u, val3, 0 });
				FastBufferWriter val5 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 2729232387u, val3, 0 });
				EndSendClientRpc.Invoke(instance2, new object[4] { val5, 2729232387u, val3, 0 });
			}
			instance.livingPlayers = instance.connectedPlayersAmount + 1;
			for (int i = 0; i < instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val6 = instance.allPlayerScripts[i];
				if (val6.isPlayerControlled && val6.isPlayerDead)
				{
					instance.livingPlayers--;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
	[HarmonyWrapSafe]
	internal static class OnPlayerDC_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (StartOfRound.Instance.inShipPhase || (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.shipHasLanded))
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
	internal static class SetShipReadyToLand_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class StartGame_Patch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			Plugin.SetLobbyJoinable(joinable: false);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnShipLandedMiscEvents")]
	internal static class OnShipLandedMiscEvents_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
	internal static class ShipLeave_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			Plugin.SetLobbyJoinable(joinable: false);
		}
	}
}

BepInEx/plugins/ControlCompany-ControlCompany/ControlCompany.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ControlCompany.Core;
using ControlCompany.Core.Config;
using ControlCompany.Core.Enemy;
using ControlCompany.Core.Enemy.NonStandardEnemy;
using ControlCompany.Core.Extentions;
using ControlCompany.Core.Input;
using ControlCompany.Core.UI;
using ControlCompany.Patches;
using Dissonance;
using GameNetcodeStuff;
using HarmonyLib;
using Steamworks.Data;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ControlCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ControlCompany")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dfed064e-ab44-4aa7-b361-7a59370d39a8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ControlCompany
{
	[BepInPlugin("ControlCompany.ControlCompany", "ControlCompany", "1.1.5")]
	public class ControlCompanyPlugin : BaseUnityPlugin
	{
		private const string modGUID = "ControlCompany.ControlCompany";

		private const string modName = "ControlCompany";

		private const string modVersion = "1.1.5";

		private readonly Harmony harmony = new Harmony("ControlCompany.ControlCompany");

		public static ControlCompanyPlugin Instance;

		internal ManualLogSource logger;

		private bool isInitialized = false;

		private bool ranInitializationScripts = false;

		private void Awake()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("ControlCompany.ControlCompany");
			logger.LogInfo((object)"Loaded ControlCompany. Patching.");
			ApplyPatches();
			logger.LogInfo((object)"Completed patching. Initializing.");
			GameObject val = new GameObject("control_company_config_manager");
			val.AddComponent<ConfigManager>();
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val);
			logger.LogInfo((object)"Completed initialization.");
			isInitialized = true;
		}

		private void ApplyPatches()
		{
			harmony.PatchAll(typeof(ControlCompanyPlugin));
			harmony.PatchAll(typeof(HUDManagerPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(EnemyAIPatch));
			harmony.PatchAll(typeof(TimeOfDayPatch));
			harmony.PatchAll(typeof(SoundManagerPatch));
			harmony.PatchAll(typeof(LobbyListPatch));
		}
	}
}
namespace ControlCompany.Patches
{
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		[HarmonyPatch("ChangeOwnershipOfEnemy")]
		[HarmonyPrefix]
		private static bool ChangeOwnershipOfEnemyPrefix(EnemyAI __instance, ref ulong newOwnerClientId)
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null && ControlCenter.Instance.CurrentMode == ControlCenter.Mode.ENEMY)
			{
				if ((Object)(object)ControlCenter.Instance.CurrentControlledEnemy != (Object)null)
				{
					ulong actualClientId = ControlCenter.Instance.GetHostPlayer().actualClientId;
					bool flag = actualClientId == newOwnerClientId || ControlCenter.Instance.CurrentControlledEnemy.IsAIControlled;
					EnemyController currentControlledEnemy = ControlCenter.Instance.CurrentControlledEnemy;
					if (((object)currentControlledEnemy).GetType() == typeof(EnemyAIController))
					{
						EnemyAIController enemyAIController = (EnemyAIController)ControlCenter.Instance.CurrentControlledEnemy;
						flag = flag || (Object)(object)enemyAIController.EnemyAI != (Object)(object)__instance;
					}
					return flag;
				}
				return true;
			}
			return true;
		}

		[HarmonyPatch("ChangeEnemyOwnerServerRpc")]
		[HarmonyPrefix]
		private static bool ChangeEnemyOwnerServerRpcPrefix(EnemyAI __instance, ref ulong clientId)
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null && ControlCenter.Instance.CurrentMode == ControlCenter.Mode.ENEMY)
			{
				if ((Object)(object)ControlCenter.Instance.CurrentControlledEnemy != (Object)null)
				{
					ulong actualClientId = ControlCenter.Instance.GetHostPlayer().actualClientId;
					bool flag = actualClientId == clientId || ControlCenter.Instance.CurrentControlledEnemy.IsAIControlled;
					EnemyController currentControlledEnemy = ControlCenter.Instance.CurrentControlledEnemy;
					if (((object)currentControlledEnemy).GetType() == typeof(EnemyAIController))
					{
						EnemyAIController enemyAIController = (EnemyAIController)ControlCenter.Instance.CurrentControlledEnemy;
						flag = flag || (Object)(object)enemyAIController.EnemyAI != (Object)(object)__instance;
					}
					return flag;
				}
				return true;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("CanPlayerScan")]
		[HarmonyPostfix]
		private static void CanPlayerScanPostfix(ref bool __result)
		{
			if (__result && (Object)(object)ControlCenter.Instance != (Object)null)
			{
				__result = ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
		}

		[HarmonyPatch("UpdateHealthUI")]
		[HarmonyPrefix]
		private static bool UpdateHealthUIPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("PlayerLookInput")]
		[HarmonyPrefix]
		private static bool PlayerLookInputPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(SoundManager))]
	internal class SoundManagerPatch
	{
		[HarmonyPatch("SetEarsRinging")]
		[HarmonyPrefix]
		private static bool SetEarsRingingPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("ShipHasLeft")]
		[HarmonyPrefix]
		private static void ShipHasLeftPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				ControlCenter.Instance.EndOfRoundCleanUp();
			}
		}

		[HarmonyPatch("StartGame")]
		[HarmonyPostfix]
		private static void StartGamePostfix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				ControlCenter.Instance.StartOfRoundInitialization();
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void CreateControlCenter()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			if (!ConfigManager.Instance.DisableModForSelf)
			{
				GameObject val = new GameObject("control_company_control_center");
				val.AddComponent<ControlCenter>();
				val.AddComponent<UIManager>();
			}
		}
	}
	internal class LobbyListPatch
	{
		public const char SERVER_NAME_FILTER = '\u200b';

		[HarmonyPatch(typeof(SteamLobbyManager), "loadLobbyListAndFilter")]
		[HarmonyPrefix]
		private static void FilterLobbyList(ref Lobby[] lobbyList, ref Lobby[] ___currentLobbyList)
		{
			if (!ConfigManager.Instance.HideControlCompanyEnabledServers)
			{
				return;
			}
			List<Lobby> list = ___currentLobbyList.ToList();
			list.RemoveAll(delegate(Lobby lobby)
			{
				string data = ((Lobby)(ref lobby)).GetData("name");
				bool flag = Enumerable.Contains(data, '\u200b');
				if (flag)
				{
				}
				return flag;
			});
			lobbyList = (___currentLobbyList = list.ToArray());
		}

		[HarmonyPatch(typeof(MenuManager), "ConfirmHostButton")]
		[HarmonyPrefix]
		private static void AddServerNameChar(MenuManager __instance)
		{
			string text = __instance.lobbyNameInputField.text;
			if (!Enumerable.Contains(text, '\u200b'))
			{
				string text2 = ((text.Length > 3) ? text.Insert(text.Length - 2, '\u200b'.ToString()) : ("\u200b" + text));
				__instance.lobbyNameInputField.text = text2;
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		[HarmonyPatch("VoteShipToLeaveEarly")]
		[HarmonyPrefix]
		private static bool VoteToLeaveEarly()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
}
namespace ControlCompany.Core
{
	internal static class Constants
	{
		public static Dictionary<int, string> ALL_LAYERS_DICT = (from index in Enumerable.Range(0, 32)
			where !string.IsNullOrEmpty(LayerMask.LayerToName(index))
			select index).ToDictionary((int index) => index, (int index) => LayerMask.LayerToName(index));

		public static LayerMask PLAYER_LOS_LAYER = LayerMask.op_Implicit(262144);

		public static LayerMask PLAYER_LAYER = LayerMask.op_Implicit(8);

		public static LayerMask PLAYER_VISOR_LAYER = LayerMask.op_Implicit(128);

		public static LayerMask ITERACTABLE_OBJ_LAYER = LayerMask.op_Implicit(512);

		public static LayerMask PROPS_LAYER = LayerMask.op_Implicit(64);

		public static LayerMask ENEMIES_LAYER = LayerMask.op_Implicit(524288);

		public static LayerMask PLAYER_RAGDOLL_LAYER = LayerMask.op_Implicit(1048576);

		public static LayerMask PHYSICS_OBJECT_LAYER = LayerMask.op_Implicit(4096);
	}
	internal class ControlCenter : MonoBehaviour
	{
		public enum Mode
		{
			HOST,
			GHOST,
			ENEMY
		}

		public static ControlCenter Instance;

		private CustomPlayerController ghostController;

		private GameObject ghost;

		private EnemyController currentControlledEnemy;

		private int currentTargetIndex = 0;

		private PlayerControllerB currentTarget;

		private Mode currentMode = Mode.HOST;

		private bool allowAllEnemies = false;

		private bool initialMicPushToTalkSetting = false;

		private bool isExtendedModeEnabled = false;

		private bool scrapSpawnMode = false;

		private int currentSpawnScrapPage = 0;

		private const int scrapSpawnPageSize = 10;

		private int currentSpawnEnemiesPage = 0;

		private const int spawnEnemiesPageSize = 12;

		private List<SpawnableEnemyWithRarity> currentSpawnableEnemyList = new List<SpawnableEnemyWithRarity>();

		private bool loadedConfig = false;

		private bool showUI = true;

		private float gameStartedTime = 0f;

		private bool inRoundEndPhase = false;

		private bool isGhostIndoors = false;

		private List<SpawnableEnemyWithRarity> allIndoorEnemies = new List<SpawnableEnemyWithRarity>();

		private List<SpawnableEnemyWithRarity> allOutdoorEnemies = new List<SpawnableEnemyWithRarity>();

		private List<SpawnableEnemyWithRarity> indoorEnemiesOfLevel = new List<SpawnableEnemyWithRarity>();

		private List<SpawnableEnemyWithRarity> outdoorEnemiesOfLevel = new List<SpawnableEnemyWithRarity>();

		public Mode CurrentMode => currentMode;

		public EnemyController CurrentControlledEnemy => currentControlledEnemy;

		public bool IsGhostIndoors
		{
			get
			{
				return isGhostIndoors;
			}
			set
			{
				isGhostIndoors = value;
			}
		}

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
		}

		private void OnEnable()
		{
			if (!loadedConfig)
			{
				loadedConfig = true;
				ConfigManager.Instance.LoadPlayerConfig(reload: true);
			}
		}

		private void Update()
		{
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			if (!IsGameStarted())
			{
				return;
			}
			if (((ButtonControl)InputKeys.TOGGLE_UI_KEY).wasPressedThisFrame)
			{
				showUI = !showUI;
			}
			gameStartedTime += Time.deltaTime;
			if (!IsHost() || inRoundEndPhase)
			{
				return;
			}
			if (((Object)(object)currentTarget == (Object)null || !currentTarget.isPlayerControlled || currentTarget.isPlayerDead) && GetAlivePlayers().Count > 0)
			{
				SetNextTargetPlayer(1);
			}
			if ((Object)(object)ghost == (Object)null)
			{
				GameObject val = new GameObject("ghost");
				ghostController = val.AddComponent<CustomPlayerController>();
				ghostController.Initialize(GetHostPlayer().playerActions, CustomPlayerController.CameraMode.FIRST_PERSON);
				ghost = val;
				ghost.SetActive(false);
				ControlCompanyPlugin.Instance.logger.LogInfo((object)"Creating ghost");
			}
			if (currentMode != 0)
			{
				GetHostPlayer().isTypingChat = true;
			}
			if (currentMode == Mode.GHOST)
			{
				if ((Object)(object)ghostController != (Object)null && ghostController.IsInitialized)
				{
					ChangeAudioListener(ghostController.AudioListener);
				}
			}
			else if (currentMode == Mode.ENEMY)
			{
				if (((Object)(object)currentControlledEnemy != (Object)null) & currentControlledEnemy.IsInitialized)
				{
					ChangeAudioListener(currentControlledEnemy.AudioListener);
				}
			}
			else if (currentMode == Mode.HOST)
			{
				ChangeAudioListener(GetHostPlayer().activeAudioListener);
			}
			InputUpdate();
		}

		private void InputUpdate()
		{
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_03df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			if (!IsGameStarted() || !IsHost() || inRoundEndPhase)
			{
				return;
			}
			if (((ButtonControl)InputKeys.EXTENDED_MODE_KEY).wasPressedThisFrame)
			{
				isExtendedModeEnabled = !isExtendedModeEnabled;
				allowAllEnemies = isExtendedModeEnabled;
				SetNextSpawnEnemiesPage(0);
			}
			switch (currentMode)
			{
			case Mode.ENEMY:
				if (!currentControlledEnemy.IsAIControlled && currentControlledEnemy.CanControlEnemy())
				{
					if (InputKeys.ENEMY_PRIMARY_SKILL_BUTTON.wasPressedThisFrame)
					{
						currentControlledEnemy.UsePrimarySkill();
					}
					else if (InputKeys.ENEMY_PRIMARY_SKILL_BUTTON.wasReleasedThisFrame)
					{
						currentControlledEnemy.ReleasePrimarySkill();
					}
					else if (InputKeys.ENEMY_SECONDARY_SKILL_BUTTON.wasPressedThisFrame)
					{
						currentControlledEnemy.UseSecondarySkill();
					}
					else if (InputKeys.ENEMY_SECONDARY_SKILL_BUTTON.wasReleasedThisFrame)
					{
						currentControlledEnemy.ReleaseSecondarySkill();
					}
					currentControlledEnemy.SetLockEnemyRotation(((ButtonControl)InputKeys.LOCK_ENEMY_ROTATION_KEY).isPressed);
				}
				if (((ButtonControl)InputKeys.EXIT_KEY).wasPressedThisFrame)
				{
					EnableGhost(enable: true, ((Component)currentControlledEnemy).transform.position);
					ghostController.EnableLight(isGhostIndoors);
					currentControlledEnemy.DestroyAndCleanUp();
					currentMode = Mode.GHOST;
				}
				else if (((ButtonControl)InputKeys.ENEMY_TOGGLE_AI_KEY).wasPressedThisFrame)
				{
					currentControlledEnemy.ToggleAIControl();
				}
				break;
			case Mode.HOST:
				if (((ButtonControl)InputKeys.HOST_GHOST_MODE_KEY).wasPressedThisFrame)
				{
					isGhostIndoors = IsTargetInside();
					EnableGhost(enable: true, ((Component)currentTarget).gameObject.transform.position);
					ghostController.EnableLight(isGhostIndoors);
					EnableHostPlayer(enable: false);
					currentMode = Mode.GHOST;
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_LEFT).wasPressedThisFrame)
				{
					SetNextTargetPlayer(-1);
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_RIGHT).wasPressedThisFrame)
				{
					SetNextTargetPlayer(1);
				}
				if (!isExtendedModeEnabled)
				{
					break;
				}
				if (((ButtonControl)InputKeys.HOST_TELEPORT_TO_ENTRANCE_KEY).wasPressedThisFrame)
				{
					if (!GetHostPlayer().isPlayerDead)
					{
						EntranceTeleport mainEntrance = GetMainEntrance(getMainEntranceThatIsOutside: true);
						if ((Object)(object)mainEntrance != (Object)null)
						{
							mainEntrance.TeleportPlayer();
						}
					}
				}
				else if (((ButtonControl)InputKeys.HOST_GIVE_CREDITS_KEY).wasPressedThisFrame)
				{
					Terminal obj = Object.FindObjectOfType<Terminal>();
					obj.groupCredits += 1000;
				}
				break;
			case Mode.GHOST:
				if (!scrapSpawnMode)
				{
					List<SpawnableEnemyWithRarity> pagedSpawnableEnemies = GetPagedSpawnableEnemies();
					for (int i = 0; i < InputKeys.GHOST_SPAWN_ENEMY_KEYS.Count && i < pagedSpawnableEnemies.Count; i++)
					{
						if (((ButtonControl)InputKeys.GHOST_SPAWN_ENEMY_KEYS[i]).wasPressedThisFrame)
						{
							currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], ghost.transform.position, ghost.transform.rotation);
							EnableGhost(enable: false);
							currentMode = Mode.ENEMY;
							break;
						}
					}
				}
				else
				{
					List<SpawnableItemWithRarity> list = ExtensionMethods.Chunk(GetSpawnableScraps(), 10).ToList()[currentSpawnScrapPage].ToList();
					for (int j = 0; j < InputKeys.GHOST_SPAWN_ENEMY_KEYS.Count && j < list.Count; j++)
					{
						if (((ButtonControl)InputKeys.GHOST_SPAWN_ENEMY_KEYS[j]).wasPressedThisFrame)
						{
							SpawnScrap(list[j], ghost.transform.position);
							break;
						}
					}
				}
				if (((ButtonControl)InputKeys.EXIT_KEY).wasPressedThisFrame)
				{
					EnableGhost(enable: false);
					EnableHostPlayer(enable: true);
					currentMode = Mode.HOST;
					GetHostPlayer().isTypingChat = false;
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_LEFT).wasPressedThisFrame)
				{
					SetNextSpawnEnemiesPage(-1);
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_RIGHT).wasPressedThisFrame)
				{
					SetNextSpawnEnemiesPage(1);
				}
				if (((ButtonControl)Keyboard.current.upArrowKey).wasPressedThisFrame)
				{
				}
				if (scrapSpawnMode && ((ButtonControl)Keyboard.current.downArrowKey).wasPressedThisFrame)
				{
					int num = GetSpawnableScraps().Count / 10;
					ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Total scraps: {GetSpawnableScraps().Count()}, final page of scrap: {num}");
					currentSpawnScrapPage++;
					if (currentSpawnScrapPage > num)
					{
						currentSpawnScrapPage = 0;
					}
				}
				break;
			}
		}

		private void ChangeAudioListener(AudioListener audioListener)
		{
			StartOfRound.Instance.audioListener = audioListener;
		}

		private EntranceTeleport GetMainEntrance(bool getMainEntranceThatIsOutside)
		{
			EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(false);
			foreach (EntranceTeleport val in array)
			{
				if (val.entranceId != 0)
				{
					continue;
				}
				if (getMainEntranceThatIsOutside)
				{
					if (val.isEntranceToBuilding)
					{
						return val;
					}
				}
				else if (!val.isEntranceToBuilding)
				{
					return val;
				}
			}
			return null;
		}

		private bool IsTargetInside()
		{
			return (Object)(object)currentTarget != (Object)null && currentTarget.isInsideFactory;
		}

		private void OnGUI()
		{
			if (!IsGameStarted() || !showUI)
			{
				return;
			}
			if (!IsHost())
			{
				if (gameStartedTime < 30f)
				{
					UIManager.Instance.RenderNotHostLabel(((InputControl)InputKeys.TOGGLE_UI_KEY).displayName);
				}
			}
			else
			{
				if (inRoundEndPhase)
				{
					return;
				}
				switch (currentMode)
				{
				case Mode.ENEMY:
					UIManager.Instance.RenderEnemyControls(((InputControl)InputKeys.ENEMY_PRIMARY_SKILL_BUTTON).shortDisplayName, ((InputControl)InputKeys.ENEMY_SECONDARY_SKILL_BUTTON).shortDisplayName, ((InputControl)InputKeys.ENEMY_TOGGLE_AI_KEY).displayName, ((InputControl)InputKeys.EXIT_KEY).displayName, currentControlledEnemy, GetHostPlayer());
					break;
				case Mode.HOST:
					UIManager.Instance.RenderHostControls(((InputControl)InputKeys.HOST_GHOST_MODE_KEY).displayName, ((InputControl)InputKeys.CYCLE_KEY_LEFT).displayName, ((InputControl)InputKeys.CYCLE_KEY_RIGHT).displayName, currentTarget, isExtendedModeEnabled, ((InputControl)InputKeys.HOST_GIVE_CREDITS_KEY).displayName, ((InputControl)InputKeys.HOST_TELEPORT_TO_ENTRANCE_KEY).displayName, ((InputControl)InputKeys.TOGGLE_UI_KEY).displayName);
					break;
				case Mode.GHOST:
				{
					bool showEnemyPaging = GetSpawnableEnemies(isGhostIndoors).Count > 12;
					List<IEnumerable<SpawnableItemWithRarity>> list = ExtensionMethods.Chunk(GetSpawnableScraps(), 10).ToList();
					List<SpawnableItemWithRarity> scraps = ((list.Count > 0) ? list[currentSpawnScrapPage].ToList() : new List<SpawnableItemWithRarity>());
					UIManager.Instance.RenderGhostControls(InputKeys.GHOST_SPAWN_ENEMY_KEYS.Select((KeyControl key) => ((InputControl)key).displayName).ToList(), ((InputControl)InputKeys.EXIT_KEY).displayName, ((InputControl)InputKeys.CYCLE_KEY_LEFT).displayName, ((InputControl)InputKeys.CYCLE_KEY_RIGHT).displayName, showEnemyPaging, GetPagedSpawnableEnemies(), scraps, GetHostPlayer(), scrapSpawnMode);
					break;
				}
				}
			}
		}

		private bool IsHostDead()
		{
			return GetHostPlayer().isPlayerDead;
		}

		private void EnableGhost(bool enable)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			EnableGhost(enable, Vector3.zero);
		}

		private void EnableGhost(bool enable, Vector3 position)
		{
			//IL_0012: 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_0027: 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)
			if (enable)
			{
				ghost.transform.position = position + new Vector3(0f, 0.5f, 0f);
				ghost.transform.rotation = Quaternion.identity;
				ghost.SetActive(true);
				ChangeAudioListener(ghostController.AudioListener);
				SetNextSpawnEnemiesPage(0);
			}
			else
			{
				ghost.SetActive(false);
			}
		}

		private void EnableHostPlayer(bool enable)
		{
			//IL_00a3: 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_003d: 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)
			PlayerControllerB hostPlayer = GetHostPlayer();
			MovementActions movement;
			if (enable)
			{
				if (ConfigManager.Instance.ForcePushToTalkWhileInMonsterMode)
				{
					ResetMicPushToTalk();
				}
				((Behaviour)GetHostPlayer().activeAudioListener).enabled = true;
				movement = hostPlayer.playerActions.Movement;
				((MovementActions)(ref movement)).PingScan.Enable();
				ChangeAudioListener(hostPlayer.activeAudioListener);
				((Behaviour)StartOfRound.Instance.activeCamera).enabled = true;
			}
			else
			{
				if (ConfigManager.Instance.ForcePushToTalkWhileInMonsterMode)
				{
					ForceMicPushToTalk();
				}
				((Behaviour)GetHostPlayer().activeAudioListener).enabled = false;
				movement = hostPlayer.playerActions.Movement;
				((MovementActions)(ref movement)).PingScan.Disable();
				((Behaviour)StartOfRound.Instance.activeCamera).enabled = false;
			}
		}

		private void EnablePlayer2DMics(bool enable, List<PlayerControllerB> players)
		{
			foreach (PlayerControllerB player in players)
			{
				if (player.isHostPlayerObject)
				{
					continue;
				}
				AudioSource currentVoiceChatAudioSource = player.currentVoiceChatAudioSource;
				if (enable)
				{
					if ((Object)(object)currentVoiceChatAudioSource != (Object)null)
					{
						currentVoiceChatAudioSource.spatialBlend = 0f;
					}
					player.currentVoiceChatIngameSettings.set2D = true;
					player.voicePlayerState.Volume = 1f;
				}
				else
				{
					if ((Object)(object)currentVoiceChatAudioSource != (Object)null)
					{
						currentVoiceChatAudioSource.spatialBlend = 1f;
					}
					player.currentVoiceChatIngameSettings.set2D = false;
					player.voicePlayerState.Volume = 0f;
				}
			}
		}

		private void SetNextTargetPlayer(int direction)
		{
			List<PlayerControllerB> alivePlayers = GetAlivePlayers();
			if (alivePlayers.Count == 0)
			{
				SetCurrentTargetToHost();
				ControlCompanyPlugin.Instance.logger.LogMessage((object)"Alive player count is zero");
			}
			else
			{
				currentTargetIndex += direction;
				if (currentTargetIndex >= alivePlayers.Count)
				{
					currentTargetIndex = 0;
				}
				else if (currentTargetIndex < 0)
				{
					currentTargetIndex = alivePlayers.Count - 1;
				}
				currentTargetIndex = Mathf.Clamp(currentTargetIndex, 0, alivePlayers.Count - 1);
				currentTarget = alivePlayers[currentTargetIndex];
			}
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Current target index: {currentTargetIndex}");
			ControlCompanyPlugin.Instance.logger.LogMessage((object)("Setting next target to: " + currentTarget?.playerUsername));
		}

		public void SetCurrentTargetToHost()
		{
			currentTargetIndex = 0;
			currentTarget = GetHostPlayer();
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Setting next target to host");
		}

		private void SetNextSpawnEnemiesPage(int direction)
		{
			List<SpawnableEnemyWithRarity> spawnableEnemies = GetSpawnableEnemies(isGhostIndoors);
			if (spawnableEnemies == null || spawnableEnemies.Count == 0)
			{
				currentSpawnableEnemyList = new List<SpawnableEnemyWithRarity>();
				return;
			}
			if (spawnableEnemies.Count > 12)
			{
				List<IEnumerable<SpawnableEnemyWithRarity>> list = ExtensionMethods.Chunk(spawnableEnemies, 12).ToList();
				currentSpawnEnemiesPage += direction;
				if (currentSpawnEnemiesPage >= list.Count)
				{
					currentSpawnEnemiesPage = 0;
				}
				else if (currentSpawnEnemiesPage < 0)
				{
					currentSpawnEnemiesPage = list.Count - 1;
				}
				currentSpawnEnemiesPage = Mathf.Clamp(currentSpawnEnemiesPage, 0, list.Count - 1);
			}
			else
			{
				currentSpawnEnemiesPage = 0;
			}
			currentSpawnableEnemyList = ExtensionMethods.Chunk(GetSpawnableEnemies(isGhostIndoors), 12).ToList()[currentSpawnEnemiesPage].ToList();
		}

		public void StartOfRoundInitialization()
		{
			allIndoorEnemies = GetAllIndoorEnemiesAcrossAllMapsList();
			allOutdoorEnemies = GetAllOutdoorEnemiesAcrossAllMapsList();
			indoorEnemiesOfLevel = new List<SpawnableEnemyWithRarity>(GetCurrentLevel().Enemies);
			outdoorEnemiesOfLevel = new List<SpawnableEnemyWithRarity>(GetCurrentLevel().OutsideEnemies);
			SpawnableEnemyWithRarity maskedEnemy = GetMaskedEnemy();
			indoorEnemiesOfLevel.Add(maskedEnemy);
			outdoorEnemiesOfLevel.Add(maskedEnemy);
			gameStartedTime = 0f;
			SetCurrentTargetToHost();
			ResetToDefault();
			inRoundEndPhase = false;
			initialMicPushToTalkSetting = IngamePlayerSettings.Instance.settings.pushToTalk;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Start of round initialization completed.");
		}

		public void EndOfRoundCleanUp()
		{
			ResetToDefault();
			inRoundEndPhase = true;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"End of round clean up completed.");
		}

		private void ResetToDefault()
		{
			StartOfRound.Instance.audioListener = GetHostPlayer().activeAudioListener;
			GetHostPlayer().isTypingChat = false;
			currentMode = Mode.HOST;
			if ((Object)(object)ghost != (Object)null)
			{
				Object.Destroy((Object)(object)ghost);
				ghost = null;
			}
			if ((Object)(object)currentControlledEnemy != (Object)null)
			{
				currentControlledEnemy.DestroyAndCleanUp();
			}
			currentSpawnableEnemyList = new List<SpawnableEnemyWithRarity>();
			currentSpawnEnemiesPage = 0;
			EnableHostPlayer(enable: true);
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Reset to default.");
		}

		public PlayerControllerB GetHostPlayer()
		{
			return RoundManager.Instance.playersManager.allPlayerObjects[0].GetComponentInChildren<PlayerControllerB>();
		}

		public List<PlayerControllerB> GetDeadPlayers()
		{
			return (from player in GetAllPlayers()
				where player.isPlayerDead
				select player).ToList();
		}

		public List<PlayerControllerB> GetAlivePlayers()
		{
			return (from player in GetAllPlayers()
				where !player.isPlayerDead
				select player).ToList();
		}

		public List<PlayerControllerB> GetAllPlayers()
		{
			List<PlayerControllerB> list = new List<PlayerControllerB>();
			GameObject[] allPlayerObjects = RoundManager.Instance.playersManager.allPlayerObjects;
			for (int i = 0; i < allPlayerObjects.Length; i++)
			{
				PlayerControllerB componentInChildren = allPlayerObjects[i].GetComponentInChildren<PlayerControllerB>();
				if ((Object)(object)componentInChildren != (Object)null && componentInChildren.isPlayerControlled)
				{
					list.Add(componentInChildren);
				}
			}
			return list;
		}

		public bool DoesCurrentLevelExist()
		{
			return (Object)(object)GetCurrentLevel() != (Object)null;
		}

		public bool IsGameStarted()
		{
			return (Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.currentLevel != (Object)null && (Object)(object)GameNetworkManager.Instance != (Object)null && GameNetworkManager.Instance.gameHasStarted && (Object)(object)StartOfRound.Instance != (Object)null && !StartOfRound.Instance.inShipPhase;
		}

		public SelectableLevel GetCurrentLevel()
		{
			return RoundManager.Instance.currentLevel;
		}

		public StartOfRound GetPlayersManager()
		{
			return RoundManager.Instance.playersManager;
		}

		private bool IsHost()
		{
			return ((NetworkBehaviour)RoundManager.Instance).IsHost;
		}

		public List<SpawnableItemWithRarity> GetSpawnableScraps()
		{
			return GetCurrentLevel().spawnableScrap;
		}

		public List<SpawnableEnemyWithRarity> GetPagedSpawnableEnemies()
		{
			return currentSpawnableEnemyList;
		}

		public List<SpawnableEnemyWithRarity> GetSpawnableEnemies(bool isIndoor)
		{
			List<SpawnableEnemyWithRarity> list = ((!isIndoor) ? GetSpawnableOutdoorEnemies() : GetSpawnableIndoorEnemies());
			if (list == null || list.Count == 0)
			{
				list = new List<SpawnableEnemyWithRarity>();
			}
			return list;
		}

		public List<SpawnableEnemyWithRarity> GetSpawnableIndoorEnemies()
		{
			return allowAllEnemies ? GetIndoorEnemyList() : GetAllowListedIndoorEnemies();
		}

		public List<SpawnableEnemyWithRarity> GetAllowListedIndoorEnemies()
		{
			return GetIndoorEnemyList().Where(delegate(SpawnableEnemyWithRarity enemy)
			{
				EnemyAI componentInChildren = enemy.enemyType.enemyPrefab.GetComponentInChildren<EnemyAI>();
				return !((Object)(object)componentInChildren == (Object)null) && componentInChildren.IsEnemyAllowlisted();
			}).ToList();
		}

		public List<SpawnableEnemyWithRarity> GetIndoorEnemyList()
		{
			return allowAllEnemies ? allIndoorEnemies : indoorEnemiesOfLevel;
		}

		public List<SpawnableEnemyWithRarity> GetAllIndoorEnemiesAcrossAllMapsList()
		{
			HashSet<string> hashSet = new HashSet<string>();
			List<SpawnableEnemyWithRarity> list = new List<SpawnableEnemyWithRarity>();
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
				{
					if (!hashSet.Contains(enemy.enemyType.enemyName))
					{
						hashSet.Add(enemy.enemyType.enemyName);
						list.Add(enemy);
					}
				}
			}
			return list;
		}

		public List<SpawnableEnemyWithRarity> GetSpawnableOutdoorEnemies()
		{
			return allowAllEnemies ? GetOutdoorEnemyList() : GetAllowListedOutdoorEnemies();
		}

		public List<SpawnableEnemyWithRarity> GetAllowListedOutdoorEnemies()
		{
			return GetOutdoorEnemyList().Where(delegate(SpawnableEnemyWithRarity enemy)
			{
				EnemyAI componentInChildren = enemy.enemyType.enemyPrefab.GetComponentInChildren<EnemyAI>();
				return !((Object)(object)componentInChildren == (Object)null) && componentInChildren.IsEnemyAllowlisted();
			}).ToList();
		}

		public List<SpawnableEnemyWithRarity> GetOutdoorEnemyList()
		{
			return allowAllEnemies ? allOutdoorEnemies : outdoorEnemiesOfLevel;
		}

		public List<SpawnableEnemyWithRarity> GetAllOutdoorEnemiesAcrossAllMapsList()
		{
			if (GetCurrentLevel().OutsideEnemies.Count == 0)
			{
				return new List<SpawnableEnemyWithRarity>();
			}
			HashSet<string> hashSet = new HashSet<string>();
			List<SpawnableEnemyWithRarity> list = new List<SpawnableEnemyWithRarity>();
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				foreach (SpawnableEnemyWithRarity outsideEnemy in val.OutsideEnemies)
				{
					if (!hashSet.Contains(outsideEnemy.enemyType.enemyName))
					{
						hashSet.Add(outsideEnemy.enemyType.enemyName);
						list.Add(outsideEnemy);
					}
				}
			}
			return list;
		}

		public SpawnableEnemyWithRarity GetMaskedEnemy()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
				{
					EnemyType enemyType = enemy.enemyType;
					object obj;
					if (enemyType == null)
					{
						obj = null;
					}
					else
					{
						GameObject enemyPrefab = enemyType.enemyPrefab;
						obj = ((enemyPrefab != null) ? enemyPrefab.GetComponent<EnemyAI>() : null);
					}
					EnemyAI val2 = (EnemyAI)obj;
					if ((Object)(object)val2 != (Object)null && ((object)val2).GetType() == typeof(MaskedPlayerEnemy))
					{
						return enemy;
					}
				}
			}
			return null;
		}

		private GameObject SpawnScrap(SpawnableItemWithRarity scrap, Vector3 position)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(scrap.spawnableItem.spawnPrefab, position, Quaternion.identity);
			GrabbableObject componentInChildren = val.GetComponentInChildren<GrabbableObject>();
			((Component)componentInChildren).transform.rotation = Quaternion.Euler(componentInChildren.itemProperties.restingRotation);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			return val;
		}

		private GameObject SpawnEnemy(SpawnableEnemyWithRarity enemyWithRarity, Vector3 position)
		{
			//IL_000c: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(enemyWithRarity.enemyType.enemyPrefab, position + new Vector3(0f, 0.5f, 0f), Quaternion.identity);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			return val;
		}

		private EnemyAIController SpawnControllableEnemy(SpawnableEnemyWithRarity enemyWithRarity, Vector3 position, Quaternion rotation)
		{
			//IL_000c: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_004f: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(enemyWithRarity.enemyType.enemyPrefab, position + new Vector3(0f, 0.5f, 0f), Quaternion.identity);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			GameObject val2 = new GameObject("enemy_controller");
			val2.transform.position = position + new Vector3(0f, 0.5f, 0f);
			val2.transform.rotation = rotation;
			EnemyAI componentInChildren = val.GetComponentInChildren<EnemyAI>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				throw new Exception("Enemy AI is null, cannot spawn enemy");
			}
			EnemyAIController andAttachEnemyController = componentInChildren.GetAndAttachEnemyController(val2);
			andAttachEnemyController.InitializeEnemyController(GetHostPlayer().playerActions, val);
			andAttachEnemyController.EnableLight(isGhostIndoors);
			ChangeAudioListener(andAttachEnemyController.AudioListener);
			return andAttachEnemyController;
		}

		private GameObject GetTurretPrefab()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				SpawnableMapObject[] spawnableMapObjects = val.spawnableMapObjects;
				foreach (SpawnableMapObject val2 in spawnableMapObjects)
				{
					object obj;
					if (val2 == null)
					{
						obj = null;
					}
					else
					{
						GameObject prefabToSpawn = val2.prefabToSpawn;
						obj = ((prefabToSpawn != null) ? prefabToSpawn.GetComponentInChildren<Turret>() : null);
					}
					if ((Object)obj != (Object)null)
					{
						return val2.prefabToSpawn;
					}
				}
			}
			return null;
		}

		private EnemyController SpawnControllableTurret(Vector3 position, Quaternion rotation)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_0051: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			GameObject turretPrefab = GetTurretPrefab();
			if ((Object)(object)turretPrefab == (Object)null)
			{
				ControlCompanyPlugin.Instance.logger.LogDebug((object)"Cannot find turret prefab in current level");
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(turretPrefab, position, rotation);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			GameObject val2 = new GameObject("enemy_controller");
			val2.transform.position = position + new Vector3(0f, 0.5f, 0f);
			val2.transform.rotation = rotation;
			TurretEnemyController turretEnemyController = val2.AddComponent<TurretEnemyController>();
			turretEnemyController.InitializeEnemyController(GetHostPlayer().playerActions, val);
			turretEnemyController.EnableLight(enable: true);
			return turretEnemyController;
		}

		private DissonanceComms GetMic()
		{
			return StartOfRound.Instance.voiceChatModule;
		}

		private void ForceMicPushToTalk()
		{
			IngamePlayerSettings.Instance.settings.pushToTalk = true;
		}

		private void ResetMicPushToTalk()
		{
			IngamePlayerSettings.Instance.settings.pushToTalk = initialMicPushToTalkSetting;
		}
	}
	internal class DoorOpener : MonoBehaviour
	{
		public void DetectAndOpenDoors(float range)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(((Component)this).transform.position, range);
			for (int i = 0; i < array.Length; i++)
			{
				DoorLock componentInChildren = ((Component)array[i]).GetComponentInChildren<DoorLock>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					OpenDoor(componentInChildren);
				}
			}
		}

		public void OpenDoor(DoorLock doorLock)
		{
			if ((Object)(object)doorLock != (Object)null && !doorLock.GetFieldValue<bool>("isDoorOpened"))
			{
				doorLock.OpenDoorAsEnemyServerRpc();
				((Component)doorLock).gameObject.GetComponent<AnimatedObjectTrigger>().TriggerAnimationNonPlayer(false, true, false);
			}
		}
	}
	internal class EnemyController : CustomPlayerController
	{
		protected GameObject enemyGameObject;

		protected bool isAIControlled = false;

		protected bool controlEnemyRotation = true;

		protected bool controlEnemyMovement = true;

		protected bool lockEnemyRotationInput = false;

		public bool IsAIControlled => isAIControlled;

		public virtual void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_004b: 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 (!isInitialized)
			{
				Initialize(playerActions, CameraMode.THIRD_PERSON);
				CharacterController obj = characterController;
				((Collider)obj).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj).excludeLayers) & ~LayerMask.op_Implicit(Constants.ITERACTABLE_OBJ_LAYER));
				enemyGameObject.transform.position = ((Component)this).transform.position;
				enemyGameObject.transform.rotation = ((Component)this).transform.rotation;
				this.enemyGameObject = enemyGameObject;
				EnableAIControl(enabled: false);
			}
		}

		public virtual bool CanControlEnemy()
		{
			return true;
		}

		public void SetLockEnemyRotation(bool lockEnemyRotationInput)
		{
			this.lockEnemyRotationInput = lockEnemyRotationInput;
		}

		public void UsePrimarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				UsePrimarySkillAction();
			}
		}

		protected virtual void UsePrimarySkillAction()
		{
		}

		public void ReleasePrimarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				ReleasePrimarySkillAction();
			}
		}

		protected virtual void ReleasePrimarySkillAction()
		{
		}

		public void UseSecondarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				UseSecondarySkillAction();
			}
		}

		protected virtual void UseSecondarySkillAction()
		{
		}

		public void ReleaseSecondarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				ReleaseSecondarySkillAction();
			}
		}

		protected virtual void ReleaseSecondarySkillAction()
		{
		}

		protected virtual void EnableAIControl(bool enabled)
		{
			CheckInitialized();
			isAIControlled = enabled;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Enable AI control: {enabled}");
			if (IsAIControlled)
			{
				ToggleAIControlTrue();
			}
			else
			{
				ToggleAIControlFalse();
			}
		}

		protected virtual void ToggleAIControlTrue()
		{
		}

		protected virtual void ToggleAIControlFalse()
		{
		}

		public virtual void ToggleAIControl()
		{
			CheckInitialized();
			isAIControlled = !isAIControlled;
			EnableAIControl(isAIControlled);
		}

		public virtual void DestroyAndCleanUp()
		{
			if (ShouldDestroyEnemyGameObjectOnCleanUp())
			{
				Object.Destroy((Object)(object)enemyGameObject);
			}
			Object.Destroy((Object)(object)((Component)this).gameObject);
		}

		protected virtual bool ShouldDestroyEnemyGameObjectOnCleanUp()
		{
			return true;
		}

		public virtual string GetPrimarySkillName()
		{
			return "";
		}

		public virtual string GetSecondarySkillName()
		{
			return "Secondary Skill";
		}

		protected void CheckInitialized()
		{
			if (!isInitialized)
			{
				throw new Exception("Not initialized yet.");
			}
		}

		protected virtual void OnControllerColliderHit(ControllerColliderHit hit)
		{
			DoorLock component = hit.gameObject.GetComponent<DoorLock>();
			if ((Object)(object)component != (Object)null)
			{
				doorOpener.OpenDoor(component);
			}
		}
	}
	internal class EnemyAIController : EnemyController
	{
		private EnemyAI enemyAI;

		private NavMeshAgent enemyAIAgent;

		private float originalAgentAngularSpeed;

		private float originalAgentSpeed;

		public EnemyAI EnemyAI => enemyAI;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0021: 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_0037: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			if (!isInitialized)
			{
				Initialize(playerActions, CameraMode.THIRD_PERSON);
				CharacterController obj = characterController;
				((Collider)obj).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj).excludeLayers) & ~LayerMask.op_Implicit(Constants.ITERACTABLE_OBJ_LAYER));
				enemyAI = GetEnemyAIFromEnemyGameObject(enemyGameObject);
				if ((Object)(object)enemyAI == (Object)null)
				{
					throw new Exception("Enemy gameobject does not have EnemyAI script attached.");
				}
				((Component)enemyAI).gameObject.LogLayer();
				enemyGameObject.transform.position = ((Component)this).transform.position;
				enemyGameObject.transform.rotation = ((Component)this).transform.rotation;
				base.enemyGameObject = enemyGameObject;
				enemyAIAgent = enemyGameObject.GetComponentInChildren<NavMeshAgent>();
				originalAgentAngularSpeed = enemyAIAgent.angularSpeed;
				originalAgentSpeed = enemyAIAgent.speed;
				ConfigureEnemyAttributes(enemyAI);
				EnableAIControl(enabled: false);
			}
		}

		protected override void Update()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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)
			if (!isInitialized)
			{
				return;
			}
			base.Update();
			if (!isAIControlled)
			{
				if (CanControlEnemy())
				{
					if (controlEnemyMovement)
					{
						enemyGameObject.transform.position = ((Component)this).transform.position;
					}
					if (controlEnemyRotation && !lockEnemyRotationInput)
					{
						enemyGameObject.transform.rotation = ((Component)this).transform.rotation;
					}
				}
			}
			else
			{
				((Component)this).transform.position = enemyGameObject.transform.position;
			}
		}

		protected EnemyAI GetEnemyAIFromEnemyGameObject(GameObject enemyObj)
		{
			return enemyObj.GetComponentInChildren<EnemyAI>();
		}

		private void ConfigureEnemyAttributes(EnemyAI enemyAI)
		{
			EnemyAttributes enemyAttributes = enemyAI.GetEnemyAttributes();
			base.WalkSpeed = enemyAttributes.WalkSpeed;
			base.RunSpeed = enemyAttributes.RunSpeed;
			SetCamDistance(enemyAttributes.CamDistance);
			SetCamHeight(enemyAttributes.CamHeight);
			controlEnemyRotation = enemyAttributes.PlayerControlsRotation;
			controlEnemyMovement = true;
		}

		protected virtual void ConfigureEnemyHandicap(EnemyAI enemyAI)
		{
		}

		public override bool CanControlEnemy()
		{
			return !enemyAI.isEnemyDead;
		}

		protected override void Move()
		{
			if (!enemyAI.isEnemyDead)
			{
				base.Move();
			}
		}

		public void SwitchAIState(int stateIndex)
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				enemyAI.SwitchToBehaviourState(stateIndex);
			}
		}

		protected override void ToggleAIControlTrue()
		{
			if ((Object)(object)enemyAIAgent != (Object)null)
			{
				enemyAIAgent.angularSpeed = originalAgentAngularSpeed;
				enemyAIAgent.speed = originalAgentSpeed;
				enemyAIAgent.isStopped = false;
			}
		}

		protected override void ToggleAIControlFalse()
		{
			if ((Object)(object)enemyAI != (Object)null)
			{
				try
				{
					enemyAI.ChangeOwnershipOfEnemy(ControlCenter.Instance.GetHostPlayer().actualClientId);
				}
				catch (Exception ex)
				{
					ControlCompanyPlugin.Instance.logger.LogDebug((object)("Cannot give host control: " + ex.Message));
				}
			}
			if ((Object)(object)enemyAIAgent != (Object)null)
			{
				enemyAIAgent.angularSpeed = 0f;
				enemyAIAgent.speed = 0f;
				enemyAIAgent.isStopped = true;
			}
			((Component)this).transform.SetParent((Transform)null);
		}

		protected override bool ShouldDestroyEnemyGameObjectOnCleanUp()
		{
			return !enemyAI.isEnemyDead;
		}

		public override string GetSecondarySkillName()
		{
			return "Secondary Skill";
		}

		protected override void UseSecondarySkillAction()
		{
			enemyAI.SwitchToBehaviourState(1);
		}

		protected override void EnableAIControl(bool enabled)
		{
			base.EnableAIControl(enabled);
			canMove = !isAIControlled;
		}
	}
	internal class CustomPlayerController : MonoBehaviour
	{
		public enum CameraMode
		{
			THIRD_PERSON,
			FIRST_PERSON
		}

		protected bool isInitialized = false;

		protected bool hasControl = false;

		protected bool canMove = false;

		protected bool canRotate = false;

		protected bool canJump = false;

		protected CameraMode camMode;

		protected CharacterController characterController;

		protected GameObject cameraGameObjectParent;

		protected GameObject cameraGameObject;

		protected Camera camera;

		protected Light light;

		protected PlayerActions playerActions;

		protected DoorOpener doorOpener;

		private AudioListener audioListener;

		private float runSpeed = 9f;

		private float walkSpeed = 7f;

		private float camDistance = -3.5f;

		private float camHeight = 2f;

		private float gravity = -20f;

		private float jumpHeight = 4.5f;

		private float currentYVelocity;

		public float RunSpeed
		{
			get
			{
				return runSpeed;
			}
			set
			{
				runSpeed = value;
			}
		}

		public float WalkSpeed
		{
			get
			{
				return walkSpeed;
			}
			set
			{
				walkSpeed = value;
			}
		}

		public float Gravity
		{
			get
			{
				return gravity;
			}
			set
			{
				gravity = value;
			}
		}

		public AudioListener AudioListener
		{
			get
			{
				return audioListener;
			}
			set
			{
				audioListener = value;
			}
		}

		public bool IsInitialized
		{
			get
			{
				return isInitialized;
			}
			set
			{
				isInitialized = value;
			}
		}

		public void Initialize(PlayerActions playerActions, CameraMode camMode)
		{
			if (!isInitialized)
			{
				this.playerActions = playerActions;
				this.camMode = camMode;
				characterController = InitializeCharacterController();
				camera = InitializeCamera();
				light = InitializeLight(((Component)camera).gameObject);
				doorOpener = ((Component)this).gameObject.AddComponent<DoorOpener>();
				EnableControl(enable: true);
				isInitialized = true;
			}
		}

		public void EnableLight(bool enable)
		{
			((Behaviour)light).enabled = enable;
		}

		public void EnableControl(bool enable)
		{
			hasControl = enable;
			canMove = enable;
			canRotate = enable;
			canJump = enable;
		}

		public bool IsMoving()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 velocity = characterController.velocity;
			return ((Vector3)(ref velocity)).sqrMagnitude > 0f;
		}

		public void SetCamHeight(float camHeight)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			this.camHeight = camHeight;
			cameraGameObjectParent.transform.localPosition = new Vector3(0f, camHeight, 0f);
		}

		public void SetCamDistance(float camDistance)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			this.camDistance = camDistance;
			cameraGameObject.transform.localPosition = new Vector3(0f, 0f, (camMode == CameraMode.THIRD_PERSON) ? camDistance : 0f);
		}

		protected virtual void Update()
		{
			if (isInitialized && hasControl)
			{
				if (canMove)
				{
					Move();
				}
				if (canRotate)
				{
					Rotate();
				}
				if (((ButtonControl)InputKeys.CONTROLLER_USE_KEY).wasPressedThisFrame)
				{
					doorOpener.DetectAndOpenDoors(3f);
				}
			}
		}

		protected virtual void Move()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: 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_006a: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: 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_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			bool flag = IngamePlayerSettings.Instance.playerInput.actions.FindAction("Sprint", false).ReadValue<float>() > 0f;
			Vector3 val = Vector2.op_Implicit(IngamePlayerSettings.Instance.playerInput.actions.FindAction("Move", false).ReadValue<Vector2>());
			Vector3 val2 = ((Component)this).transform.right * val.x;
			Vector3 val3 = ((Component)this).transform.forward * val.y;
			bool isGrounded = characterController.isGrounded;
			if (isGrounded && currentYVelocity < 0f)
			{
				currentYVelocity = 0f;
			}
			if (canJump && isGrounded && ((ButtonControl)InputKeys.CONTROLLER_JUMP_KEY).wasPressedThisFrame)
			{
				currentYVelocity += Mathf.Sqrt(jumpHeight * (0f - gravity));
			}
			currentYVelocity += gravity * Time.deltaTime;
			characterController.Move(((val2 + val3) * (flag ? runSpeed : walkSpeed) + new Vector3(0f, currentYVelocity, 0f)) * Time.deltaTime);
		}

		protected virtual void Rotate()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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_0038: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			MovementActions movement = playerActions.Movement;
			Vector2 val = ((MovementActions)(ref movement)).Look.ReadValue<Vector2>() * 0.008f * (float)IngamePlayerSettings.Instance.settings.lookSensitivity;
			if (IngamePlayerSettings.Instance.settings.invertYAxis)
			{
				val.y *= -1f;
			}
			((Component)this).transform.Rotate(new Vector3(0f, val.x, 0f));
			cameraGameObjectParent.transform.Rotate(new Vector3(0f - val.y, 0f, 0f));
		}

		private Light InitializeLight(GameObject lightParent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("controller_light");
			val.transform.SetParent(lightParent.transform);
			val.transform.localPosition = new Vector3(0f, 0.5f, 0f);
			val.transform.localRotation = Quaternion.identity;
			Light val2 = val.AddComponent<Light>();
			val2.range = 15f;
			val2.intensity = 225f;
			val2.cullingMask = -1;
			return val2;
		}

		private CharacterController InitializeCharacterController()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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)
			CharacterController controller = ((Component)this).gameObject.AddComponent<CharacterController>();
			((Collider)controller).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(Constants.PLAYER_LOS_LAYER) | LayerMask.op_Implicit(Constants.ITERACTABLE_OBJ_LAYER) | LayerMask.op_Implicit(Constants.ENEMIES_LAYER) | LayerMask.op_Implicit(Constants.PROPS_LAYER) | LayerMask.op_Implicit(Constants.PLAYER_RAGDOLL_LAYER));
			controller.center = new Vector3(0f, 0.55f, 0f);
			controller.height = 0.4f;
			ControlCenter.Instance.GetAllPlayers().ForEach(delegate(PlayerControllerB p)
			{
				if ((Object)(object)p != (Object)null)
				{
					((Component)p).GetComponentsInChildren<Collider>().ToList().ForEach(delegate(Collider c)
					{
						Physics.IgnoreCollision(c, (Collider)(object)controller);
					});
				}
			});
			controller.slopeLimit = 60f;
			controller.stepOffset = 0.4f;
			return controller;
		}

		private Camera InitializeCamera()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0024: 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)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0073: 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)
			GameObject val = new GameObject("controller_cam_parent");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localRotation = Quaternion.identity;
			val.transform.localPosition = new Vector3(0f, camHeight, 0f);
			GameObject val2 = new GameObject("controller_cam");
			val2.transform.SetParent(val.transform);
			val2.transform.localRotation = Quaternion.identity;
			val2.transform.localPosition = new Vector3(0f, 0f, (camMode == CameraMode.THIRD_PERSON) ? camDistance : 0f);
			Camera val3 = val2.AddComponent<Camera>();
			audioListener = val2.AddComponent<AudioListener>();
			cameraGameObject = val2;
			cameraGameObjectParent = val;
			Camera gameplayCamera = ControlCenter.Instance.GetHostPlayer().gameplayCamera;
			val3.cullingMask = gameplayCamera.cullingMask;
			val3.farClipPlane = gameplayCamera.farClipPlane;
			return val3;
		}
	}
}
namespace ControlCompany.Core.UI
{
	public class UIInstruction
	{
		public string InputKey { get; set; }

		public string ActionText { get; set; }
	}
	internal class UIManager : MonoBehaviour
	{
		private const float GUI_LABEL_HEIGHT = 36f;

		private const float GUI_LABEL_WIDTH = 750f;

		private const float GUI_PADDING = 32f;

		private const int GUI_FONT_SIZE = 28;

		private const FontStyle GUI_FONT_WEIGHT = 0;

		public static UIManager Instance;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
		}

		public void RenderNotHostLabel(string toggleUIKey)
		{
			//IL_000b: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 24,
				fontStyle = (FontStyle)0
			};
			val.normal.textColor = Color.red;
			RenderTextTopLeftCorner("Not hosting. ControlCompany mod is disabled. Press " + toggleUIKey + " to hide.", 0f, val, 1000f);
		}

		public void RenderEnemyControls(string primaryKey, string secondaryKey, string aiControlKey, string exitKey, EnemyController enemyController, PlayerControllerB hostPlayer)
		{
			string primarySkillName = enemyController.GetPrimarySkillName();
			string secondarySkillName = enemyController.GetSecondarySkillName();
			List<UIInstruction> list = new List<UIInstruction>();
			if (enemyController.IsAIControlled)
			{
				list.Add(new UIInstruction
				{
					InputKey = aiControlKey,
					ActionText = "Take control"
				});
			}
			else
			{
				if (!Utility.IsNullOrWhiteSpace(primarySkillName))
				{
					list.Add(new UIInstruction
					{
						InputKey = primaryKey,
						ActionText = primarySkillName
					});
				}
				if (!Utility.IsNullOrWhiteSpace(secondarySkillName))
				{
					list.Add(new UIInstruction
					{
						InputKey = secondaryKey,
						ActionText = secondarySkillName
					});
				}
				list.Add(new UIInstruction
				{
					InputKey = aiControlKey,
					ActionText = "AI control"
				});
			}
			list.Add(new UIInstruction
			{
				InputKey = exitKey,
				ActionText = "Exit"
			});
			RenderPlayerStatus(hostPlayer);
			float height = 0f;
			height = RenderEnemyStatus(enemyController, height);
			RenderEnemySkills(list, height);
		}

		public void RenderHostControls(string ghostModeKey, string cycleLeftKey, string cycleRightKey, PlayerControllerB currentTarget, bool isExtendedModeEnabled, string creditsKey, string entranceTeleportKey, string toggleUIKey)
		{
			List<UIInstruction> list = new List<UIInstruction>();
			list.Add(new UIInstruction
			{
				InputKey = ghostModeKey,
				ActionText = "Ghost mode"
			});
			list.Add(new UIInstruction
			{
				InputKey = $"{cycleLeftKey}/{cycleRightKey}",
				ActionText = "Change target"
			});
			list.Add(new UIInstruction
			{
				InputKey = toggleUIKey,
				ActionText = "Hide UI"
			});
			if (isExtendedModeEnabled)
			{
				list.Add(new UIInstruction
				{
					InputKey = creditsKey,
					ActionText = "Give credits"
				});
				list.Add(new UIInstruction
				{
					InputKey = entranceTeleportKey,
					ActionText = "Teleport to entrance"
				});
			}
			RenderHostControlList(list, currentTarget);
		}

		public void RenderGhostControls(List<string> enemySpawnKeys, string exitKey, string cycleLeftKey, string cycleRightKey, bool showEnemyPaging, List<SpawnableEnemyWithRarity> enemies, List<SpawnableItemWithRarity> scraps, PlayerControllerB hostPlayer, bool scrapSpawnMode)
		{
			List<UIInstruction> list = new List<UIInstruction>();
			if (!scrapSpawnMode)
			{
				if (enemies != null && enemies.Count > 0)
				{
					if (showEnemyPaging)
					{
						list.Add(new UIInstruction
						{
							InputKey = $"{cycleLeftKey}/{cycleRightKey}",
							ActionText = "Change page"
						});
					}
					for (int i = 0; i < enemies.Count && i < enemySpawnKeys.Count; i++)
					{
						GameObject enemyPrefab = enemies[i].enemyType.enemyPrefab;
						EnemyAI componentInChildren = enemyPrefab.GetComponentInChildren<EnemyAI>();
						list.Add(new UIInstruction
						{
							InputKey = enemySpawnKeys[i],
							ActionText = $"Control {(((Object)(object)componentInChildren == (Object)null) ? enemies[i].enemyType.enemyName : componentInChildren.GetEnemyName())}"
						});
					}
				}
			}
			else
			{
				for (int j = 0; j < scraps.Count && j < enemySpawnKeys.Count; j++)
				{
					list.Add(new UIInstruction
					{
						InputKey = enemySpawnKeys[j],
						ActionText = $"Spawn {scraps[j].spawnableItem.itemName}"
					});
				}
			}
			list.Add(new UIInstruction
			{
				InputKey = exitKey,
				ActionText = "Exit"
			});
			RenderPlayerStatus(hostPlayer);
			RenderGhostControlList(list);
		}

		private void RenderGhostControlList(List<UIInstruction> ghostControls)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			if (ghostControls.Count <= 0)
			{
				return;
			}
			GUIStyle style = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)5,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = 0f;
			foreach (UIInstruction ghostControl in ghostControls)
			{
				RenderTextTopRightCorner($"{ghostControl.InputKey}: {ghostControl.ActionText}", num, style);
				num += 36f;
			}
		}

		private float RenderMicStatus(float height, PlayerControllerB hostPlayer)
		{
			//IL_000b: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = height;
			if (IngamePlayerSettings.Instance.settings.micEnabled)
			{
				if (!StartOfRound.Instance.voiceChatModule.IsMuted)
				{
					val.normal.textColor = Color.green;
					RenderTextTopLeftCorner(string.Format("{0} mic enabled", hostPlayer.isPlayerDead ? "Dead" : "Player"), num, val);
				}
				else
				{
					val.normal.textColor = Color.red;
					RenderTextTopLeftCorner(string.Format("{0} mic disabled (push to talk)", hostPlayer.isPlayerDead ? "Dead" : "Player"), num, val);
				}
				num += 36f;
			}
			return num;
		}

		private float RenderPlayerStatus(PlayerControllerB hostPlayer)
		{
			//IL_000b: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0050: 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_00b1: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			if (hostPlayer.isPlayerDead)
			{
				val.normal.textColor = Color.red;
			}
			else
			{
				val.normal.textColor = Color.green;
			}
			float num = 0f;
			RenderTextTopLeftCorner(string.Format("Player status: {0}", hostPlayer.isPlayerDead ? "Dead" : "Alive"), num, val);
			num += 36f;
			if (!hostPlayer.isPlayerDead)
			{
				GUIStyle val2 = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)3,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				bool flag = !HostIsNearOtherPlayers(hostPlayer);
				if (flag)
				{
					val2.normal.textColor = Color.green;
				}
				else
				{
					val2.normal.textColor = Color.red;
				}
				RenderTextTopLeftCorner(string.Format("Player proximity: {0}", flag ? "Alone" : "Near others"), num, val2);
				num += 36f;
			}
			return num + RenderMicStatus(num, hostPlayer);
		}

		private void RenderHostControlList(List<UIInstruction> hostControls, PlayerControllerB currentTarget)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			if (hostControls.Count <= 0)
			{
				return;
			}
			GUIStyle style = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)5,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = 0f;
			if ((Object)(object)currentTarget != (Object)null)
			{
				RenderTextTopRightCorner($"Spawn target: {currentTarget.playerUsername}", num, style);
				num += 36f;
			}
			foreach (UIInstruction hostControl in hostControls)
			{
				RenderTextTopRightCorner($"{hostControl.InputKey}: {hostControl.ActionText}", num, style);
				num += 36f;
			}
		}

		private float RenderEnemyStatus(EnemyController enemyController, float height)
		{
			//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)
			//IL_0025: 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_0037: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			float num = height;
			if (enemyController.IsAIControlled)
			{
				GUIStyle val = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)5,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				val.normal.textColor = Color.red;
				RenderTextTopRightCorner("AI controlled", num, val);
				num += 36f;
			}
			return num;
		}

		private float RenderEnemySkills(List<UIInstruction> playerEnemyControls, float height)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			float num = height;
			if (playerEnemyControls.Count > 0)
			{
				GUIStyle style = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)5,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				foreach (UIInstruction playerEnemyControl in playerEnemyControls)
				{
					RenderTextTopRightCorner($"{playerEnemyControl.InputKey}: {playerEnemyControl.ActionText}", num, style);
					num += 36f;
				}
			}
			return num;
		}

		private void RenderTextMiddle(string text, float yPos, GUIStyle style)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect((float)Screen.width / 2f - 375f, yPos + 32f, 750f, 36f), text, style);
		}

		private void RenderTextTopRightCorner(string text, float yPos, GUIStyle style)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect((float)Screen.width - 750f - 32f, yPos + 32f, 750f, 36f), text, style);
		}

		private void RenderTextTopLeftCorner(string text, float yPos, GUIStyle style, float widthOverride = -1f)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect(32f, yPos + 32f, (widthOverride > 0f) ? widthOverride : 750f, 36f), text, style);
		}

		private bool HostIsNearOtherPlayers(PlayerControllerB hostPlayer)
		{
			return (bool)hostPlayer.Call("NearOtherPlayers", hostPlayer, 17f);
		}
	}
}
namespace ControlCompany.Core.Input
{
	public static class InputKeys
	{
		public static KeyControl EXIT_KEY = Keyboard.current.escapeKey;

		public static KeyControl EXTENDED_MODE_KEY = Keyboard.current.digit0Key;

		public static KeyControl TOGGLE_UI_KEY = Keyboard.current.uKey;

		public static KeyControl CYCLE_KEY_LEFT = Keyboard.current.oKey;

		public static KeyControl CYCLE_KEY_RIGHT = Keyboard.current.pKey;

		public static KeyControl HOST_GHOST_MODE_KEY = Keyboard.current.f1Key;

		public static KeyControl HOST_GIVE_CREDITS_KEY = Keyboard.current.digit8Key;

		public static KeyControl HOST_TELEPORT_TO_ENTRANCE_KEY = Keyboard.current.digit9Key;

		public static KeyControl GHOST_SPAWN_ENEMY_1 = Keyboard.current.f1Key;

		public static KeyControl GHOST_SPAWN_ENEMY_2 = Keyboard.current.f2Key;

		public static KeyControl GHOST_SPAWN_ENEMY_3 = Keyboard.current.f3Key;

		public static KeyControl GHOST_SPAWN_ENEMY_4 = Keyboard.current.f4Key;

		public static KeyControl GHOST_SPAWN_ENEMY_5 = Keyboard.current.f5Key;

		public static KeyControl GHOST_SPAWN_ENEMY_6 = Keyboard.current.f6Key;

		public static KeyControl GHOST_SPAWN_ENEMY_7 = Keyboard.current.f7Key;

		public static KeyControl GHOST_SPAWN_ENEMY_8 = Keyboard.current.f8Key;

		public static KeyControl GHOST_SPAWN_ENEMY_9 = Keyboard.current.f9Key;

		public static KeyControl GHOST_SPAWN_ENEMY_10 = Keyboard.current.f10Key;

		public static KeyControl GHOST_SPAWN_ENEMY_11 = Keyboard.current.f11Key;

		public static KeyControl GHOST_SPAWN_ENEMY_12 = Keyboard.current.f12Key;

		public static List<KeyControl> GHOST_SPAWN_ENEMY_KEYS = new List<KeyControl>();

		public static KeyControl ENEMY_TOGGLE_AI_KEY = Keyboard.current.f1Key;

		public static ButtonControl ENEMY_PRIMARY_SKILL_BUTTON = Mouse.current.leftButton;

		public static ButtonControl ENEMY_SECONDARY_SKILL_BUTTON = Mouse.current.rightButton;

		public static KeyControl LOCK_ENEMY_ROTATION_KEY = Keyboard.current.leftAltKey;

		public static KeyControl CONTROLLER_USE_KEY = Keyboard.current.eKey;

		public static KeyControl CONTROLLER_JUMP_KEY = Keyboard.current.spaceKey;
	}
}
namespace ControlCompany.Core.Extentions
{
	public static class ExtensionMethods
	{
		public static T GetFieldValue<T>(this object obj, string name)
		{
			return (T)(obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj));
		}

		public static void SetFieldValue<T>(this object obj, string method, T value)
		{
			obj.GetType().GetField(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField | BindingFlags.SetProperty)?.SetValue(obj, value);
		}

		public static object Call(this object o, string methodName, params object[] args)
		{
			MethodInfo method = o.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(o, args);
			}
			return null;
		}

		public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
		{
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return defaultValue;
		}

		public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
		{
			while (source.Any())
			{
				yield return source.Take(chunksize);
				source = source.Skip(chunksize);
			}
		}

		public static void LogLayer(this GameObject gameObject)
		{
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Enemy layer ({LayerMask.LayerToName(gameObject.layer)}): {gameObject.layer}");
		}

		public static void LogGameObjectName(this GameObject gameObject)
		{
			ControlCompanyPlugin.Instance.logger.LogMessage((object)string.Format("GameObject name: {0}, parent: {1}", ((Object)gameObject).name, ((Object)(object)gameObject.transform.parent != (Object)null) ? ((Object)gameObject.transform.parent).name : "null"));
		}

		public static void LogAllComponents(this GameObject gameObject)
		{
			Component[] components = gameObject.GetComponents<Component>();
			foreach (Component val in components)
			{
				_ = $"GameObject ({((Object)gameObject).name}) component: {((Object)val).name}";
			}
		}

		public static void LogPosition(this GameObject gameObject)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"GameObject ({((Object)gameObject).name}) position: {gameObject.transform.position}, local position: {gameObject.transform.localPosition}");
		}
	}
}
namespace ControlCompany.Core.Enemy
{
	internal class SandWormEnemyController : EnemyAIController
	{
		private SandWormAI sandWormAI;

		private bool usedEmerge = false;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			sandWormAI = (SandWormAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void Move()
		{
			if (!IsEmerged() && !usedEmerge)
			{
				base.Move();
			}
		}

		protected override void Update()
		{
			base.Update();
			controlEnemyRotation = !IsEmerged() && !usedEmerge;
			if (IsEmerged())
			{
				usedEmerge = true;
			}
		}

		protected override void UseSecondarySkillAction()
		{
			if (!IsEmerged() && !usedEmerge)
			{
				usedEmerge = true;
				sandWormAI.StartEmergeAnimation();
			}
		}

		public override string GetSecondarySkillName()
		{
			return usedEmerge ? "" : "Emerge";
		}

		private bool IsEmerged()
		{
			return sandWormAI.inEmergingState || sandWormAI.emerged;
		}
	}
	internal class SpringManEnemyController : EnemyAIController
	{
		private SpringManAI springMan;

		private float initialWalkSpeed;

		private float initialRunSpeed;

		private bool holdingForceMove = false;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			springMan = (SpringManAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
			initialWalkSpeed = base.WalkSpeed;
			initialRunSpeed = base.RunSpeed;
		}

		protected override void Update()
		{
			base.Update();
			bool flag = springMan.GetFieldValue<bool>("hasStopped") || springMan.GetFieldValue<bool>("stoppingMovement");
			controlEnemyRotation = !flag || holdingForceMove;
			float fieldValue = springMan.GetFieldValue<float>("currentAnimSpeed");
			base.WalkSpeed = initialWalkSpeed * (1f + fieldValue / 6f);
			base.RunSpeed = initialRunSpeed * (1f + fieldValue / 6f);
		}

		protected override void Move()
		{
			if ((!springMan.GetFieldValue<bool>("hasStopped") && !springMan.GetFieldValue<bool>("stoppingMovement")) || holdingForceMove)
			{
				base.Move();
			}
		}

		protected override void UseSecondarySkillAction()
		{
			holdingForceMove = true;
		}

		protected override void ReleaseSecondarySkillAction()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				holdingForceMove = false;
			}
		}

		public override string GetSecondarySkillName()
		{
			return "(HOLD) Force move";
		}
	}
	internal class MaskedPlayerEnemyController : EnemyAIController
	{
		private MaskedPlayerEnemy maskedEnemy;

		private float entranceDoorOpenRange = 2.5f;

		private float useEntranceDoorCooldown = 2f;

		private float timeSinceLastEntranceDoorUse = 0f;

		private bool canUseEntranceDoorOnCollision = true;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			maskedEnemy = (MaskedPlayerEnemy)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
			canJump = true;
		}

		protected override void Update()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			base.Update();
			bool fieldValue = maskedEnemy.GetFieldValue<bool>("inKillAnimation");
			bool fieldValue2 = maskedEnemy.GetFieldValue<bool>("crouching");
			controlEnemyRotation = !fieldValue && !fieldValue2;
			if (!canUseEntranceDoorOnCollision)
			{
				timeSinceLastEntranceDoorUse += Time.deltaTime;
				if (timeSinceLastEntranceDoorUse >= useEntranceDoorCooldown)
				{
					canUseEntranceDoorOnCollision = true;
					timeSinceLastEntranceDoorUse = 0f;
				}
			}
			MovementActions movement = playerActions.Movement;
			if (((MovementActions)(ref movement)).Interact.WasPressedThisFrame())
			{
				ScanNearbyAndOpenMainEntranceDoor();
				return;
			}
			movement = playerActions.Movement;
			if (((MovementActions)(ref movement)).Crouch.WasPressedThisFrame())
			{
				Crouch(!fieldValue2);
			}
		}

		protected override void Move()
		{
			bool fieldValue = maskedEnemy.GetFieldValue<bool>("inKillAnimation");
			bool fieldValue2 = maskedEnemy.GetFieldValue<bool>("crouching");
			if (!fieldValue && !fieldValue2)
			{
				base.Move();
			}
		}

		protected override void UseSecondarySkillAction()
		{
		}

		private void Crouch(bool crouching)
		{
			maskedEnemy.SetCrouchingServerRpc(crouching);
		}

		private void ScanNearbyAndOpenMainEntranceDoor()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(((Component)this).transform.position, entranceDoorOpenRange);
			for (int i = 0; i < array.Length; i++)
			{
				EntranceTeleport componentInChildren = ((Component)array[i]).GetComponentInChildren<EntranceTeleport>();
				if ((Object)(object)componentInChildren != (Object)null && componentInChildren.entranceId == 0)
				{
					UseEntranceDoor();
				}
			}
		}

		private void UseEntranceDoor()
		{
			//IL_001d: 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_0029: 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)
			((Collider)characterController).enabled = false;
			Vector3 position = RoundManager.FindMainEntrancePosition(true, !((EnemyAI)maskedEnemy).isOutside);
			((Component)this).transform.position = position;
			maskedEnemy.Call("TeleportMaskedEnemyAndSync", RoundManager.FindMainEntrancePosition(true, !((EnemyAI)maskedEnemy).isOutside), !((EnemyAI)maskedEnemy).isOutside);
			((Collider)characterController).enabled = true;
			canUseEntranceDoorOnCollision = false;
			ControlCenter.Instance.IsGhostIndoors = !((EnemyAI)maskedEnemy).isOutside;
		}

		protected override void OnControllerColliderHit(ControllerColliderHit hit)
		{
			base.OnControllerColliderHit(hit);
			if (canUseEntranceDoorOnCollision)
			{
				EntranceTeleport componentInChildren = hit.gameObject.GetComponentInChildren<EntranceTeleport>();
				if ((Object)(object)componentInChildren != (Object)null && componentInChildren.entranceId == 0)
				{
					UseEntranceDoor();
				}
			}
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}
	}
	internal class BlobEnemyController : EnemyAIController
	{
		private BlobAI blobAI;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			blobAI = (BlobAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void UseSecondarySkillAction()
		{
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}
	}
	internal class CentipedeEnemyController : EnemyAIController
	{
		private CentipedeAI centipedeAI;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			centipedeAI = (CentipedeAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void Update()
		{
			base.Update();
			bool flag = IsClingingToSomething();
			controlEnemyRotation = !flag;
			controlEnemyMovement = !flag;
		}

		protected override void Move()
		{
			if (!IsClingingToSomething())
			{
				base.Move();
			}
		}

		protected override void UsePrimarySkillAction()
		{
			if (((EnemyAI)centipedeAI).currentBehaviourStateIndex == 1)
			{
				SwitchAIState(2);
			}
		}

		protected override void UseSecondarySkillAction()
		{
			if (!IsClingingToSomething())
			{
				centipedeAI.Call("RaycastToCeiling");
				SwitchAIState(1);
			}
		}

		public bool IsClingingToSomething()
		{
			return (Object)(object)centipedeAI.clingingToPlayer != (Object)null || ((EnemyAI)centipedeAI).inSpecialAnimation || centipedeAI.GetFieldValue<bool>("clingingToDeadBody") || centipedeAI.GetFieldValue<bool>("clingingToCeiling") || centipedeAI.GetFieldValue<bool>("startedCeilingAnimationCoroutine") || centipedeAI.GetFieldValue<bool>("inDroppingOffPlayerAnim");
		}

		public override string GetPrimarySkillName()
		{
			return "Drop";
		}

		public override string GetSecondarySkillName()
		{
			return "Attach to ceiling";
		}
	}
	internal class FlowermanEnemyController : EnemyAIController
	{
		private FlowermanAI flowermanAI;

		private const int FLOWERMAN_DEFAULT_MODE = 0;

		private const int FLOWERMAN_STAND_MODE = 1;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			flowermanAI = (FlowermanAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void Move()
		{
			if (!((EnemyAI)flowermanAI).inSpecialAnimation)
			{
				base.Move();
			}
		}

		protected override void Update()
		{
			base.Update();
			controlEnemyRotation = !((EnemyAI)flowermanAI).inSpecialAnimation;
		}

		protected override void UseSecondarySkillAction()
		{
			((EnemyAI)flowermanAI).SwitchToBehaviourState(1);
		}

		protected override void ReleaseSecondarySkillAction()
		{
			((EnemyAI)flowermanAI).SwitchToBehaviourState(0);
		}

		protected override void UsePrimarySkillAction()
		{
			if (flowermanAI.carryingPlayerBody)
			{
				flowermanAI.Call("DropPlayerBody");
				flowermanAI.DropPlayerBodyServerRpc();
			}
		}

		public override string GetPrimarySkillName()
		{
			return flowermanAI.carryingPlayerBody ? "Drop body" : "";
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}
	}
	internal class ForestGiantEnemyController : EnemyAIController
	{
		private ForestGiantAI forestGiantAI;

		private const int FOREST_GIANT_DEFAULT_MODE = 0;

		private const int FOREST_GIANT_CHASE_MODE = 1;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			forestGiantAI = (ForestGiantAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void Update()
		{
			base.Update();
			bool flag = IsEatingPlayer();
			controlEnemyRotation = !flag;
			controlEnemyMovement = !flag;
		}

		protected override void Move()
		{
			if (!IsEatingPlayer())
			{
				base.Move();
			}
		}

		protected override void UseSecondarySkillAction()
		{
		}

		protected override void ReleaseSecondarySkillAction()
		{
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}

		public bool IsEatingPlayer()
		{
			return forestGiantAI.GetFieldValue<bool>("inEatingPlayerAnimation");
		}
	}
	internal class BaboonBirdEnemyController : EnemyAIController
	{
		private BaboonBirdAI baboonBirdAI;

		private float grabRange = 1.5f;

		private Vector3 originalBaboonCampPosition;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			baboonBirdAI = (BaboonBirdAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void EnableAIControl(bool enabled)
		{
			//IL_0017: 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_0030: 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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (enabled)
			{
				BaboonBirdAI.baboonCampPosition = originalBaboonCampPosition;
			}
			else
			{
				originalBaboonCampPosition = BaboonBirdAI.baboonCampPosition;
				BaboonBirdAI.baboonCampPosition = new Vector3(1000f, 1000f, 1000f);
			}
			base.EnableAIControl(enabled);
		}

		protected override void UseSecondarySkillAction()
		{
			if ((Object)(object)baboonBirdAI.heldScrap == (Object)null)
			{
				GrabNearbyItem();
			}
			else
			{
				DropCurrentItem();
			}
		}

		public void GrabNearbyItem()
		{
			//IL_0027: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)baboonBirdAI.heldScrap != (Object)null)
			{
				return;
			}
			Collider[] array = Physics.OverlapSphere(enemyGameObject.transform.position, grabRange);
			NetworkObject val = null;
			float num = float.PositiveInfinity;
			for (int i = 0; i < array.Length; i++)
			{
				GrabbableObject componentInChildren = ((Component)array[i]).GetComponentInChildren<GrabbableObject>();
				if (!((Object)(object)componentInChildren != (Object)null) || !(bool)baboonBirdAI.Call("CanGrabScrap", componentInChildren))
				{
					continue;
				}
				NetworkObject component = ((Component)componentInChildren).GetComponent<NetworkObject>();
				if ((Object)(object)component != (Object)null)
				{
					float num2 = Vector3.Distance(((Component)componentInChildren).transform.position, ((Component)this).transform.position);
					if (num2 < num)
					{
						num = num2;
						val = component;
					}
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				((EnemyAI)baboonBirdAI).SwitchToBehaviourState(1);
				baboonBirdAI.Call("GrabItemAndSync", val);
			}
		}

		public void DropCurrentItem()
		{
			if (!((Object)(object)baboonBirdAI.heldScrap == (Object)null))
			{
				baboonBirdAI.Call("DropHeldItemAndSync");
			}
		}

		public override void DestroyAndCleanUp()
		{
			if (!((EnemyAI)baboonBirdAI).isEnemyDead && (Object)(object)baboonBirdAI.heldScrap != (Object)null)
			{
				DropCurrentItem();
			}
			base.DestroyAndCleanUp();
		}

		public override string GetSecondarySkillName()
		{
			return ((Object)(object)baboonBirdAI.heldScrap == (Object)null) ? "Grab item" : "Drop item";
		}
	}
	internal class HoardingBugEnemyController : EnemyAIController
	{
		private HoarderBugAI hoarderBugAI;

		private List<Type> allowedGrabbableItemUse = new List<Type>
		{
			typeof(ShotgunItem),
			typeof(NoisemakerProp),
			typeof(FlashlightItem)
		};

		private float grabRange = 1.5f;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			hoarderBugAI = (HoarderBugAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void EnableAIControl(bool enabled)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			if (enabled)
			{
				hoarderBugAI.Call("ChooseNestPosition");
				((EnemyAI)hoarderBugAI).SwitchToBehaviourState(0);
			}
			else
			{
				hoarderBugAI.nestPosition = new Vector3(2000f, 2000f, 2000f);
			}
			base.EnableAIControl(enabled);
		}

		protected override void Update()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (isInitialized)
			{
				base.Update();
				if (!isAIControlled)
				{
					hoarderBugAI.nestPosition = new Vector3(2000f, 2000f, 2000f);
				}
			}
		}

		protected override void UsePrimarySkillAction()
		{
			if (hoarderBugAI.heldItem != null)
			{
				UseHeldItem();
			}
		}

		protected override void UseSecondarySkillAction()
		{
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Using hoarder bug secondary");
			if (hoarderBugAI.heldItem == null)
			{
				GrabNearbyItem();
			}
			else
			{
				DropCurrentItem();
			}
		}

		public void UseHeldItem()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			GrabbableObject itemGrabbableObject = hoarderBugAI.heldItem.itemGrabbableObject;
			Type type = ((object)itemGrabbableObject).GetType();
			if (allowedGrabbableItemUse.Contains(type))
			{
				if (type == typeof(ShotgunItem))
				{
					ShotgunItem val = (ShotgunItem)itemGrabbableObject;
					val.gunShootAudio.volume = 0.15f;
					val.shotgunRayPoint = enemyGameObject.transform;
					val.ShootGunAndSync(false);
				}
				else
				{
					itemGrabbableObject.UseItemOnClient(true);
				}
			}
		}

		public void GrabNearbyItem()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (hoarderBugAI.heldItem != null)
			{
				return;
			}
			Collider[] array = Physics.OverlapSphere(enemyGameObject.transform.position, grabRange);
			for (int i = 0; i < array.Length; i++)
			{
				GrabbableObject componentInChildren = ((Component)array[i]).GetComponentInChildren<GrabbableObject>();
				if ((Object)(object)componentInChildren != (Object)null && hoarderBugAI.heldItem == null)
				{
					NetworkObject component = ((Component)componentInChildren).GetComponent<NetworkObject>();
					if ((Object)(object)component != (Object)null)
					{
						hoarderBugAI.targetItem = componentInChildren;
						hoarderBugAI.Call("GrabTargetItemIfClose");
						break;
					}
				}
			}
		}

		public void DropCurrentItem()
		{
			if (hoarderBugAI.heldItem != null)
			{
				hoarderBugAI.Call("DropItemAndCallDropRPC", ((Component)hoarderBugAI.heldItem.itemGrabbableObject).GetComponent<NetworkObject>(), false);
			}
		}

		public override string GetPrimarySkillName()
		{
			return (hoarderBugAI.heldItem != null && allowedGrabbableItemUse.Contains(((object)hoarderBugAI.heldItem.itemGrabbableObject).GetType())) ? "Use item" : "";
		}

		public override string GetSecondarySkillName()
		{
			return (hoarderBugAI.heldItem == null) ? "Grab item" : "Drop item";
		}
	}
	internal class JesterEnemyController : EnemyAIController
	{
		private JesterAI jesterEnemyAI;

		private const int JESTER_DEFAULT_MODE = 0;

		private const int JESTER_CRANK_MODE_INDEX = 1;

		private const int JESTER_POP_OUT_INDEX = 2;

		private float initialWalkSpeed;

		private float initialRunSpeed;

		private bool initialControlRotation;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			jesterEnemyAI = (JesterAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
			initialWalkSpeed = base.WalkSpeed;
			initialRunSpeed = base.RunSpeed;
			initialControlRotation = controlEnemyRotation;
		}

		protected override void Update()
		{
			base.Update();
			if (IsCranking())
			{
				controlEnemyMovement = false;
				controlEnemyRotation = false;
			}
			else if (IsPoppedOut() || IsInBox())
			{
				controlEnemyMovement = initialControlRotation;
				controlEnemyRotation = initialControlRotation;
			}
			if (IsPoppedOut())
			{
				base.WalkSpeed = 10f;
				base.RunSpeed = 15f;
			}
			else if (IsInBox())
			{
				base.WalkSpeed = initialWalkSpeed;
				base.RunSpeed = initialRunSpeed;
			}
		}

		protected override void UsePrimarySkillAction()
		{
			if (!IsInBox())
			{
				ResetState();
			}
		}

		protected override void UseSecondarySkillAction()
		{
			if (IsInBox())
			{
				Cranking();
			}
		}

		protected override void ReleaseSecondarySkillAction()
		{
			if (IsCranking())
			{
				PopOut();
			}
		}

		protected override void Move()
		{
			if (!IsCranking())
			{
				base.Move();
			}
		}

		public override string GetPrimarySkillName()
		{
			return "Close box";
		}

		public override string GetSecondarySkillName()
		{
			return "(HOLD) Play music";
		}

		private void Cranking()
		{
			SwitchAIState(1);
		}

		private void PopOut()
		{
			SwitchAIState(2);
		}

		private void ResetState()
		{
			SwitchAIState(0);
		}

		private bool IsInBox()
		{
			return ((EnemyAI)jesterEnemyAI).currentBehaviourStateIndex == 0;
		}

		private bool IsCranking()
		{
			return ((EnemyAI)jesterEnemyAI).currentBehaviourStateIndex == 1;
		}

		private bool IsPoppedOut()
		{
			return ((EnemyAI)jesterEnemyAI).currentBehaviourStateIndex == 2;
		}
	}
	internal class MouthDogEnemyController : EnemyAIController
	{
		private MouthDogAI mouthDogAI;

		private const int MOUTH_DOG_LUNGE = 2;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			mouthDogAI = (MouthDogAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void UseSecondarySkillAction()
		{
			if (!IsLunging())
			{
				Lunge();
			}
		}

		public override string GetSecondarySkillName()
		{
			return "Lunge";
		}

		private void Lunge()
		{
			((EnemyAI)mouthDogAI).SwitchToBehaviourState(2);
		}

		private bool IsLunging()
		{
			return ((EnemyAI)mouthDogAI).currentBehaviourStateIndex == 2;
		}
	}
	internal class NutcrackerEnemyController : EnemyAIController
	{
		private NutcrackerEnemyAI nutcrackerEnemyAI;

		private const int NUTCRACKER_DEFAULT_MODE = 0;

		private const int NUTCRACKER_SENTRY_MODE = 1;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			nutcrackerEnemyAI = (NutcrackerEnemyAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void Update()
		{
			if (isInitialized)
			{
				base.Update();
				if (!isAIControlled && IsMoving() && ((EnemyAI)nutcrackerEnemyAI).currentBehaviourStateIndex != 0)
				{
					((EnemyAI)nutcrackerEnemyAI).SwitchToBehaviourState(0);
				}
			}
		}

		protected override void UsePrimarySkillAction()

BepInEx/plugins/FlipMods-ReservedFlashlightSlot/ReservedFlashlightSlot.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using ReservedFlashlightSlot.Patches;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedFlashlightSlot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedFlashlightSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5b7d6563-4e51-4a69-bcf9-fa1dea6eff75")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedFlashlightSlot
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> activateFlashlightKey;

		public static ConfigEntry<bool> hideFlashlightMeshShoulder;

		public static string activateFlashlightDisplayName;

		public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>();

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			activateFlashlightKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedFlashlightSlot", "ActivateFlashlightKey", "<Keyboard>/f", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)");
			hideFlashlightMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedFlashlightSlot", "HideFlashlightOnShoulder", false, "Hides the flashlight mesh while on your shoulder. Only applies in scenarios where you can view your player in third person.");
			activateFlashlightDisplayName = GetDisplayName(activateFlashlightKey.Value);
			currentConfigEntries.Add(((ConfigEntryBase)activateFlashlightKey).Definition.Key, (ConfigEntryBase)(object)activateFlashlightKey);
			currentConfigEntries.Add(((ConfigEntryBase)hideFlashlightMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideFlashlightMeshShoulder);
			TryRemoveOldConfigSettings();
		}

		public static string GetDisplayName(string key)
		{
			key = key.Replace("<Keyboard>/", "");
			key = key.Replace("<Mouse>/", "");
			string text = key;
			text = text.Replace("leftAlt", "Alt");
			text = text.Replace("rightAlt", "Alt");
			text = text.Replace("leftCtrl", "Ctrl");
			text = text.Replace("rightCtrl", "Ctrl");
			text = text.Replace("leftShift", "Shift");
			text = text.Replace("rightShift", "Shift");
			text = text.Replace("leftButton", "LMB");
			text = text.Replace("rightButton", "RMB");
			return text.Replace("middleButton", "MMB");
		}

		public static void TryRemoveOldConfigSettings()
		{
			HashSet<string> hashSet = new HashSet<string>();
			HashSet<string> hashSet2 = new HashSet<string>();
			foreach (ConfigEntryBase value in currentConfigEntries.Values)
			{
				hashSet.Add(value.Definition.Section);
				hashSet2.Add(value.Definition.Key);
			}
			try
			{
				Plugin.Log("Cleaning old config entries");
				ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config;
				string configFilePath = config.ConfigFilePath;
				if (!File.Exists(configFilePath))
				{
					return;
				}
				string text = File.ReadAllText(configFilePath);
				string[] array = File.ReadAllLines(configFilePath);
				string text2 = "";
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = array[i].Replace("\n", "");
					if (array[i].Length <= 0)
					{
						continue;
					}
					if (array[i].StartsWith("["))
					{
						if (text2 != "" && !hashSet.Contains(text2))
						{
							text2 = "[" + text2 + "]";
							int num = text.IndexOf(text2);
							int num2 = text.IndexOf(array[i]);
							text = text.Remove(num, num2 - num);
						}
						text2 = array[i].Replace("[", "").Replace("]", "").Trim();
					}
					else
					{
						if (!(text2 != ""))
						{
							continue;
						}
						if (i <= array.Length - 4 && array[i].StartsWith("##"))
						{
							int j;
							for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++)
							{
							}
							if (hashSet.Contains(text2))
							{
								int num3 = array[i + j - 1].IndexOf("=");
								string item = array[i + j - 1].Substring(0, num3 - 1);
								if (!hashSet2.Contains(item))
								{
									int num4 = text.IndexOf(array[i]);
									int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length;
									text = text.Remove(num4, num5 - num4);
								}
							}
							i += j - 1;
						}
						else if (array[i].Length > 3)
						{
							text = text.Replace(array[i], "");
						}
					}
				}
				if (!hashSet.Contains(text2))
				{
					text2 = "[" + text2 + "]";
					int num6 = text.IndexOf(text2);
					text = text.Remove(num6, text.Length - num6);
				}
				while (text.Contains("\n\n\n"))
				{
					text = text.Replace("\n\n\n", "\n\n");
				}
				File.WriteAllText(configFilePath, text);
				config.Reload();
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "1.6.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

		private static ManualLogSource logger;

		public static ReservedItemInfo proFlashlightInfo = new ReservedItemInfo("Pro-flashlight", 120, false, false, false, false);

		public static ReservedItemInfo flashlightInfo = new ReservedItemInfo("Flashlight", 120, false, false, false, false);

		public static ReservedItemInfo laserPointerInfo = new ReservedItemInfo("Laser pointer", 120, false, false, false, false);

		private void Awake()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			instance = this;
			CreateCustomLogger();
			ConfigSettings.BindConfigSettings();
			_harmony = new Harmony("ReservedFlashlightSlot");
			PatchAll();
			Log("ReservedFlashlightSlot loaded");
		}

		private void PatchAll()
		{
			IEnumerable<Type> enumerable;
			try
			{
				enumerable = Assembly.GetExecutingAssembly().GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				enumerable = ex.Types.Where((Type t) => t != null);
			}
			foreach (Type item in enumerable)
			{
				_harmony.PatchAll(item);
			}
		}

		private void CreateCustomLogger()
		{
			try
			{
				logger = Logger.CreateLogSource($"{((BaseUnityPlugin)this).Info.Metadata.Name}-{((BaseUnityPlugin)this).Info.Metadata.Version}");
			}
			catch
			{
				logger = ((BaseUnityPlugin)this).Logger;
			}
		}

		public static void Log(string message)
		{
			logger.LogInfo((object)message);
		}

		public static void LogError(string message)
		{
			logger.LogError((object)message);
		}

		public static void LogWarning(string message)
		{
			logger.LogWarning((object)message);
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedFlashlightSlot";

		public const string PLUGIN_NAME = "ReservedFlashlightSlot";

		public const string PLUGIN_VERSION = "1.6.3";
	}
}
namespace ReservedFlashlightSlot.Patches
{
	[HarmonyPatch]
	public class MaskedEnemyPatcher
	{
		public static Dictionary<MaskedPlayerEnemy, GameObject> heldFlashlightsByEnemy = new Dictionary<MaskedPlayerEnemy, GameObject>();

		public static HashSet<MaskedPlayerEnemy> spawnedEnemies = new HashSet<MaskedPlayerEnemy>();

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "OnDestroy")]
		[HarmonyPrefix]
		public static void OnDestroy(MaskedPlayerEnemy __instance)
		{
			if (heldFlashlightsByEnemy.TryGetValue(__instance, out var value))
			{
				Plugin.LogWarning("Destroying flashlight. Enemy destroyed.");
				Object.DestroyImmediate((Object)(object)value);
				spawnedEnemies.Remove(__instance);
			}
			heldFlashlightsByEnemy.Remove(__instance);
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "LateUpdate")]
		[HarmonyPostfix]
		public static void ShowWalkieOnEnemy(MaskedPlayerEnemy __instance)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: 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)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			if (!spawnedEnemies.Contains(__instance) && SyncManager.syncReservedItemsList.Contains(Plugin.proFlashlightInfo) && !((EnemyAI)__instance).isEnemyDead && !heldFlashlightsByEnemy.ContainsKey(__instance) && (Object)(object)__instance.mimickingPlayer != (Object)null && PlayerPatcher.allPlayerData.TryGetValue(__instance.mimickingPlayer, out var value))
			{
				spawnedEnemies.Add(__instance);
				FlashlightItem reservedFlashlight = FlashlightPatcher.GetReservedFlashlight(value.playerController);
				if ((Object)(object)reservedFlashlight != (Object)null)
				{
					Plugin.LogWarning("OnMaskedEnemySpawn - MimickingPlayer: " + ((Object)value.playerController).name + " - Spawning flashlight object on enemy.");
					GameObject val = new GameObject("ReservedFlashlight [MaskedEnemy]");
					Light[] componentsInChildren = ((Component)reservedFlashlight).GetComponentsInChildren<Light>();
					MeshRenderer mainObjectRenderer = ((GrabbableObject)reservedFlashlight).mainObjectRenderer;
					Light[] array = componentsInChildren;
					foreach (Light val2 in array)
					{
						Light component = Object.Instantiate<GameObject>(((Component)val2).gameObject, ((Component)val2).transform.localPosition, ((Component)val2).transform.localRotation, val.transform).GetComponent<Light>();
						((Behaviour)component).enabled = true;
						((Component)component).gameObject.layer = 6;
					}
					MeshRenderer component2 = Object.Instantiate<GameObject>(((Component)mainObjectRenderer).gameObject, ((Component)mainObjectRenderer).transform.localPosition, ((Component)mainObjectRenderer).transform.localRotation, val.transform).GetComponent<MeshRenderer>();
					((Renderer)component2).enabled = true;
					((Component)component2).gameObject.layer = 6;
					val.transform.localScale = ((Component)reservedFlashlight).transform.localScale;
					heldFlashlightsByEnemy.Add(__instance, val);
				}
			}
			if (heldFlashlightsByEnemy.TryGetValue(__instance, out var value2))
			{
				if (((EnemyAI)__instance).isEnemyDead)
				{
					Plugin.LogWarning("Destroying flashlight. Enemy dead.");
					Object.DestroyImmediate((Object)(object)value2);
					spawnedEnemies.Remove(__instance);
					heldFlashlightsByEnemy.Remove(__instance);
				}
				else
				{
					Transform parent = ((EnemyAI)__instance).eye.parent.parent;
					value2.transform.rotation = parent.rotation * Quaternion.Euler(FlashlightPatcher.playerShoulderRotationOffset);
					value2.transform.position = parent.position + parent.rotation * FlashlightPatcher.playerShoulderPositionOffset;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class FlashlightPatcher
	{
		public static Vector3 playerShoulderPositionOffset = new Vector3(0.2f, 0.25f, 0f);

		public static Vector3 playerShoulderRotationOffset = new Vector3(90f, 0f, 0f);

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static PlayerControllerB GetPreviousPlayerHeldBy(FlashlightItem flashlightItem)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			return (PlayerControllerB)Traverse.Create((object)flashlightItem).Field("previousPlayerHeldBy").GetValue();
		}

		public static FlashlightItem GetMainFlashlight(PlayerControllerB playerController)
		{
			return GetCurrentlySelectedFlashlight(playerController) ?? GetReservedFlashlight(playerController);
		}

		public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController)
		{
			ReservedPlayerData value;
			return (FlashlightItem)((SyncManager.syncReservedItemsList.Contains(Plugin.flashlightInfo) && PlayerPatcher.allPlayerData.TryGetValue(playerController, out value)) ? /*isinst with value type is only supported in some contexts*/: null);
		}

		public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController)
		{
			return (FlashlightItem)((playerController.currentItemSlot >= 0 && playerController.currentItemSlot < playerController.ItemSlots.Length) ? /*isinst with value type is only supported in some contexts*/: null);
		}

		public static bool IsFlashlightOn(PlayerControllerB playerController)
		{
			return ((GrabbableObject)(GetMainFlashlight(playerController)?)).isBeingUsed ?? false;
		}

		[HarmonyPatch(typeof(FlashlightItem), "SwitchFlashlight")]
		[HarmonyPostfix]
		public static void OnSwitchOnOffFlashlight(bool on, FlashlightItem __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, on);
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "PocketItem")]
		[HarmonyPostfix]
		public static void OnPocketFlashlightLocal(FlashlightItem __instance)
		{
			OnPocketFlashlight(__instance, ((GrabbableObject)__instance).isBeingUsed);
		}

		[HarmonyPatch(typeof(FlashlightItem), "PocketFlashlightClientRpc")]
		[HarmonyPrefix]
		public static void OnPocketFlashlightClientRpc(bool stillUsingFlashlight, FlashlightItem __instance)
		{
			if (NetworkHelper.IsValidClientRpcExecStage((NetworkBehaviour)(object)__instance) && !((NetworkBehaviour)__instance).IsOwner && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController))
			{
				OnPocketFlashlight(__instance, stillUsingFlashlight);
			}
		}

		private static void OnPocketFlashlight(FlashlightItem flashlightItem, bool stillUsingFlashlight = false)
		{
			if ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null)
			{
				return;
			}
			FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy);
			FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy);
			bool flag = stillUsingFlashlight || ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed);
			if ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed)
			{
				((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = null;
			}
			else if (((GrabbableObject)flashlightItem).isBeingUsed)
			{
				((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)flashlightItem;
			}
			else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight.isBeingUsed))
			{
				((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
			}
			MeshRenderer[] componentsInChildren = ((Component)flashlightItem).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = (((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)(object)localPlayerController) ? 23 : 6);
				}
			}
			if ((Object)(object)flashlightItem == (Object)(object)reservedFlashlight)
			{
				((GrabbableObject)flashlightItem).parentObject = ((GrabbableObject)flashlightItem).playerHeldBy.playerGlobalHead.parent;
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "EquipItem")]
		[HarmonyPostfix]
		public static void OnEquipFlashlight(FlashlightItem __instance)
		{
			if ((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)
			{
				return;
			}
			bool mainFlashlightActive = ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight != (Object)null && ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed) || ((GrabbableObject)__instance).isBeingUsed;
			FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)__instance).playerHeldBy);
			if (((GrabbableObject)__instance).isBeingUsed || (Object)(object)__instance == (Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight)
			{
				((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = null;
			}
			else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed))
			{
				((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
			}
			MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = 6;
				}
			}
			((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder);
			UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, mainFlashlightActive);
		}

		[HarmonyPatch(typeof(FlashlightItem), "DiscardItem")]
		[HarmonyPrefix]
		public static void ResetPocketedFlashlight(FlashlightItem __instance)
		{
			PlayerControllerB previousPlayerHeldBy = GetPreviousPlayerHeldBy(__instance);
			if ((Object)(object)previousPlayerHeldBy == (Object)null)
			{
				return;
			}
			FlashlightItem reservedFlashlight = GetReservedFlashlight(previousPlayerHeldBy);
			if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)__instance == (Object)(object)previousPlayerHeldBy.pocketedFlashlight || (Object)(object)previousPlayerHeldBy.pocketedFlashlight == (Object)null))
			{
				previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
			}
			MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = 6;
				}
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
		[HarmonyPostfix]
		public static void SetPositionOffset(GrabbableObject __instance)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance.parentObject != (Object)null && __instance.isPocketed && (Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy))
			{
				Transform transform = ((Component)__instance.parentObject).transform;
				((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset);
				((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset;
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")]
		[HarmonyPrefix]
		public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance)
		{
			if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && !ConfigSettings.hideFlashlightMeshShoulder.Value && !ReservedItemPatcher.ReservedItemIsBeingGrabbed(__instance))
			{
				enable = true;
			}
		}

		private static void UpdateAllFlashlightStates(PlayerControllerB playerController, bool mainFlashlightActive = true)
		{
			FlashlightItem mainFlashlight = GetMainFlashlight(playerController);
			if ((Object)(object)mainFlashlight == (Object)null)
			{
				((Behaviour)playerController.helmetLight).enabled = false;
				mainFlashlightActive = false;
			}
			else
			{
				playerController.ChangeHelmetLight(mainFlashlight.flashlightTypeID, mainFlashlightActive && (Object)(object)playerController == (Object)(object)localPlayerController && (Object)(object)playerController.ItemSlots[playerController.currentItemSlot] != (Object)(object)mainFlashlight);
			}
			for (int i = 0; i < playerController.ItemSlots.Length; i++)
			{
				GrabbableObject obj = playerController.ItemSlots[i];
				FlashlightItem val = (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					UpdateFlashlightState(val, (Object)(object)val == (Object)(object)mainFlashlight && mainFlashlightActive);
				}
			}
		}

		private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy;
				((GrabbableObject)flashlightItem).isBeingUsed = active;
				bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem;
				((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag;
				((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag;
				flashlightItem.usingPlayerHelmetLight = active && !flag;
			}
		}
	}
}
namespace ReservedFlashlightSlot.Input
{
	internal class InputUtilsCompat
	{
		internal static InputActionAsset Asset => IngameKeybinds.GetAsset();

		internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils");

		public static InputAction ToggleFlashlightHotkey => IngameKeybinds.Instance.ToggleFlashlightHotkey;
	}
	internal class IngameKeybinds : LcInputActions
	{
		internal static IngameKeybinds Instance = new IngameKeybinds();

		[InputAction("<Keyboard>/f", Name = "[ReservedItemSlots]\nToggle flashlight")]
		public InputAction ToggleFlashlightHotkey { get; set; }

		internal static InputActionAsset GetAsset()
		{
			return ((LcInputActions)Instance).Asset;
		}
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static InputActionAsset Asset;

		public static InputActionMap ActionMap;

		private static InputAction ActivateFlashlightAction;

		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		public static void AddToKeybindMenu()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Log("Initializing hotkeys.");
			if (InputUtilsCompat.Enabled)
			{
				Asset = InputUtilsCompat.Asset;
				ActionMap = Asset.actionMaps[0];
				ActivateFlashlightAction = InputUtilsCompat.ToggleFlashlightHotkey;
			}
			else
			{
				Asset = ScriptableObject.CreateInstance<InputActionAsset>();
				ActionMap = new InputActionMap("ReservedItemSlots");
				InputActionSetupExtensions.AddActionMap(Asset, ActionMap);
				ActivateFlashlightAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ToggleFlashlight", (InputActionType)0, ConfigSettings.activateFlashlightKey.Value, (string)null, (string)null, (string)null, (string)null);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable()
		{
			Asset.Enable();
			ActivateFlashlightAction.performed += OnActivateFlashlightPerformed;
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable()
		{
			Asset.Disable();
			ActivateFlashlightAction.performed -= OnActivateFlashlightPerformed;
		}

		private static void OnActivateFlashlightPerformed(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject))
			{
				return;
			}
			FlashlightItem mainFlashlight = FlashlightPatcher.GetMainFlashlight(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null) && !ShipBuildModeManager.Instance.InBuildMode && !localPlayerController.inTerminalMenu)
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}
	}
}

BepInEx/plugins/Jordo-NeedyCats/NeedyCats.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using Unity.Netcode.Samples;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("NeedyCats")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NeedyCats")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("c7d3e258-85ed-4246-9766-b0915f7aec88")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace NeedyCats
{
	public class NeedyCatProp : PhysicsProp, INoiseListener
	{
		[Space(3f)]
		public Animator animator;

		public AudioSource audioSource;

		public SkinnedMeshRenderer skinnedMeshRenderer;

		[Space(3f)]
		public Vector2 IntervalMeow;

		public Vector2 IntervalMove;

		public Vector2 IntervalSitAnimChange;

		public Vector2 IntervalIdleAnimChange;

		public float WalkingSpeed = 1f;

		public float RunningSpeed = 8f;

		private (int, float)[] placeableMeowInterval;

		[HideInInspector]
		public (string, int)[] CatNames;

		private float timeBeforeNextMove = 1f;

		private float timeBeforeNextMeow = 1f;

		private float timeBeforeNextSitAnim = 1f;

		private int sitAnimationsLength = 3;

		private float timeBeforeNextIdleAnim = 1f;

		private int idleAnimationsLength = 4;

		private bool isSitting;

		private int materialIndex;

		private int nameIndex;

		private bool hasLoadedSave;

		private HoarderBugItem hoarderBugItem;

		[Space(3f)]
		public AudioClip[] noiseSFX;

		public AudioClip[] fleeSFX;

		public AudioClip[] calmSFX;

		[Space(3f)]
		public float noiseRange = 65f;

		public float maxLoudness = 1f;

		public float minLoudness = 0.95f;

		public float minPitch = 0.9f;

		public float maxPitch = 1f;

		private NavMeshAgent agent;

		private Random random;

		[Space(3f)]
		public Vector3 destination;

		private GameObject[] allAINodes;

		private NavMeshPath navmeshPath;

		private float velX;

		private float velY;

		private Vector3 previousPosition;

		private Vector3 agentLocalVelocity;

		private ClientNetworkTransform clientNetworkTransform;

		private bool isBeingHoarded
		{
			get
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				if (hoarderBugItem != null)
				{
					return Vector3.Distance(((Component)this).transform.position, hoarderBugItem.itemNestPosition) < 2f;
				}
				return false;
			}
		}

		public void Awake()
		{
		}

		public override void Start()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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_00c8: Expected O, but got Unknown
			((GrabbableObject)this).Start();
			try
			{
				if ((Object)(object)agent == (Object)null)
				{
					agent = ((Component)this).GetComponent<NavMeshAgent>();
				}
				if ((Object)(object)animator == (Object)null)
				{
					animator = ((Component)this).GetComponentInChildren<Animator>();
				}
				if ((Object)(object)skinnedMeshRenderer == (Object)null)
				{
					skinnedMeshRenderer = ((Component)this).GetComponentInChildren<SkinnedMeshRenderer>();
				}
				clientNetworkTransform = ((Component)this).GetComponent<ClientNetworkTransform>();
				random = new Random(StartOfRound.Instance.randomMapSeed + 85);
				GameObject[] first = GameObject.FindGameObjectsWithTag("AINode");
				GameObject[] second = GameObject.FindGameObjectsWithTag("OutsideAINode");
				allAINodes = first.Concat(second).ToArray();
				agent.updatePosition = false;
				destination = ((Component)this).transform.position;
				navmeshPath = new NavMeshPath();
				((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback += NetworkManager_OnClientConnectedCallback;
				placeableMeowInterval = new(int, float)[3]
				{
					(22, 10f),
					(21, 2f),
					(4, 6f)
				};
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"Error when initializing variables for {((Object)((Component)this).gameObject).name} : {arg}");
			}
			if (((NetworkBehaviour)this).IsServer && !hasLoadedSave)
			{
				nameIndex = Random.Range(0, CatNames.Length);
				SetCatNameServerRpc(CatNames[nameIndex].Item1);
				if (CatNames[nameIndex].Item2 != -1)
				{
					materialIndex = CatNames[nameIndex].Item2;
				}
				else
				{
					materialIndex = Random.Range(0, ((GrabbableObject)this).itemProperties.materialVariants.Length);
				}
				SetCatMaterialServerRpc(materialIndex);
			}
		}

		public override void OnDestroy()
		{
			((NetworkBehaviour)this).OnDestroy();
			((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback -= NetworkManager_OnClientConnectedCallback;
		}

		private void NetworkManager_OnClientConnectedCallback(ulong obj)
		{
			if (((NetworkBehaviour)this).IsServer)
			{
				SetCatMaterialServerRpc(materialIndex);
				SetCatNameServerRpc(CatNames[nameIndex].Item1);
				if (isSitting)
				{
					MakeCatSitServerRpc(sit: true);
				}
			}
		}

		public override void LoadItemSaveData(int saveData)
		{
			((MonoBehaviour)this).StartCoroutine(NetworkSafeLoadItemSaveData(saveData));
		}

		private IEnumerator NetworkSafeLoadItemSaveData(int saveData)
		{
			yield return ((NetworkBehaviour)this).IsSpawned;
			if (((NetworkBehaviour)this).IsServer)
			{
				<>n__0(saveData);
				int catMaterialServerRpc = (saveData >> 16) & 0xFFFF;
				int num = saveData & 0xFFFF;
				if (num > CatNames.Length)
				{
					num = Random.Range(0, CatNames.Length);
				}
				SetCatNameServerRpc(CatNames[num].Item1);
				if (CatNames[num].Item2 != -1)
				{
					catMaterialServerRpc = CatNames[num].Item2;
				}
				SetCatMaterialServerRpc(catMaterialServerRpc);
				materialIndex = catMaterialServerRpc;
				nameIndex = num;
				hasLoadedSave = true;
			}
		}

		public override int GetItemDataToSave()
		{
			return (materialIndex << 16) | nameIndex;
		}

		private void SynchronizeAnimator(float maxSpeed = 4f)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			agentLocalVelocity = ((Component)animator).transform.InverseTransformDirection(Vector3.ClampMagnitude(((Component)this).transform.position - previousPosition, 1f) / (Time.deltaTime * 2f));
			animator.SetBool("move", ((Vector3)(ref agentLocalVelocity)).magnitude > 0.05f);
			velX = Mathf.Lerp(velX, agentLocalVelocity.x, 10f * Time.deltaTime);
			animator.SetFloat("velx", Mathf.Clamp(velX, 0f - maxSpeed, maxSpeed));
			velY = Mathf.Lerp(velY, agentLocalVelocity.z, 10f * Time.deltaTime);
			animator.SetFloat("vely", Mathf.Clamp(velY, 0f - maxSpeed, maxSpeed));
			previousPosition = ((Component)this).transform.position;
		}

		public override void GrabItem()
		{
			animator.SetBool("move", false);
			animator.SetFloat("velx", 0f);
			animator.SetFloat("vely", 0f);
			animator.SetBool("held", true);
			isSitting = false;
			((GrabbableObject)this).GrabItem();
			if (((NetworkBehaviour)this).IsOwner)
			{
				HUDManager.Instance.DisplayTip("Cat Facts", "Too noisy? Give your cat a pet to quiet it down for a bit!", false, true, "LC_NeedyCatsTip");
			}
		}

		public override void DiscardItem()
		{
			animator.SetBool("held", false);
			((GrabbableObject)this).DiscardItem();
		}

		public override void GrabItemFromEnemy(EnemyAI enemy)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			((GrabbableObject)this).isHeldByEnemy = true;
			animator.SetBool("move", false);
			animator.SetFloat("velx", 0f);
			animator.SetFloat("vely", 0f);
			animator.SetBool("held", true);
			((GrabbableObject)this).GrabItemFromEnemy(enemy);
			if (((NetworkBehaviour)this).IsServer && enemy is HoarderBugAI)
			{
				HoarderBugAI val = (HoarderBugAI)enemy;
				hoarderBugItem = (((Object)(object)val.heldItem.itemGrabbableObject == (Object)(object)this) ? val.heldItem : null);
			}
		}

		public override void DiscardItemFromEnemy()
		{
			((GrabbableObject)this).isHeldByEnemy = false;
			animator.SetBool("held", false);
			((GrabbableObject)this).DiscardItemFromEnemy();
		}

		public override void Update()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)clientNetworkTransform).enabled = !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy;
			if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((NetworkBehaviour)this).IsOwner)
			{
				((Component)this).GetComponent<NetworkObject>().RemoveOwnership();
			}
			if (!((GrabbableObject)this).isInElevator && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap)
			{
				((Behaviour)agent).enabled = !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && ((GrabbableObject)this).reachedFloorTarget && !(((GrabbableObject)this).fallTime < 1f);
				if (((GrabbableObject)this).fallTime >= 1f && !((GrabbableObject)this).reachedFloorTarget)
				{
					((GrabbableObject)this).targetFloorPosition = ((Component)this).transform.position;
					destination = ((Component)this).transform.position;
					previousPosition = ((Component)this).transform.position;
					((Behaviour)agent).enabled = true;
				}
			}
			if (((GrabbableObject)this).fallTime >= 1f && !((GrabbableObject)this).reachedFloorTarget && animator.GetBool("held"))
			{
				animator.SetBool("held", false);
			}
			if (((GrabbableObject)this).isHeld || ((GrabbableObject)this).isHeldByEnemy || !((GrabbableObject)this).reachedFloorTarget || ((GrabbableObject)this).fallTime < 1f || ((GrabbableObject)this).isInElevator)
			{
				((GrabbableObject)this).Update();
			}
			if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && (((GrabbableObject)this).isInElevator || isBeingHoarded) && !isSitting)
			{
				MakeCatSitServerRpc(sit: true);
			}
			else if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((GrabbableObject)this).isInElevator && !isBeingHoarded && isSitting && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap)
			{
				MakeCatSitServerRpc(sit: false);
			}
			if (((NetworkBehaviour)this).IsServer)
			{
				if (isSitting)
				{
					if (timeBeforeNextSitAnim <= 0f)
					{
						SetCatSitAnimationServerRpc(Random.Range(0, sitAnimationsLength));
						timeBeforeNextSitAnim = Random.Range(IntervalSitAnimChange.x, IntervalSitAnimChange.y);
					}
					timeBeforeNextSitAnim -= Time.deltaTime;
				}
				else
				{
					if (timeBeforeNextIdleAnim <= 0f)
					{
						SetCatIdleAnimationServerRpc(Random.Range(0, idleAnimationsLength));
						timeBeforeNextIdleAnim = Random.Range(IntervalIdleAnimChange.x, IntervalIdleAnimChange.y);
					}
					timeBeforeNextIdleAnim -= Time.deltaTime;
				}
				if (timeBeforeNextMeow <= 0f)
				{
					MakeCatMeowServerRpc();
					float num = 0f;
					if (((GrabbableObject)this).isInElevator)
					{
						PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
						foreach (PlayerControllerB val in allPlayerScripts)
						{
							if (val.isInElevator)
							{
								num += 2f;
								break;
							}
						}
						(int, float)[] array = placeableMeowInterval;
						for (int j = 0; j < array.Length; j++)
						{
							(int, float) tuple = array[j];
							if (StartOfRound.Instance.SpawnedShipUnlockables.ContainsKey(tuple.Item1))
							{
								num += tuple.Item2;
							}
						}
					}
					timeBeforeNextMeow = Random.Range(IntervalMeow.x + num, IntervalMeow.y + num);
				}
				timeBeforeNextMeow -= Time.deltaTime;
				if (!((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((GrabbableObject)this).isInElevator && !isBeingHoarded && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap)
				{
					if (timeBeforeNextMove <= 0f)
					{
						SetRandomDestination();
						timeBeforeNextMove = Random.Range(IntervalMove.x, IntervalMove.y);
					}
					timeBeforeNextMove -= Time.deltaTime;
					((Component)this).transform.position = agent.nextPosition;
				}
			}
			if (!((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy)
			{
				SynchronizeAnimator();
			}
		}

		public void SetDestinationToPosition(Vector3 position, bool checkForPath = false)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			if (checkForPath)
			{
				position = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 1.75f, -1);
				navmeshPath = new NavMeshPath();
				if (!agent.CalculatePath(position, navmeshPath))
				{
					Debug.Log((object)(((Object)((Component)this).gameObject).name + " calculatepath returned false."));
					return;
				}
				if (Vector3.Distance(navmeshPath.corners[navmeshPath.corners.Length - 1], RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 2.7f, -1)) > 1.55f)
				{
					Debug.Log((object)(((Object)((Component)this).gameObject).name + " path calculation went wrong."));
					return;
				}
			}
			destination = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, -1f, -1);
			agent.SetDestination(destination);
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (((NetworkBehaviour)this).IsOwner)
			{
				MakeCatCalmServerRpc();
			}
		}

		public void SetRandomDestination()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_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_0032: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)this).transform.position + Random.insideUnitSphere * 5f;
			agent.speed = WalkingSpeed;
			SetDestinationToPosition(position);
		}

		private void PlayCatNoise(AudioClip[] array, bool audible = true)
		{
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			int num = random.Next(0, array.Length);
			float num2 = (float)random.Next((int)(minLoudness * 100f), (int)(maxLoudness * 100f)) / 100f;
			float pitch = (float)random.Next((int)(minPitch * 100f), (int)(maxPitch * 100f)) / 100f;
			audioSource.pitch = pitch;
			audioSource.PlayOneShot(array[num], num2);
			WalkieTalkie.TransmitOneShotAudio(audioSource, array[num], num2 - 0.4f);
			if (audible)
			{
				noiseRange = (((GrabbableObject)this).isInElevator ? (noiseRange - 2.5f) : noiseRange);
				RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange, num2, 0, ((GrabbableObject)this).isInElevator && StartOfRound.Instance.hangarDoorsClosed, 8881);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MakeCatMeowServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3454429685u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3454429685u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					MakeCatMeowClientRpc();
				}
			}
		}

		[ClientRpc]
		public void MakeCatMeowClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1946573138u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1946573138u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayCatNoise(noiseSFX);
					animator.SetTrigger("meow");
				}
			}
		}

		[ServerRpc]
		public void MakeCatCalmServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2784153610u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2784153610u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			float num = 0f;
			if (((GrabbableObject)this).isInElevator)
			{
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				foreach (PlayerControllerB val3 in allPlayerScripts)
				{
					if (val3.isInElevator)
					{
						num += 2f;
						break;
					}
				}
				(int, float)[] array = placeableMeowInterval;
				for (int j = 0; j < array.Length; j++)
				{
					(int, float) tuple = array[j];
					if (StartOfRound.Instance.SpawnedShipUnlockables.ContainsKey(tuple.Item1))
					{
						num += tuple.Item2;
					}
				}
			}
			timeBeforeNextMeow = Random.Range(IntervalMeow.x + num + 3f, IntervalMeow.y + num + 6f);
			MakeCatCalmClientRpc();
		}

		[ClientRpc]
		public void MakeCatCalmClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2302897036u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2302897036u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((GrabbableObject)this).playerHeldBy.doingUpperBodyEmote = 1.16f;
					((GrabbableObject)this).playerHeldBy.playerBodyAnimator.SetTrigger("PullGrenadePin2");
					((MonoBehaviour)this).StartCoroutine(PlayCatCalmNoiseDelayed());
				}
			}
		}

		private IEnumerator PlayCatCalmNoiseDelayed()
		{
			yield return (object)new WaitForSeconds(0.5f);
			PlayCatNoise(calmSFX, audible: false);
		}

		[ServerRpc]
		public void MakeCatSitServerRpc(bool sit)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Invalid comparison between Unknown and I4
			//IL_00a5: 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_00b3: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2411027775u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sit, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2411027775u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				MakeCatSitClientRpc(sit);
			}
		}

		[ClientRpc]
		public void MakeCatSitClientRpc(bool sit)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3921800473u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sit, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3921800473u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					animator.SetBool("sit", sit);
					isSitting = sit;
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SetCatMaterialServerRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2046492207u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2046492207u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					SetCatMaterialClientRpc(index);
				}
			}
		}

		[ClientRpc]
		public void SetCatMaterialClientRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3875721248u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3875721248u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && (Object)(object)skinnedMeshRenderer != (Object)null)
				{
					((Renderer)skinnedMeshRenderer).sharedMaterial = ((GrabbableObject)this).itemProperties.materialVariants[index];
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SetCatNameServerRpc(string name)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3049925245u, val, (RpcDelivery)0);
				bool flag = name != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(name, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3049925245u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				SetCatNameClientRpc(name);
			}
		}

		[ClientRpc]
		public void SetCatNameClientRpc(string name)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1321450034u, val, (RpcDelivery)0);
				bool flag = name != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(name, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1321450034u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				((Component)this).GetComponentInChildren<ScanNodeProperties>().headerText = "Cat (" + name + ")";
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SetCatIdleAnimationServerRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1770904636u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1770904636u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					SetCatIdleAnimationClientRpc(index);
				}
			}
		}

		[ClientRpc]
		public void SetCatIdleAnimationClientRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(283245169u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 283245169u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					animator.SetInteger("idleAnimation", index);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SetCatSitAnimationServerRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1062797608u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1062797608u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					SetCatSitAnimationClientRpc(index);
				}
			}
		}

		[ClientRpc]
		public void SetCatSitAnimationClientRpc(int index)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4162097660u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4162097660u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					animator.SetInteger("sitAnimation", index);
				}
			}
		}

		public virtual void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if (((GrabbableObject)this).isHeld || ((GrabbableObject)this).isHeldByEnemy || noiseID == 8881 || noiseID == 75 || ((GrabbableObject)this).isInShipRoom || !StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap)
			{
				return;
			}
			Vector3 val = noisePosition - ((Component)this).transform.position;
			if (!(((Vector3)(ref val)).magnitude < 5f) || !(noiseLoudness > 0.8f))
			{
				return;
			}
			PlayCatNoise(fleeSFX);
			if (((NetworkBehaviour)this).IsServer)
			{
				Vector3 position = ((Component)this).transform.position - ((Vector3)(ref val)).normalized * 20f;
				GameObject[] array = allAINodes.OrderBy((GameObject x) => Vector3.Distance(position, x.transform.position)).ToArray();
				SetDestinationToPosition(array[0].transform.position);
				agent.speed = RunningSpeed;
				timeBeforeNextMove = Random.Range(IntervalMove.x + 1f, IntervalMove.y + 2f);
			}
		}

		[CompilerGenerated]
		[DebuggerHidden]
		private void <>n__0(int saveData)
		{
			((GrabbableObject)this).LoadItemSaveData(saveData);
		}

		protected override void __initializeVariables()
		{
			((PhysicsProp)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NeedyCatProp()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Expected O, but got Unknown
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(3454429685u, new RpcReceiveHandler(__rpc_handler_3454429685));
			NetworkManager.__rpc_func_table.Add(1946573138u, new RpcReceiveHandler(__rpc_handler_1946573138));
			NetworkManager.__rpc_func_table.Add(2784153610u, new RpcReceiveHandler(__rpc_handler_2784153610));
			NetworkManager.__rpc_func_table.Add(2302897036u, new RpcReceiveHandler(__rpc_handler_2302897036));
			NetworkManager.__rpc_func_table.Add(2411027775u, new RpcReceiveHandler(__rpc_handler_2411027775));
			NetworkManager.__rpc_func_table.Add(3921800473u, new RpcReceiveHandler(__rpc_handler_3921800473));
			NetworkManager.__rpc_func_table.Add(2046492207u, new RpcReceiveHandler(__rpc_handler_2046492207));
			NetworkManager.__rpc_func_table.Add(3875721248u, new RpcReceiveHandler(__rpc_handler_3875721248));
			NetworkManager.__rpc_func_table.Add(3049925245u, new RpcReceiveHandler(__rpc_handler_3049925245));
			NetworkManager.__rpc_func_table.Add(1321450034u, new RpcReceiveHandler(__rpc_handler_1321450034));
			NetworkManager.__rpc_func_table.Add(1770904636u, new RpcReceiveHandler(__rpc_handler_1770904636));
			NetworkManager.__rpc_func_table.Add(283245169u, new RpcReceiveHandler(__rpc_handler_283245169));
			NetworkManager.__rpc_func_table.Add(1062797608u, new RpcReceiveHandler(__rpc_handler_1062797608));
			NetworkManager.__rpc_func_table.Add(4162097660u, new RpcReceiveHandler(__rpc_handler_4162097660));
		}

		private static void __rpc_handler_3454429685(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).MakeCatMeowServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1946573138(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).MakeCatMeowClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2784153610(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).MakeCatCalmServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2302897036(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).MakeCatCalmClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2411027775(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00ab: 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_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				bool sit = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sit, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).MakeCatSitServerRpc(sit);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3921800473(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool sit = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sit, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).MakeCatSitClientRpc(sit);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2046492207(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catMaterialServerRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catMaterialServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).SetCatMaterialServerRpc(catMaterialServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3875721248(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catMaterialClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catMaterialClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).SetCatMaterialClientRpc(catMaterialClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3049925245(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string catNameServerRpc = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref catNameServerRpc, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).SetCatNameServerRpc(catNameServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1321450034(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string catNameClientRpc = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref catNameClientRpc, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).SetCatNameClientRpc(catNameClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1770904636(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catIdleAnimationServerRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catIdleAnimationServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).SetCatIdleAnimationServerRpc(catIdleAnimationServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_283245169(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catIdleAnimationClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catIdleAnimationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).SetCatIdleAnimationClientRpc(catIdleAnimationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1062797608(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catSitAnimationServerRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catSitAnimationServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NeedyCatProp)(object)target).SetCatSitAnimationServerRpc(catSitAnimationServerRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4162097660(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int catSitAnimationClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref catSitAnimationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NeedyCatProp)(object)target).SetCatSitAnimationClientRpc(catSitAnimationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "NeedyCatProp";
		}
	}
	public class NoiseListenerRedirect : MonoBehaviour, INoiseListener
	{
		private INoiseListener target;

		public void Awake()
		{
			target = ((Component)((Component)this).transform.parent).GetComponent<INoiseListener>();
		}

		public void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			INoiseListener obj = target;
			if (obj != null)
			{
				obj.DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID);
			}
		}
	}
	[BepInPlugin("Jordo.NeedyCats", "Needy Cats", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class NeedyCatsBase : BaseUnityPlugin
	{
		public static class Assets
		{
			public static string mainAssetBundleName = "needycats";

			public static AssetBundle MainAssetBundle = null;

			private static string GetAssemblyName()
			{
				return Assembly.GetExecutingAssembly().FullName.Split(new char[1] { ',' })[0];
			}

			public static void PopulateAssets()
			{
				if ((Object)(object)MainAssetBundle == (Object)null)
				{
					using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetAssemblyName() + "." + mainAssetBundleName))
					{
						MainAssetBundle = AssetBundle.LoadFromStream(stream);
					}
				}
			}
		}

		private const string modGUID = "Jordo.NeedyCats";

		private const string modName = "Needy Cats";

		private const string modVersion = "1.1.1";

		private readonly Harmony harmony = new Harmony("Jordo.NeedyCats");

		public static NeedyCatsBase Instance;

		private static List<(string, int)> catNames = new List<(string, int)>();

		private static ConfigEntry<int> spawnRate;

		private static ConfigEntry<string> catNamesConfig;

		internal static ManualLogSource mls;

		private string defaultCatNames = "One:Stripes,Bella,Tigger,Chloe,Shadow,Luna,Oreo,Oliver,Kitty,Lucy,Molly,Jasper,Smokey,Gizmo,Simba,Tiger,Charlie,Angel,Jack,Lily,Peanut,Toby,Baby,Loki,Midnight,Milo,Princess,Sophie,Harley,Max,Missy,Rocky,Zoe,CoCo,Misty,Nala,Oscar,Pepper,Sasha,Buddy,Pumpkin,Kiki,Mittens,Bailey,Callie,Lucky,Patches,Simon,Garfield:Orange,George,Maggie,Sammy,Sebastian,Boots,Cali,Felix,Lilly,Phoebe,Sassy,Tucker,Bandit,Dexter,Fiona,Jake,Precious,Romeo,Snickers,Socks,Daisy,Gracie,Lola,Sadie,Sox,Casper,Fluffy,Marley,Minnie,Sweetie,Ziggy,Belle,Blackie,Chester,Frankie,Ginger,Muffin,Murphy,Rusty,Scooter,Batman,Boo,Cleo,Izzy,Jasmine,Mimi,Sugar,Cupcake,Dusty,Leo,Noodle,Panda,Peaches";

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("Jordo.NeedyCats");
			PatchNetcode();
			Assets.PopulateAssets();
			spawnRate = ((BaseUnityPlugin)this).Config.Bind<int>("NeedyCats", "Spawn rate", 20, "Sets the cat's spawn rate (This affects all moons).");
			catNamesConfig = ((BaseUnityPlugin)this).Config.Bind<string>("NeedyCats", "Cat names", defaultCatNames, "Possible cat names separated by a colon (,). If the cat's name is followed by ':', you can input a material that'll be forced for that name among the following: Black, White, Spots, Boots, Orange, Stripes. You can find an image showcasing each material on the mod's wiki on Thunderstore. This list must contain at least one name. Example string: 'Daisy,Garfield:Orange,Chloe'");
			string[] array = catNamesConfig.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				string[] array2 = text.Split(new char[1] { ':' });
				catNames.Add((array2[0], (array2.Length > 1) ? GetMaterialID(array2[1]) : (-1)));
			}
			harmony.PatchAll(typeof(NeedyCatsBase));
			mls.LogInfo((object)"Initialized Needy Cats");
		}

		private int GetMaterialID(string name)
		{
			return name.ToLower() switch
			{
				"black" => 0, 
				"white" => 1, 
				"boots" => 2, 
				"spots" => 3, 
				"orange" => 4, 
				"stripes" => 5, 
				_ => -1, 
			};
		}

		private void PatchNetcode()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPostfix]
		private static void AddNeedyCatsToNetworkManager(GameNetworkManager __instance)
		{
			((Component)__instance).GetComponent<NetworkManager>().AddNetworkPrefab(Assets.MainAssetBundle.LoadAsset<GameObject>("Cat.prefab"));
			mls.LogInfo((object)"Added Needy Cats prefab to Network Manager.");
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void AddNeedyCatsToItems(StartOfRound __instance)
		{
			Item item = Assets.MainAssetBundle.LoadAsset<Item>("CatItem");
			if (!__instance.allItemsList.itemsList.Contains(item))
			{
				__instance.allItemsList.itemsList.Add(item);
			}
			mls.LogInfo((object)"Added Needy Cats to items list.");
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPrefix]
		private static void AddNeedyCatsToAllLevels(StartOfRound __instance)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			Item item = Assets.MainAssetBundle.LoadAsset<Item>("CatItem");
			SpawnableItemWithRarity val = new SpawnableItemWithRarity();
			val.rarity = spawnRate.Value;
			val.spawnableItem = item;
			SelectableLevel[] levels = __instance.levels;
			foreach (SelectableLevel val2 in levels)
			{
				if (val2.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)item))
				{
					return;
				}
				val2.spawnableScrap.Add(val);
			}
			mls.LogInfo((object)"Added Needy Cats to all levels.");
		}

		[HarmonyPatch(typeof(HoarderBugAI), "GrabTargetItemIfClose")]
		[HarmonyPrefix]
		private static bool GrabTargetItemIfClose(HoarderBugAI __instance)
		{
			//IL_003c: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0081: 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)
			float num = ((__instance.targetItem is NeedyCatProp) ? 1f : 0.75f);
			if ((Object)(object)__instance.targetItem != (Object)null && __instance.heldItem == null && Vector3.Distance(((Component)__instance).transform.position, ((Component)__instance.targetItem).transform.position) < num)
			{
				if (!((EnemyAI)__instance).SetDestinationToPosition(__instance.nestPosition, true))
				{
					__instance.nestPosition = ((EnemyAI)__instance).ChooseClosestNodeToPosition(((Component)__instance).transform.position, false, 0).position;
					((EnemyAI)__instance).SetDestinationToPosition(__instance.nestPosition, false);
				}
				NetworkObject component = ((Component)__instance.targetItem).GetComponent<NetworkObject>();
				((EnemyAI)__instance).SwitchToBehaviourStateOnLocalClient(1);
				__instance.GrabItem(component);
				__instance.sendingGrabOrDropRPC = true;
				__instance.GrabItemServerRpc(NetworkObjectReference.op_Implicit(component));
				return true;
			}
			return false;
		}

		[HarmonyPatch(typeof(NeedyCatProp), "Awake")]
		[HarmonyPrefix]
		private static void AddNeedyCatsNames(NeedyCatProp __instance)
		{
			__instance.CatNames = catNames.ToArray();
		}
	}
}

BepInEx/plugins/JunLethalCompany-GamblingMachineAtTheCompany/GamblersMod.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GamblersMod.Patches;
using GamblersMod.Player;
using GamblersMod.RoundManagerCustomSpace;
using GamblersMod.config;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("GamblersMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GamblersMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4389dd08-eb54-4b6f-955c-5f772ecc6fc7")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace GamblersMod
{
	public class GamblingMachineManager : MonoBehaviour
	{
		public List<GameObject> GamblingMachines;

		public static GamblingMachineManager Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			Plugin.mls.LogMessage((object)"Gambling machine manager has awoken!");
			GamblingMachines = new List<GameObject>();
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		public void Spawn(Vector3 spawnPoint, Quaternion quaternion)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			Plugin.mls.LogMessage((object)$"Spawning gambling machine... #{GamblingMachines.Count}");
			GameObject val = Object.Instantiate<GameObject>(Plugin.GamblingMachine, spawnPoint, quaternion);
			val.tag = "Untagged";
			val.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
			val.layer = LayerMask.NameToLayer("InteractableObject");
			val.GetComponent<NetworkObject>().Spawn(false);
			if (GamblingMachines.Count >= 1)
			{
				val.GetComponent<AudioSource>().Pause();
			}
			GamblingMachines.Add(val);
		}

		public void DespawnAll()
		{
			Plugin.mls.LogMessage((object)"Despwawning gambling machine...");
			foreach (GameObject gamblingMachine in GamblingMachines)
			{
				gamblingMachine.GetComponent<NetworkObject>().Despawn(true);
			}
			Reset();
		}

		public void Reset()
		{
			Plugin.mls.LogInfo((object)"Resetting gambling machine manager state...");
			GamblingMachines.Clear();
		}
	}
	[BepInPlugin("Junypai.GamblersMod", "Gamblers Mod", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string modGUID = "Junypai.GamblersMod";

		public const string modName = "Gamblers Mod";

		public const string modVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("Junypai.GamblersMod");

		public static Plugin Instance;

		public static GameObject GamblingMachine;

		public static AudioClip GamblingJackpotScrapAudio;

		public static AudioClip GamblingHalveScrapAudio;

		public static AudioClip GamblingRemoveScrapAudio;

		public static AudioClip GamblingDoubleScrapAudio;

		public static AudioClip GamblingTripleScrapAudio;

		public static AudioClip GamblingDrumrollScrapAudio;

		public static GameObject GamblingATMMachine;

		public static AudioClip GamblingMachineMusicAudio;

		public static GameObject GamblingMachineResultCanvas;

		public static Font GamblingFont;

		public static GameObject GamblingHandIcon;

		public static GambleConfigSettingsSerializable UserConfigSnapshot;

		public static GambleConfigSettingsSerializable RecentHostConfig;

		public static GambleConfigSettingsSerializable CurrentUserConfig;

		public static ManualLogSource mls;

		private void Awake()
		{
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			NetcodeWeaver();
			mls = Logger.CreateLogSource("Junypai.GamblersMod");
			CurrentUserConfig = new GambleConfigSettingsSerializable(((BaseUnityPlugin)this).Config);
			RecentHostConfig = new GambleConfigSettingsSerializable(((BaseUnityPlugin)this).Config);
			UserConfigSnapshot = new GambleConfigSettingsSerializable(((BaseUnityPlugin)this).Config);
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			mls.LogInfo((object)"Loading gambler bundle assets");
			AssetBundle val = AssetBundle.LoadFromFile(Path.Combine(directoryName, "gamblingmachinebundle"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				mls.LogError((object)"Unable to load gambler bundle assets");
			}
			else
			{
				mls.LogInfo((object)"Gamblers bundle assets successfully loaded");
			}
			GamblingDrumrollScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "drumroll");
			GamblingJackpotScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "holyshit");
			GamblingHalveScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "cricket");
			GamblingRemoveScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "womp");
			GamblingMachineMusicAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "machineMusic");
			GamblingDoubleScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "doublekill");
			GamblingTripleScrapAudio = LoadAssetFromAssetBundleAndLogInfo<AudioClip>(val, "triplekill");
			GamblingFont = LoadAssetFromAssetBundleAndLogInfo<Font>(val, "3270-Regular");
			GamblingMachine = LoadAssetFromAssetBundleAndLogInfo<GameObject>(val, "GamblingMachine");
			GamblingHandIcon = LoadAssetFromAssetBundleAndLogInfo<GameObject>(val, "HandIconGO");
			GamblingMachine.AddComponent<GamblingMachine>();
			new GameObject().AddComponent<GamblingMachineManager>();
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(GameNetworkManagerPatch));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(RoundManagerPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
		}

		private T LoadAssetFromAssetBundleAndLogInfo<T>(AssetBundle bundle, string assetName) where T : Object
		{
			T val = bundle.LoadAsset<T>(assetName);
			if (!Object.op_Implicit((Object)(object)val))
			{
				mls.LogError((object)(assetName + " asset failed to load"));
			}
			else
			{
				mls.LogInfo((object)(assetName + " asset successfully loaded"));
			}
			return val;
		}

		private static void NetcodeWeaver()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
	public class StartOfRoundCustom : NetworkBehaviour
	{
		private void Awake()
		{
		}

		[ServerRpc]
		public void DespawnGamblingMachineServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1680317104u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1680317104u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				GamblingMachineManager.Instance.DespawnAll();
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_StartOfRoundCustom()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(1680317104u, new RpcReceiveHandler(__rpc_handler_1680317104));
		}

		private static void __rpc_handler_1680317104(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((StartOfRoundCustom)(object)target).DespawnGamblingMachineServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "StartOfRoundCustom";
		}
	}
}
namespace GamblersMod.RoundManagerCustomSpace
{
	internal class RoundManagerCustom : NetworkBehaviour
	{
		public RoundManager RoundManager;

		private List<Vector3> spawnPoints;

		private void Awake()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			RoundManager = ((Component)this).GetComponent<RoundManager>();
			spawnPoints = new List<Vector3>();
			spawnPoints.Add(new Vector3(-27.808f, -2.6256f, -9.7409f));
			spawnPoints.Add(new Vector3(-27.808f, -2.6256f, -4.7409f));
			spawnPoints.Add(new Vector3(-27.808f, -2.6256f, 0.7409f));
			spawnPoints.Add(new Vector3(-27.808f, -2.6256f, 6.7409f));
		}

		[ServerRpc]
		public void DespawnGamblingMachineServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3258984052u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3258984052u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				GamblingMachineManager.Instance.DespawnAll();
			}
		}

		[ServerRpc]
		public void SpawnGamblingMachineServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2764001088u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2764001088u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Plugin.mls.LogInfo((object)("Attempting to spawn gambling machine at " + ((Object)RoundManager.currentLevel).name));
				for (int i = 0; i < Plugin.CurrentUserConfig.configNumberOfMachines && i < spawnPoints.Count; i++)
				{
					GamblingMachineManager.Instance.Spawn(spawnPoints[i], Quaternion.Euler(0f, 90f, 0f));
					Plugin.mls.LogInfo((object)$"Spawned machine number: {i}");
				}
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_RoundManagerCustom()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(3258984052u, new RpcReceiveHandler(__rpc_handler_3258984052));
			NetworkManager.__rpc_func_table.Add(2764001088u, new RpcReceiveHandler(__rpc_handler_2764001088));
		}

		private static void __rpc_handler_3258984052(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((RoundManagerCustom)(object)target).DespawnGamblingMachineServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2764001088(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((RoundManagerCustom)(object)target).SpawnGamblingMachineServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "RoundManagerCustom";
		}
	}
}
namespace GamblersMod.Player
{
	internal class PlayerControllerCustom : NetworkBehaviour
	{
		private PlayerGamblingUIManager PlayerGamblingUIManager;

		private PlayerControllerB PlayerControllerOriginal;

		public bool isUsingGamblingMachine;

		private void Awake()
		{
			PlayerGamblingUIManager = ((Component)this).gameObject.AddComponent<PlayerGamblingUIManager>();
			PlayerControllerOriginal = ((Component)this).gameObject.GetComponent<PlayerControllerB>();
		}

		private void Update()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0039: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)this).IsOwner)
			{
				return;
			}
			Camera gameplayCamera = PlayerControllerOriginal.gameplayCamera;
			Vector3 position = ((Component)gameplayCamera).transform.position;
			Vector3 forward = ((Component)gameplayCamera).transform.forward;
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(position, forward);
			float num = 5f;
			int num2 = 512;
			RaycastHit val2 = default(RaycastHit);
			bool flag = Physics.Raycast(val, ref val2, num, num2);
			if (Object.op_Implicit((Object)(object)((RaycastHit)(ref val2)).collider))
			{
				GameObject gameObject = ((Component)((RaycastHit)(ref val2)).transform).gameObject;
				if (((Object)gameObject).name.Contains("GamblingMachine"))
				{
					PlayerGamblingUIManager.ShowInteractionText();
					GrabbableObject val3 = PlayerControllerOriginal.ItemSlots[PlayerControllerOriginal.currentItemSlot];
					GamblingMachine component = gameObject.GetComponent<GamblingMachine>();
					if (component.isInCooldownPhase())
					{
						PlayerGamblingUIManager.SetInteractionText($"Cooling down... {component.gamblingMachineCurrentCooldown}");
					}
					else if (component.numberOfUses <= 0)
					{
						PlayerGamblingUIManager.SetInteractionText("This machine is all used up");
					}
					else
					{
						string bindingDisplayString = InputActionRebindingExtensions.GetBindingDisplayString(IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false), 0, (DisplayStringOptions)0);
						if (isUsingGamblingMachine)
						{
							PlayerGamblingUIManager.SetInteractionText("You're already using a machine");
						}
						else
						{
							PlayerGamblingUIManager.SetInteractionText("Gamble: [" + bindingDisplayString + "]");
						}
					}
					if (Object.op_Implicit((Object)(object)val3))
					{
						PlayerGamblingUIManager.SetInteractionSubText($"Scrap value on hand: ■{val3.scrapValue}");
					}
					else
					{
						PlayerGamblingUIManager.SetInteractionSubText("Please hold a scrap on your hand");
					}
				}
				if (((Object)gameObject).name.Contains("GamblingMachine") && IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false).triggered)
				{
					GamblingMachine component2 = gameObject.GetComponent<GamblingMachine>();
					handleGamblingMachineInput(component2);
				}
			}
			else
			{
				PlayerGamblingUIManager.HideInteractionText();
			}
		}

		public void ReleaseGamblingMachineLock()
		{
			Plugin.mls.LogInfo((object)$"Releasing gambling machine lock for: {((NetworkBehaviour)this).OwnerClientId}");
			isUsingGamblingMachine = false;
		}

		public void LockGamblingMachine()
		{
			Plugin.mls.LogInfo((object)$"Locking gambling machine for: {((NetworkBehaviour)this).OwnerClientId}");
			isUsingGamblingMachine = true;
		}

		private void handleGamblingMachineInput(GamblingMachine GamblingMachineHit)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//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)
			GrabbableObject val = PlayerControllerOriginal.ItemSlots[PlayerControllerOriginal.currentItemSlot];
			if (Object.op_Implicit((Object)(object)val) && !GamblingMachineHit.isInCooldownPhase() && GamblingMachineHit.numberOfUses > 0 && !isUsingGamblingMachine)
			{
				Plugin.mls.LogInfo((object)("Gambling machine was interacted with by: " + PlayerControllerOriginal.playerUsername));
				GamblingMachineHit.SetCurrentGamblingCooldownToMaxCooldown();
				Plugin.mls.LogMessage((object)$"Scrap value of {((Object)val).name} on hand: ▊{val.scrapValue}");
				GamblingMachineHit.ActivateGamblingMachineServerRPC(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)val), NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)this));
				PlayerGamblingUIManager.SetInteractionText($"Cooling down... {GamblingMachineHit.gamblingMachineCurrentCooldown}");
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "PlayerControllerCustom";
		}
	}
}
namespace GamblersMod.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPatch(GameNetworkManager __instance)
		{
			Plugin.mls.LogInfo((object)"Adding Gambling machine to network prefab");
			NetworkManager.Singleton.AddNetworkPrefab(Plugin.GamblingMachine);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void StartDisconnectPatch()
		{
			Plugin.mls.LogInfo((object)"Player disconnected. Resetting the user's configuration settings.");
			Plugin.CurrentUserConfig = Plugin.UserConfigSnapshot;
			GamblingMachineManager.Instance.Reset();
		}
	}
	[HarmonyPatch(typeof(GrabbableObject))]
	internal class GrabbableObjectPatch
	{
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePatch(StartOfRound __instance)
		{
			Plugin.mls.LogInfo((object)"StartOfRoundPatch has awoken");
		}
	}
	public class PlayerGamblingUIManager : NetworkBehaviour
	{
		private GameObject gamblingMachineInteractionTextCanvasObject;

		private Canvas gamblingMachineInteractionTextCanvas;

		private GameObject gamblingMachineInteractionTextObject;

		private GameObject gamblingMachineInteractionScrapInfoTextObject;

		private Text gamblingMachineInteractionScrapInfoText;

		private Text gamblingMachineInteractionText;

		private string interactionName;

		private string interactionText;

		private void Awake()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			gamblingMachineInteractionTextCanvasObject = new GameObject();
			gamblingMachineInteractionTextCanvasObject.transform.parent = ((Component)this).transform;
			interactionName = "gamblingMachine";
			((Object)gamblingMachineInteractionTextCanvasObject).name = interactionName + "InteractionTextCanvasObject";
			gamblingMachineInteractionTextCanvasObject.AddComponent<Canvas>();
			gamblingMachineInteractionTextCanvasObject.SetActive(false);
			gamblingMachineInteractionTextCanvas = gamblingMachineInteractionTextCanvasObject.GetComponent<Canvas>();
			gamblingMachineInteractionTextCanvas.renderMode = (RenderMode)0;
			gamblingMachineInteractionTextCanvasObject.AddComponent<CanvasScaler>();
			gamblingMachineInteractionTextCanvasObject.AddComponent<GraphicRaycaster>();
			gamblingMachineInteractionTextObject = new GameObject();
			((Object)gamblingMachineInteractionTextObject).name = interactionName + "InteractionTextObject";
			gamblingMachineInteractionTextObject.AddComponent<Text>();
			Transform transform = gamblingMachineInteractionTextObject.transform;
			Rect rect = ((Component)gamblingMachineInteractionTextCanvas).GetComponent<RectTransform>().rect;
			float num = ((Rect)(ref rect)).width / 2f - 20f;
			rect = ((Component)gamblingMachineInteractionTextCanvas).GetComponent<RectTransform>().rect;
			transform.localPosition = new Vector3(num, ((Rect)(ref rect)).height / 2f - 50f, 0f);
			gamblingMachineInteractionText = gamblingMachineInteractionTextObject.GetComponent<Text>();
			gamblingMachineInteractionText.text = interactionText;
			gamblingMachineInteractionText.alignment = (TextAnchor)4;
			gamblingMachineInteractionText.font = Plugin.GamblingFont;
			((Graphic)gamblingMachineInteractionText).rectTransform.sizeDelta = new Vector2(500f, 400f);
			gamblingMachineInteractionText.fontSize = 26;
			((Component)gamblingMachineInteractionText).transform.parent = gamblingMachineInteractionTextCanvasObject.transform;
			gamblingMachineInteractionScrapInfoTextObject = new GameObject();
			((Object)gamblingMachineInteractionScrapInfoTextObject).name = interactionName + "InteractionScrapInfoTextObject";
			gamblingMachineInteractionScrapInfoTextObject.AddComponent<Text>();
			Transform transform2 = gamblingMachineInteractionScrapInfoTextObject.transform;
			rect = ((Component)gamblingMachineInteractionTextCanvas).GetComponent<RectTransform>().rect;
			float num2 = ((Rect)(ref rect)).width / 2f - 20f;
			rect = ((Component)gamblingMachineInteractionTextCanvas).GetComponent<RectTransform>().rect;
			transform2.localPosition = new Vector3(num2, ((Rect)(ref rect)).height / 2f - 100f, 0f);
			gamblingMachineInteractionScrapInfoText = gamblingMachineInteractionScrapInfoTextObject.GetComponent<Text>();
			gamblingMachineInteractionScrapInfoText.text = interactionText;
			gamblingMachineInteractionScrapInfoText.alignment = (TextAnchor)4;
			gamblingMachineInteractionScrapInfoText.font = Plugin.GamblingFont;
			((Graphic)gamblingMachineInteractionScrapInfoText).rectTransform.sizeDelta = new Vector2(500f, 300f);
			gamblingMachineInteractionScrapInfoText.fontSize = 18;
			((Graphic)gamblingMachineInteractionScrapInfoText).color = Color.green;
			((Component)gamblingMachineInteractionScrapInfoText).transform.parent = gamblingMachineInteractionTextCanvasObject.transform;
		}

		public void SetInteractionText(string text)
		{
			gamblingMachineInteractionText.text = text;
		}

		public void SetInteractionSubText(string text)
		{
			gamblingMachineInteractionScrapInfoText.text = text;
		}

		public void ShowInteractionText()
		{
			gamblingMachineInteractionTextCanvasObject.SetActive(true);
		}

		public void HideInteractionText()
		{
			gamblingMachineInteractionTextCanvasObject.SetActive(false);
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "PlayerGamblingUIManager";
		}
	}
	internal class GamblingMachine : NetworkBehaviour
	{
		private int gamblingMachineMaxCooldown;

		public int gamblingMachineCurrentCooldown = 0;

		private float jackpotMultiplier;

		private float tripleMultiplier;

		private float doubleMultiplier;

		private float halvedMultiplier;

		private float zeroMultiplier;

		private int jackpotPercentage;

		private int triplePercentage;

		private int doublePercentage;

		private int halvedPercentage;

		private int removedPercentage;

		private bool isMusicEnabled = true;

		private float musicVolume = 0.35f;

		private int rollMinValue;

		private int rollMaxValue;

		private int currentRoll = 100;

		public float currentGamblingOutcomeMultiplier = 1f;

		public string currentGamblingOutcome = GambleConstants.GamblingOutcome.DEFAULT;

		private Coroutine CountdownCooldownCoroutineBeingRan;

		private bool lockGamblingMachineServer = false;

		public int numberOfUses;

		private void Awake()
		{
			Plugin.mls.LogInfo((object)"GamblingMachine has Awoken");
			gamblingMachineMaxCooldown = Plugin.CurrentUserConfig.configMaxCooldown;
			numberOfUses = Plugin.CurrentUserConfig.configNumberOfUses;
			jackpotMultiplier = Plugin.CurrentUserConfig.configJackpotMultiplier;
			tripleMultiplier = Plugin.CurrentUserConfig.configTripleMultiplier;
			doubleMultiplier = Plugin.CurrentUserConfig.configDoubleMultiplier;
			halvedMultiplier = Plugin.CurrentUserConfig.configHalveMultiplier;
			zeroMultiplier = Plugin.CurrentUserConfig.configZeroMultiplier;
			jackpotPercentage = Plugin.CurrentUserConfig.configJackpotChance;
			triplePercentage = Plugin.CurrentUserConfig.configTripleChance;
			doublePercentage = Plugin.CurrentUserConfig.configDoubleChance;
			halvedPercentage = Plugin.CurrentUserConfig.configHalveChance;
			removedPercentage = Plugin.CurrentUserConfig.configZeroChance;
			isMusicEnabled = Plugin.CurrentUserConfig.configGamblingMusicEnabled;
			musicVolume = Plugin.CurrentUserConfig.configGamblingMusicVolume;
			Plugin.mls.LogInfo((object)$"GamblingMachine: gamblingMachineMaxCooldown loaded from config: {gamblingMachineMaxCooldown}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: jackpotMultiplier loaded from config: {jackpotMultiplier}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: tripleMultiplier loaded from config: {tripleMultiplier}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: doubleMultiplier loaded from config: {doubleMultiplier}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: halvedMultiplier loaded from config: {halvedMultiplier}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: zeroMultiplier loaded from config: {zeroMultiplier}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: jackpotPercentage loaded from config: {jackpotPercentage}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: triplePercentage loaded from config: {triplePercentage}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: doublePercentage loaded from config: {doublePercentage}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: halvedPercentage loaded from config: {halvedPercentage}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: removedPercentage loaded from config: {removedPercentage}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: gamblingMusicEnabled loaded from config: {isMusicEnabled}");
			Plugin.mls.LogInfo((object)$"GamblingMachine: gamblingMusicVolume loaded from config: {musicVolume}");
			InitAudioSource();
			rollMinValue = 1;
			rollMaxValue = jackpotPercentage + triplePercentage + doublePercentage + halvedPercentage + removedPercentage;
		}

		private void Start()
		{
			Plugin.mls.LogInfo((object)"GamblingMachine has Started");
		}

		public void GenerateGamblingOutcomeFromCurrentRoll()
		{
			bool flag = currentRoll >= rollMinValue && currentRoll <= jackpotPercentage;
			int num = jackpotPercentage;
			int num2 = jackpotPercentage + triplePercentage;
			bool flag2 = currentRoll > num && currentRoll <= num2;
			int num3 = num2;
			int num4 = num2 + doublePercentage;
			bool flag3 = currentRoll > num3 && currentRoll <= num4;
			int num5 = num4;
			int num6 = num4 + halvedPercentage;
			bool flag4 = currentRoll > num5 && currentRoll <= num6;
			if (flag)
			{
				Plugin.mls.LogMessage((object)"Rolled Jackpot");
				currentGamblingOutcomeMultiplier = jackpotMultiplier;
				currentGamblingOutcome = GambleConstants.GamblingOutcome.JACKPOT;
			}
			else if (flag2)
			{
				Plugin.mls.LogMessage((object)"Rolled Triple");
				currentGamblingOutcomeMultiplier = tripleMultiplier;
				currentGamblingOutcome = GambleConstants.GamblingOutcome.TRIPLE;
			}
			else if (flag3)
			{
				Plugin.mls.LogMessage((object)"Rolled Double");
				currentGamblingOutcomeMultiplier = doubleMultiplier;
				currentGamblingOutcome = GambleConstants.GamblingOutcome.DOUBLE;
			}
			else if (flag4)
			{
				Plugin.mls.LogMessage((object)"Rolled Halved");
				currentGamblingOutcomeMultiplier = halvedMultiplier;
				currentGamblingOutcome = GambleConstants.GamblingOutcome.HALVE;
			}
			else
			{
				Plugin.mls.LogMessage((object)"Rolled Remove");
				currentGamblingOutcomeMultiplier = zeroMultiplier;
				currentGamblingOutcome = GambleConstants.GamblingOutcome.REMOVE;
			}
		}

		public void PlayGambleResultAudio(string outcome)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			if (outcome == GambleConstants.GamblingOutcome.JACKPOT)
			{
				AudioSource.PlayClipAtPoint(Plugin.GamblingJackpotScrapAudio, ((Component)this).transform.position, 0.6f);
			}
			else if (outcome == GambleConstants.GamblingOutcome.TRIPLE)
			{
				AudioSource.PlayClipAtPoint(Plugin.GamblingTripleScrapAudio, ((Component)this).transform.position, 0.6f);
			}
			else if (outcome == GambleConstants.GamblingOutcome.DOUBLE)
			{
				AudioSource.PlayClipAtPoint(Plugin.GamblingDoubleScrapAudio, ((Component)this).transform.position, 0.6f);
			}
			else if (outcome == GambleConstants.GamblingOutcome.HALVE)
			{
				AudioSource.PlayClipAtPoint(Plugin.GamblingHalveScrapAudio, ((Component)this).transform.position, 0.6f);
			}
			else if (outcome == GambleConstants.GamblingOutcome.REMOVE)
			{
				AudioSource.PlayClipAtPoint(Plugin.GamblingRemoveScrapAudio, ((Component)this).transform.position, 0.6f);
			}
		}

		public void PlayDrumRoll()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			AudioSource.PlayClipAtPoint(Plugin.GamblingDrumrollScrapAudio, ((Component)this).transform.position, 0.6f);
		}

		public void BeginGamblingMachineCooldown(Action onCountdownFinish)
		{
			SetCurrentGamblingCooldownToMaxCooldown();
			if (CountdownCooldownCoroutineBeingRan != null)
			{
				((MonoBehaviour)this).StopCoroutine(CountdownCooldownCoroutineBeingRan);
			}
			CountdownCooldownCoroutineBeingRan = ((MonoBehaviour)this).StartCoroutine(CountdownCooldownCoroutine(onCountdownFinish));
		}

		public bool isInCooldownPhase()
		{
			return gamblingMachineCurrentCooldown > 0;
		}

		private IEnumerator CountdownCooldownCoroutine(Action onCountdownFinish)
		{
			Plugin.mls.LogInfo((object)"Start gambling machine cooldown");
			while (gamblingMachineCurrentCooldown > 0)
			{
				yield return (object)new WaitForSeconds(1f);
				gamblingMachineCurrentCooldown--;
				Plugin.mls.LogMessage((object)$"Gambling machine cooldown: {gamblingMachineCurrentCooldown}");
			}
			onCountdownFinish();
			Plugin.mls.LogMessage((object)"End gambling machine cooldown");
		}

		public void SetCurrentGamblingCooldownToMaxCooldown()
		{
			gamblingMachineCurrentCooldown = gamblingMachineMaxCooldown;
		}

		public void SetRoll(int newRoll)
		{
			currentRoll = newRoll;
		}

		public int RollDice()
		{
			int result = Random.Range(rollMinValue, rollMaxValue);
			Plugin.mls.LogMessage((object)$"rollMinValue: {rollMinValue}");
			Plugin.mls.LogMessage((object)$"rollMaxValue: {rollMaxValue}");
			Plugin.mls.LogMessage((object)$"Roll value: {currentRoll}");
			return result;
		}

		public int GetScrapValueBasedOnGambledOutcome(GrabbableObject scrap)
		{
			return (int)Mathf.Floor((float)scrap.scrapValue * currentGamblingOutcomeMultiplier);
		}

		[ServerRpc(RequireOwnership = false)]
		public void ActivateGamblingMachineServerRPC(NetworkBehaviourReference scrapBeingGambledRef, NetworkBehaviourReference playerWhoGambledRef, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_0142: 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)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3977934568u, serverRpcParams, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkBehaviourReference>(ref scrapBeingGambledRef, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkBehaviourReference>(ref playerWhoGambledRef, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 3977934568u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost) || !((NetworkBehaviour)this).IsServer)
			{
				return;
			}
			if (numberOfUses <= 0)
			{
				Plugin.mls.LogWarning((object)"ActivateGamblingMachineServerRPC: Machine usage limit has been reached");
				return;
			}
			if (lockGamblingMachineServer)
			{
				Plugin.mls.LogWarning((object)$"Gambling machine is already processing one client's request. Throwing away a request for... {serverRpcParams.Receive.SenderClientId}");
				return;
			}
			lockGamblingMachineServer = true;
			numberOfUses--;
			Plugin.mls.LogInfo((object)$"ActivateGamblingMachineServerRPC: Number of uses left: {numberOfUses}");
			GrabbableObject scrap = default(GrabbableObject);
			if (!((NetworkBehaviourReference)(ref scrapBeingGambledRef)).TryGet<GrabbableObject>(ref scrap, (NetworkManager)null))
			{
				Plugin.mls.LogError((object)"ActivateGamblingMachineServerRPC: Failed to get scrap value on client side.");
				return;
			}
			BeginGamblingMachineCooldownClientRpc();
			Plugin.mls.LogMessage((object)("ActivateGamblingMachineServerRPC: Starting gambling machine cooldown phase in the server invoked by: " + serverRpcParams.Receive.SenderClientId));
			SetRoll(RollDice());
			GenerateGamblingOutcomeFromCurrentRoll();
			int scrapValueBasedOnGambledOutcome = GetScrapValueBasedOnGambledOutcome(scrap);
			ActivateGamblingMachineClientRPC(scrapBeingGambledRef, playerWhoGambledRef, serverRpcParams.Receive.SenderClientId, scrapValueBasedOnGambledOutcome, currentGamblingOutcome, numberOfUses);
		}

		[ClientRpc]
		private void ActivateGamblingMachineClientRPC(NetworkBehaviourReference scrapBeingGambledRef, NetworkBehaviourReference playerWhoGambledRef, ulong invokerId, int updatedScrapValue, string outcome, int numberOfUsesServer)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(875756295u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref scrapBeingGambledRef, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref playerWhoGambledRef, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val2, invokerId);
				BytePacker.WriteValueBitPacked(val2, updatedScrapValue);
				bool flag = outcome != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(outcome, false);
				}
				BytePacker.WriteValueBitPacked(val2, numberOfUsesServer);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 875756295u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			NetworkBehaviourReference scrapBeingGambledRef2 = scrapBeingGambledRef;
			int updatedScrapValue2 = updatedScrapValue;
			string outcome2 = outcome;
			Plugin.mls.LogInfo((object)"ActivateGamblingMachineClientRPC: Activiating gambling machines on client...");
			numberOfUses = numberOfUsesServer;
			Plugin.mls.LogInfo((object)$"ActivateGamblingMachineClientRPC: Number of uses left: {numberOfUses}");
			PlayerControllerCustom playerWhoGambled = default(PlayerControllerCustom);
			if (!((NetworkBehaviourReference)(ref playerWhoGambledRef)).TryGet<PlayerControllerCustom>(ref playerWhoGambled, (NetworkManager)null))
			{
				Plugin.mls.LogError((object)"ActivateGamblingMachineClientRPC: Failed to get player who gambled.");
				return;
			}
			playerWhoGambled.LockGamblingMachine();
			PlayDrumRoll();
			BeginGamblingMachineCooldown(delegate
			{
				GrabbableObject val3 = default(GrabbableObject);
				if (!((NetworkBehaviourReference)(ref scrapBeingGambledRef2)).TryGet<GrabbableObject>(ref val3, (NetworkManager)null))
				{
					Plugin.mls.LogError((object)"ActivateGamblingMachineClientRPC: Failed to get scrap value on client side.");
				}
				else
				{
					Plugin.mls.LogInfo((object)$"Setting scrap value to: {updatedScrapValue2}");
					val3.SetScrapValue(updatedScrapValue2);
					PlayGambleResultAudio(outcome2);
					playerWhoGambled.ReleaseGamblingMachineLock();
					if (((NetworkBehaviour)this).IsServer)
					{
						Plugin.mls.LogMessage((object)"Unlocking gambling machine");
						lockGamblingMachineServer = false;
					}
				}
			});
		}

		[ClientRpc]
		private void BeginGamblingMachineCooldownClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1546410253u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1546410253u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Plugin.mls.LogInfo((object)"Setting machine cooldown to max");
					SetCurrentGamblingCooldownToMaxCooldown();
				}
			}
		}

		private void InitAudioSource()
		{
			if (!isMusicEnabled)
			{
				((Component)this).GetComponent<AudioSource>().Pause();
			}
			((Component)this).GetComponent<AudioSource>().volume = musicVolume;
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_GamblingMachine()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(3977934568u, new RpcReceiveHandler(__rpc_handler_3977934568));
			NetworkManager.__rpc_func_table.Add(875756295u, new RpcReceiveHandler(__rpc_handler_875756295));
			NetworkManager.__rpc_func_table.Add(1546410253u, new RpcReceiveHandler(__rpc_handler_1546410253));
		}

		private static void __rpc_handler_3977934568(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0069: 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_0078: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference scrapBeingGambledRef = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref scrapBeingGambledRef, default(ForNetworkSerializable));
				NetworkBehaviourReference playerWhoGambledRef = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref playerWhoGambledRef, default(ForNetworkSerializable));
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((GamblingMachine)(object)target).ActivateGamblingMachineServerRPC(scrapBeingGambledRef, playerWhoGambledRef, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_875756295(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference scrapBeingGambledRef = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref scrapBeingGambledRef, default(ForNetworkSerializable));
				NetworkBehaviourReference playerWhoGambledRef = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref playerWhoGambledRef, default(ForNetworkSerializable));
				ulong invokerId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref invokerId);
				int updatedScrapValue = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref updatedScrapValue);
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string outcome = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref outcome, false);
				}
				int numberOfUsesServer = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref numberOfUsesServer);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((GamblingMachine)(object)target).ActivateGamblingMachineClientRPC(scrapBeingGambledRef, playerWhoGambledRef, invokerId, updatedScrapValue, outcome, numberOfUsesServer);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1546410253(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((GamblingMachine)(object)target).BeginGamblingMachineCooldownClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "GamblingMachine";
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPrefix]
		public static void Awake(PlayerControllerB __instance)
		{
			((Component)__instance).gameObject.AddComponent<PlayerControllerCustom>();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void ConnectClientToPlayerObjectPatch()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Plugin.mls.LogInfo((object)"ConnectClientToPlayerObjectPatch");
			if (NetworkManager.Singleton.IsHost)
			{
				Plugin.mls.LogInfo((object)("Registering host config message handler: Junypai.GamblersMod_" + GambleConstants.ON_HOST_RECIEVES_CLIENT_CONFIG_REQUEST));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("Junypai.GamblersMod_" + GambleConstants.ON_HOST_RECIEVES_CLIENT_CONFIG_REQUEST, new HandleNamedMessageDelegate(GambleConfigNetworkHelper.OnHostRecievesClientConfigRequest));
			}
			else
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("Junypai.GamblersMod_" + GambleConstants.ON_CLIENT_RECIEVES_HOST_CONFIG_REQUEST, new HandleNamedMessageDelegate(GambleConfigNetworkHelper.OnClientRecievesHostConfigRequest));
				GambleConfigNetworkHelper.StartClientRequestConfigFromHost();
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		public static RoundManagerCustom RoundManagerCustom;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		public static void AwakePatch(RoundManager __instance)
		{
			Plugin.mls.LogInfo((object)"RoundManagerPatch has awoken");
			RoundManagerCustom = ((Component)__instance).gameObject.AddComponent<RoundManagerCustom>();
		}

		[HarmonyPatch("LoadNewLevelWait")]
		[HarmonyPrefix]
		public static void LoadNewLevelWaitPatch(RoundManager __instance)
		{
			Plugin.mls.LogInfo((object)"FinishGeneratingNewLevelServerRpcPatch was called");
			if (__instance.currentLevel.levelID != 3)
			{
				Plugin.mls.LogInfo((object)"Despawning gambling machine...");
				RoundManagerCustom.DespawnGamblingMachineServerRpc();
			}
			if (__instance.currentLevel.levelID == 3)
			{
				Plugin.mls.LogInfo((object)"Spawning gambling machine...");
				RoundManagerCustom.SpawnGamblingMachineServerRpc();
			}
		}

		[HarmonyPatch("DespawnPropsAtEndOfRound")]
		[HarmonyPostfix]
		public static void DespawnPropsAtEndOfRoundPatch()
		{
			Plugin.mls.LogInfo((object)"End of round: despawning gambling machines");
			RoundManagerCustom.DespawnGamblingMachineServerRpc();
		}
	}
}
namespace GamblersMod.GrabbableObjectCustom
{
	internal class GrabbableObjectCustom
	{
	}
}
namespace GamblersMod.config
{
	public class GambleConfigNetworkHelper
	{
		public static void OnHostRecievesClientConfigRequest(ulong clientId, FastBufferReader _)
		{
			//IL_0061: 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_007f: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsHost)
			{
				return;
			}
			Plugin.mls.LogInfo((object)"Host recieved client config request.");
			Plugin.mls.LogInfo((object)"Serializing host config data...");
			byte[] serializedSettings = SerializerHelper.GetSerializedSettings(Plugin.CurrentUserConfig);
			Plugin.mls.LogInfo((object)"Start writing host config data...");
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(serializedSettings.Length + 4, (Allocator)2, -1);
			FastBufferWriter val2 = val;
			try
			{
				Plugin.mls.LogInfo((object)"Writing host config data");
				int num = serializedSettings.Length;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(serializedSettings, -1, 0);
				Plugin.mls.LogInfo((object)$"Sending host config data to client with id of {clientId}...");
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Junypai.GamblersMod_" + GambleConstants.ON_CLIENT_RECIEVES_HOST_CONFIG_REQUEST, clientId, val, (NetworkDelivery)4);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
			}
		}

		public static void StartClientRequestConfigFromHost()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				Plugin.mls.LogInfo((object)"Client is requesting configuration from host");
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Junypai.GamblersMod_" + GambleConstants.ON_HOST_RECIEVES_CLIENT_CONFIG_REQUEST, 0uL, val, (NetworkDelivery)3);
			}
		}

		public static void OnClientRecievesHostConfigRequest(ulong _, FastBufferReader reader)
		{
			//IL_003c: 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)
			Plugin.mls.LogInfo((object)"Client recieved configuration message from host");
			if (!((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				Plugin.mls.LogError((object)"Could not sync client configuration with host. The stream sent by StartClientRequestConfigFromHost was invalid.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				Plugin.mls.LogError((object)"Could not sync client configuration with host. Host could not serialize the data.");
			}
			byte[] settingsAsBytes = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref settingsAsBytes, num, 0);
			Plugin.RecentHostConfig = SerializerHelper.GetDeserializedSettings<GambleConfigSettingsSerializable>(settingsAsBytes);
			Plugin.CurrentUserConfig = Plugin.RecentHostConfig;
			Plugin.CurrentUserConfig.configGamblingMusicEnabled = Plugin.UserConfigSnapshot.configGamblingMusicEnabled;
			Plugin.CurrentUserConfig.configGamblingMusicVolume = Plugin.UserConfigSnapshot.configGamblingMusicVolume;
			ManualLogSource mls = Plugin.mls;
			mls.LogInfo((object)$"Cooldown value from config: {Plugin.CurrentUserConfig.configMaxCooldown}");
			mls.LogInfo((object)$"Jackpot chance value from config: {Plugin.CurrentUserConfig.configJackpotChance}");
			mls.LogInfo((object)$"Triple chance value from config: {Plugin.CurrentUserConfig.configTripleChance}");
			mls.LogInfo((object)$"Double chance value from config: {Plugin.CurrentUserConfig.configDoubleChance}");
			mls.LogInfo((object)$"Halve chance value from config: {Plugin.CurrentUserConfig.configHalveChance}");
			mls.LogInfo((object)$"Zero chance value from config: {Plugin.CurrentUserConfig.configZeroChance}");
			mls.LogInfo((object)$"Jackpot multiplier value from config: {Plugin.CurrentUserConfig.configJackpotMultiplier}");
			mls.LogInfo((object)$"Triple multiplier value from config: {Plugin.CurrentUserConfig.configTripleMultiplier}");
			mls.LogInfo((object)$"Double multiplier value from config: {Plugin.CurrentUserConfig.configDoubleMultiplier}");
			mls.LogInfo((object)$"Halve multiplier value from config: {Plugin.CurrentUserConfig.configHalveMultiplier}");
			mls.LogInfo((object)$"Zero multiplier value from config: {Plugin.CurrentUserConfig.configZeroMultiplier}");
			mls.LogInfo((object)$"Audio enabled from config: {Plugin.CurrentUserConfig.configGamblingMusicEnabled}");
			mls.LogInfo((object)$"Audio volume from config: {Plugin.CurrentUserConfig.configGamblingMusicVolume}");
			mls.LogInfo((object)$"Number of uses from config: {Plugin.CurrentUserConfig.configNumberOfUses}");
			mls.LogInfo((object)$"Number of machines from config: {Plugin.CurrentUserConfig.configNumberOfMachines}");
			Plugin.mls.LogInfo((object)"Successfully synced a client with host configuration");
		}
	}
	public class GambleConstants
	{
		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct GamblingOutcome
		{
			public static string JACKPOT = "JACKPOT";

			public static string TRIPLE = "TRIPLE";

			public static string DOUBLE = "DOUBLE";

			public static string HALVE = "HALVE";

			public static string REMOVE = "REMOVE";

			public static string DEFAULT = "DEFAULT";
		}

		public static readonly string GAMBLING_GENERAL_SECTION_KEY = "General Machine Settings";

		public static readonly string GAMBLING_CHANCE_SECTION_KEY = "Gambling Chances";

		public static readonly string GAMBLING_MULTIPLIERS_SECTION_KEY = "Gambling Multipliers";

		public static readonly string GAMBLING_AUDIO_SECTION_KEY = "Audio";

		public static readonly string CONFIG_MAXCOOLDOWN = "gamblingMachineMaxCooldown";

		public static readonly string CONFIG_NUMBER_OF_USES = "Number Of Uses";

		public static readonly string CONFIG_NUMBER_OF_MACHINES = "Number Of Machines";

		public static readonly string CONFIG_JACKPOT_CHANCE_KEY = "JackpotChance";

		public static readonly string CONFIG_TRIPLE_CHANCE_KEY = "TripleChance";

		public static readonly string CONFIG_DOUBLE_CHANCE_KEY = "DoubleChance";

		public static readonly string CONFIG_HALVE_CHANCE_KEY = "HalveChance";

		public static readonly string CONFIG_ZERO_CHANCE_KEY = "ZeroChance";

		public static readonly string CONFIG_JACKPOT_MULTIPLIER = "JackpotMultiplier";

		public static readonly string CONFIG_TRIPLE_MULTIPLIER = "TripleMultiplier";

		public static readonly string CONFIG_DOUBLE_MULTIPLIER = "DoubleMultiplier";

		public static readonly string CONFIG_HALVE_MULTIPLIER = "HalveMultiplier";

		public static readonly string CONFIG_ZERO_MULTIPLIER = "ZeroMultiplier";

		public static readonly string CONFIG_GAMBLING_MUSIC_ENABLED = "GambleMachineMusicEnabled";

		public static readonly string CONFIG_GAMBLING_MUSIC_VOLUME = "GambleMachineMusicVolume";

		public static readonly string ON_HOST_RECIEVES_CLIENT_CONFIG_REQUEST = "OnHostRecievesClientConfigRequest";

		public static readonly string ON_CLIENT_RECIEVES_HOST_CONFIG_REQUEST = "OnClientRecievesHostConfigRequest";
	}
	[Serializable]
	public class GambleConfigSettingsSerializable
	{
		public int configMaxCooldown;

		public int configNumberOfUses;

		public int configNumberOfMachines;

		public int configJackpotChance;

		public int configTripleChance;

		public int configDoubleChance;

		public int configHalveChance;

		public int configZeroChance;

		public float configJackpotMultiplier;

		public float configTripleMultiplier;

		public float configDoubleMultiplier;

		public float configHalveMultiplier;

		public float configZeroMultiplier;

		public bool configGamblingMusicEnabled;

		public float configGamblingMusicVolume;

		public GambleConfigSettingsSerializable(ConfigFile configFile)
		{
			configFile.Bind<int>(GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_MAXCOOLDOWN, 4, "Cooldown of the machine. Reducing this will cause the drumroll sound to not sync & may also cause latency issues");
			configFile.Bind<int>(GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_NUMBER_OF_USES, 9999, "Number of times a gambling machine can be used");
			configFile.Bind<int>(GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_NUMBER_OF_MACHINES, 3, "How many gambling machines will be spawned (max 4)");
			configFile.Bind<int>(GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_JACKPOT_CHANCE_KEY, 3, "Chance to roll a jackpot. Ex. If set to 3, you have a 3% chance to get a jackpot. Make sure ALL your chance values add up to 100 or else the math won't make sense!");
			configFile.Bind<int>(GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_TRIPLE_CHANCE_KEY, 11, "Chance to roll a triple. Ex. If set to 11, you have a 11% chance to get a triple. Make sure ALL your chance values add up to 100 or else the math won't make sense!");
			configFile.Bind<int>(GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_DOUBLE_CHANCE_KEY, 27, "Chance to roll a double. Ex. If set to 27, you have a 27% chance to get a double. Make sure ALL your chance values add up to 100 or else the math won't make sense!");
			configFile.Bind<int>(GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_HALVE_CHANCE_KEY, 50, "Chance to roll a halve. Ex. If set to 47, you have a 47% chance to get a halve. Make sure ALL your chance values add up to 100 or else the math won't make sense!");
			configFile.Bind<int>(GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_ZERO_CHANCE_KEY, 9, "Chance to roll a zero. Ex. If set to 12, you have a 12% chance to get a zero. Make sure ALL your chance values add up to 100 or else the math won't make sense!");
			configFile.Bind<float>(GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_JACKPOT_MULTIPLIER, 10f, "Jackpot multiplier");
			configFile.Bind<float>(GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_TRIPLE_MULTIPLIER, 3f, "Triple multiplier");
			configFile.Bind<float>(GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_DOUBLE_MULTIPLIER, 2f, "Double multiplier");
			configFile.Bind<float>(GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_HALVE_MULTIPLIER, 0.5f, "Halve multiplier");
			configFile.Bind<float>(GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_ZERO_MULTIPLIER, 0f, "Zero multiplier");
			configFile.Bind<bool>(GambleConstants.GAMBLING_AUDIO_SECTION_KEY, GambleConstants.CONFIG_GAMBLING_MUSIC_ENABLED, true, "Enable gambling machine music (CLIENT SIDE)");
			configFile.Bind<float>(GambleConstants.GAMBLING_AUDIO_SECTION_KEY, GambleConstants.CONFIG_GAMBLING_MUSIC_VOLUME, 0.35f, "Gambling machine music volume (CLIENT SIDE)");
			configMaxCooldown = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_MAXCOOLDOWN);
			configJackpotChance = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_JACKPOT_CHANCE_KEY);
			configTripleChance = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_TRIPLE_CHANCE_KEY);
			configDoubleChance = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_DOUBLE_CHANCE_KEY);
			configHalveChance = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_HALVE_CHANCE_KEY);
			configZeroChance = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_CHANCE_SECTION_KEY, GambleConstants.CONFIG_ZERO_CHANCE_KEY);
			configJackpotMultiplier = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_JACKPOT_MULTIPLIER);
			configTripleMultiplier = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_TRIPLE_MULTIPLIER);
			configDoubleMultiplier = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_DOUBLE_MULTIPLIER);
			configHalveMultiplier = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_HALVE_MULTIPLIER);
			configZeroMultiplier = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_MULTIPLIERS_SECTION_KEY, GambleConstants.CONFIG_ZERO_MULTIPLIER);
			configGamblingMusicEnabled = GetConfigFileKeyValue<bool>(configFile, GambleConstants.GAMBLING_AUDIO_SECTION_KEY, GambleConstants.CONFIG_GAMBLING_MUSIC_ENABLED);
			configGamblingMusicVolume = GetConfigFileKeyValue<float>(configFile, GambleConstants.GAMBLING_AUDIO_SECTION_KEY, GambleConstants.CONFIG_GAMBLING_MUSIC_VOLUME);
			configNumberOfUses = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_NUMBER_OF_USES);
			configNumberOfMachines = GetConfigFileKeyValue<int>(configFile, GambleConstants.GAMBLING_GENERAL_SECTION_KEY, GambleConstants.CONFIG_NUMBER_OF_MACHINES);
			LogInitializedConfigsValues();
		}

		private void LogInitializedConfigsValues()
		{
			ManualLogSource mls = Plugin.mls;
			mls.LogInfo((object)$"Cooldown value from config: {configMaxCooldown}");
			mls.LogInfo((object)$"Jackpot chance value from config: {configJackpotChance}");
			mls.LogInfo((object)$"Triple chance value from config: {configTripleChance}");
			mls.LogInfo((object)$"Double chance value from config: {configDoubleChance}");
			mls.LogInfo((object)$"Halve chance value from config: {configHalveChance}");
			mls.LogInfo((object)$"Zero chance value from config: {configZeroChance}");
			mls.LogInfo((object)$"Jackpot multiplier value from config: {configJackpotMultiplier}");
			mls.LogInfo((object)$"Triple multiplier value from config: {configTripleMultiplier}");
			mls.LogInfo((object)$"Double multiplier value from config: {configDoubleMultiplier}");
			mls.LogInfo((object)$"Halve multiplier value from config: {configHalveMultiplier}");
			mls.LogInfo((object)$"Zero multiplier value from config: {configZeroMultiplier}");
			mls.LogInfo((object)$"Music enabled from config: {configGamblingMusicEnabled}");
			mls.LogInfo((object)$"Music volume from config: {configGamblingMusicVolume}");
			mls.LogInfo((object)$"Number of uses from config: {configNumberOfUses}");
			mls.LogInfo((object)$"Number of machines from config: {configNumberOfMachines}");
		}

		private T GetConfigFileKeyValue<T>(ConfigFile configFile, string section, string key)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			ConfigDefinition val = new ConfigDefinition(section, key);
			Plugin.mls.LogInfo((object)("Getting configuration entry: Section: " + section + " Key: " + key));
			ConfigEntry<T> val2 = default(ConfigEntry<T>);
			if (!configFile.TryGetEntry<T>(val, ref val2))
			{
				Plugin.mls.LogError((object)("Failed to get configuration value. Section: " + section + " Key: " + key));
			}
			return val2.Value;
		}
	}
	internal class SerializerHelper
	{
		public static byte[] GetSerializedSettings<T>(T valToSerialize)
		{
			MemoryStream memoryStream = new MemoryStream();
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			try
			{
				binaryFormatter.Serialize(memoryStream, valToSerialize);
			}
			catch (SerializationException ex)
			{
				Plugin.mls.LogError((object)("Config serialization failed: " + ex.Message));
			}
			byte[] result = memoryStream.ToArray();
			memoryStream.Close();
			return result;
		}

		public static T GetDeserializedSettings<T>(byte[] settingsAsBytes)
		{
			MemoryStream memoryStream = new MemoryStream();
			memoryStream.Write(settingsAsBytes, 0, settingsAsBytes.Length);
			memoryStream.Seek(0L, SeekOrigin.Begin);
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			try
			{
				object obj = binaryFormatter.Deserialize(memoryStream);
				memoryStream.Close();
				return (T)obj;
			}
			catch (SerializationException ex)
			{
				Plugin.mls.LogError((object)("Config deserialization failed: " + ex.Message));
			}
			memoryStream.Close();
			return default(T);
		}
	}
}

BepInEx/plugins/MegaPiggy-BuyableShotgun/BuyableShotgun.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("BuyableShotgun")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+f4271793e57a966e00668122ac278845cc79146b")]
[assembly: AssemblyProduct("BuyableShotgun")]
[assembly: AssemblyTitle("BuyableShotgun")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 BuyableShotgun
{
	[BepInDependency("evaisa.lethallib", "0.13.2")]
	[BepInPlugin("MegaPiggy.BuyableShotgun", "Buyable Shotgun", "1.0.4")]
	public class BuyableShotgun : BaseUnityPlugin
	{
		private const string modGUID = "MegaPiggy.BuyableShotgun";

		private const string modName = "Buyable Shotgun";

		private const string modVersion = "1.0.4";

		private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgun");

		private static BuyableShotgun Instance;

		private ConfigEntry<int> ShotgunPriceConfig;

		private static Dictionary<string, TerminalNode> infoNodes = new Dictionary<string, TerminalNode>();

		private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger;

		public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList();

		public Item Shotgun => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name.Equals("Shotgun")));

		public Item ShotgunClone { get; private set; }

		public int ShotgunPrice => ShotgunPriceConfig.Value;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			ShotgunPriceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunPrice", 700, "Credits needed to buy shotgun");
			SceneManager.sceneLoaded += OnSceneLoaded;
			ShotgunClone = MakeNonScrap(ShotgunPrice);
			AddToShop();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Buyable Shotgun is loaded with version 1.0.4!");
		}

		private Item MakeNonScrap(int price)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			Item val = ScriptableObject.CreateInstance<Item>();
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).name = "Error";
			val.itemName = "Error";
			val.itemId = 6624;
			val.isScrap = false;
			val.creditsWorth = price;
			val.canBeGrabbedBeforeGameStart = true;
			val.automaticallySetUsingPower = false;
			val.batteryUsage = 300f;
			val.canBeInspected = false;
			val.isDefensiveWeapon = true;
			val.saveItemVariable = true;
			val.syncGrabFunction = false;
			val.twoHandedAnimation = true;
			val.verticalOffset = 0.25f;
			GameObject val2 = NetworkPrefabs.CreateNetworkPrefab("Cube");
			GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)3);
			val3.transform.SetParent(val2.transform, false);
			((Renderer)val3.GetComponent<MeshRenderer>()).sharedMaterial.shader = Shader.Find("HDRP/Lit");
			val2.AddComponent<BoxCollider>().size = Vector3.one * 2f;
			val2.AddComponent<AudioSource>();
			PhysicsProp val4 = val2.AddComponent<PhysicsProp>();
			((GrabbableObject)val4).itemProperties = val;
			((GrabbableObject)val4).grabbable = true;
			val.spawnPrefab = val2;
			val2.tag = "PhysicsProp";
			val2.layer = LayerMask.NameToLayer("Props");
			val3.layer = LayerMask.NameToLayer("Props");
			try
			{
				GameObject val5 = Object.Instantiate<GameObject>(Items.scanNodePrefab, val2.transform);
				((Object)val5).name = "ScanNode";
				val5.transform.localPosition = new Vector3(0f, 0f, 0f);
				Transform transform = val5.transform;
				transform.localScale *= 2f;
				ScanNodeProperties component = val5.GetComponent<ScanNodeProperties>();
				component.nodeType = 1;
				component.headerText = "Error";
				component.subText = "A mod is incompatible with Buyable Shotgun";
			}
			catch (Exception ex)
			{
				LoggerInstance.LogError((object)ex.ToString());
			}
			val2.transform.localScale = Vector3.one / 2f;
			return val;
		}

		private void CloneNonScrap(Item original, Item clone, int price)
		{
			Object.DontDestroyOnLoad((Object)(object)original.spawnPrefab);
			CopyFields(original, clone);
			((Object)clone).name = "Buyable" + ((Object)original).name;
			clone.creditsWorth = price;
		}

		public static void CopyFields(Item source, Item destination)
		{
			FieldInfo[] fields = typeof(Item).GetFields();
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				fieldInfo.SetValue(destination, fieldInfo.GetValue(source));
			}
		}

		private TerminalNode CreateInfoNode(string name, string description)
		{
			if (infoNodes.ContainsKey(name))
			{
				return infoNodes[name];
			}
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			Object.DontDestroyOnLoad((Object)(object)val);
			val.clearPreviousText = true;
			((Object)val).name = name + "InfoNode";
			val.displayText = description + "\n\n";
			infoNodes.Add(name, val);
			return val;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			LoggerInstance.LogInfo((object)("Scene \"" + ((Scene)(ref scene)).name + "\" loaded with " + ((object)(LoadSceneMode)(ref mode)).ToString() + " mode."));
			if (!((Object)(object)Shotgun == (Object)null))
			{
				CloneNonScrap(Shotgun, ShotgunClone, ShotgunPrice);
			}
		}

		private void AddToShop()
		{
			Item shotgunClone = ShotgunClone;
			int shotgunPrice = ShotgunPrice;
			Items.RegisterShopItem(shotgunClone, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("Shotgun", "Nutcracker's shotgun. Can hold 2 shells. Recommended to keep safety on while not using or it might shoot randomly."), shotgunPrice);
			LoggerInstance.LogInfo((object)$"Shotgun added to Shop for {ShotgunPrice} credits");
		}
	}
}

BepInEx/plugins/MegaPiggy-BuyableShotgunShells/BuyableShotgunShells.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("BuyableShotgunShells")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d3b9a4b110f11cec26aacb9899b73d38055d7e40")]
[assembly: AssemblyProduct("BuyableShotgunShells")]
[assembly: AssemblyTitle("BuyableShotgunShells")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 BuyableShotgunShells
{
	[BepInDependency("evaisa.lethallib", "0.13.2")]
	[BepInPlugin("MegaPiggy.BuyableShotgunShells", "Buyable Shotgun Shells", "1.0.5")]
	public class BuyableShotgunShells : BaseUnityPlugin
	{
		private const string modGUID = "MegaPiggy.BuyableShotgunShells";

		private const string modName = "Buyable Shotgun Shells";

		private const string modVersion = "1.0.5";

		private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgunShells");

		private static BuyableShotgunShells Instance;

		private ConfigEntry<int> ShellPriceConfig;

		private static Dictionary<string, TerminalNode> infoNodes = new Dictionary<string, TerminalNode>();

		private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger;

		public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList();

		public Item ShotgunShell => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name.Equals("GunAmmo")));

		public Item ShotgunShellClone { get; private set; }

		public int ShellPrice => ShellPriceConfig.Value;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			ShellPriceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunShellPrice", 20, "Credits needed to buy shotgun shells");
			SceneManager.sceneLoaded += OnSceneLoaded;
			ShotgunShellClone = MakeNonScrap(ShellPrice);
			AddToShop();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Buyable Shotgun Shells is loaded with version 1.0.5!");
		}

		private Item MakeNonScrap(int price)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			Item val = ScriptableObject.CreateInstance<Item>();
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).name = "Error";
			val.itemName = "Error";
			val.itemId = 6624;
			val.isScrap = false;
			val.creditsWorth = price;
			val.canBeGrabbedBeforeGameStart = true;
			val.automaticallySetUsingPower = false;
			val.batteryUsage = 300f;
			val.canBeInspected = false;
			val.isDefensiveWeapon = true;
			val.saveItemVariable = true;
			val.syncGrabFunction = false;
			val.twoHandedAnimation = true;
			val.verticalOffset = 0.25f;
			GameObject val2 = NetworkPrefabs.CreateNetworkPrefab("Cube");
			GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)3);
			val3.transform.SetParent(val2.transform, false);
			((Renderer)val3.GetComponent<MeshRenderer>()).sharedMaterial.shader = Shader.Find("HDRP/Lit");
			val2.AddComponent<BoxCollider>().size = Vector3.one * 2f;
			val2.AddComponent<AudioSource>();
			PhysicsProp val4 = val2.AddComponent<PhysicsProp>();
			((GrabbableObject)val4).itemProperties = val;
			((GrabbableObject)val4).grabbable = true;
			val.spawnPrefab = val2;
			val2.tag = "PhysicsProp";
			val2.layer = LayerMask.NameToLayer("Props");
			val3.layer = LayerMask.NameToLayer("Props");
			try
			{
				GameObject val5 = Object.Instantiate<GameObject>(Items.scanNodePrefab, val2.transform);
				((Object)val5).name = "ScanNode";
				val5.transform.localPosition = new Vector3(0f, 0f, 0f);
				Transform transform = val5.transform;
				transform.localScale *= 2f;
				ScanNodeProperties component = val5.GetComponent<ScanNodeProperties>();
				component.nodeType = 1;
				component.headerText = "Error";
				component.subText = "A mod is incompatible with Buyable Shotgun Shells";
			}
			catch (Exception ex)
			{
				LoggerInstance.LogError((object)ex.ToString());
			}
			val2.transform.localScale = Vector3.one / 2f;
			return val;
		}

		private void CloneNonScrap(Item original, Item clone, int price)
		{
			Object.DontDestroyOnLoad((Object)(object)original.spawnPrefab);
			CopyFields(original, clone);
			((Object)clone).name = "Buyable" + ((Object)original).name;
			clone.creditsWorth = price;
		}

		public static void CopyFields(Item source, Item destination)
		{
			FieldInfo[] fields = typeof(Item).GetFields();
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				fieldInfo.SetValue(destination, fieldInfo.GetValue(source));
			}
		}

		private TerminalNode CreateInfoNode(string name, string description)
		{
			if (infoNodes.ContainsKey(name))
			{
				return infoNodes[name];
			}
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.clearPreviousText = true;
			((Object)val).name = name + "InfoNode";
			val.displayText = description + "\n\n";
			infoNodes.Add(name, val);
			return val;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (!((Object)(object)ShotgunShell == (Object)null))
			{
				CloneNonScrap(ShotgunShell, ShotgunShellClone, ShellPrice);
				ShotgunShellClone.itemName = "Shells";
			}
		}

		private void AddToShop()
		{
			Item shotgunShellClone = ShotgunShellClone;
			int shellPrice = ShellPrice;
			Items.RegisterShopItem(shotgunShellClone, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("ShotgunShell", "Ammo for the Nutcracker's Shotgun."), shellPrice);
			LoggerInstance.LogInfo((object)$"Shotgun Shell added to Shop for {ShellPrice} credits");
		}
	}
}

BepInEx/plugins/Midge-PushCompany/PushCompany/PushCompany.dll

Decompiled 9 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using PushCompany.Assets.Scripts;
using PushCompany.Properties;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PushCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Push your fellow crewmates with the interaction key! (E by default)")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
[assembly: AssemblyProduct("PushCompany")]
[assembly: AssemblyTitle("PushCompany")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 PushCompany
{
	[BepInPlugin("PushCompany", "PushCompany", "1.2.0")]
	public class PushCompanyBase : BaseUnityPlugin
	{
		public static readonly Lazy<PushCompanyBase> Instance = new Lazy<PushCompanyBase>(() => new PushCompanyBase());

		public static GameObject pushPrefab;

		public ManualLogSource mls;

		private readonly Harmony harmony = new Harmony("PushCompany");

		public static ConfigEntry<float> config_PushCooldown;

		public static ConfigEntry<float> config_PushForce;

		public static ConfigEntry<float> config_PushRange;

		public static ConfigEntry<float> config_PushCost;

		private void Awake()
		{
			mls = Logger.CreateLogSource("PushCompany");
			ConfigSetup();
			LoadBundle();
			harmony.PatchAll(typeof(PushCompanyBase));
			harmony.PatchAll(typeof(PlayerControllerB_Patches));
			harmony.PatchAll(typeof(NetworkHandler));
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			mls.LogInfo((object)"PushCompany has initialized!");
		}

		private void ConfigSetup()
		{
			config_PushCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cooldown", "Value", 0.025f, "How long until the player can push again");
			config_PushForce = ((BaseUnityPlugin)this).Config.Bind<float>("Push Force", "Value", 12.5f, "How strong the player pushes.");
			config_PushRange = ((BaseUnityPlugin)this).Config.Bind<float>("Push Range", "Value", 3f, "The distance the player is able to push.");
			config_PushCost = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cost", "Value", 0.08f, "The energy cost of each push.");
		}

		private void LoadBundle()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.pushcompany);
			if ((Object)(object)val == (Object)null)
			{
				throw new Exception("Failed to load Push Bundle!");
			}
			pushPrefab = val.LoadAsset<GameObject>("Assets/Push.prefab");
			if ((Object)(object)pushPrefab == (Object)null)
			{
				throw new Exception("Failed to load Push Prefab!");
			}
			pushPrefab.AddComponent<PushComponent>();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "PushCompany";

		public const string PLUGIN_NAME = "PushCompany";

		public const string PLUGIN_VERSION = "1.2.0";
	}
}
namespace PushCompany.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("PushCompany.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] AssetBundles
		{
			get
			{
				object @object = ResourceManager.GetObject("AssetBundles", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] AssetBundles_manifest
		{
			get
			{
				object @object = ResourceManager.GetObject("AssetBundles.manifest", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] AssetBundles1
		{
			get
			{
				object @object = ResourceManager.GetObject("AssetBundles1", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] AssetBundles2
		{
			get
			{
				object @object = ResourceManager.GetObject("AssetBundles2", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] pushcompany
		{
			get
			{
				object @object = ResourceManager.GetObject("pushcompany", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] pushcompany_push
		{
			get
			{
				object @object = ResourceManager.GetObject("pushcompany.push", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] pushcompany_push_manifest
		{
			get
			{
				object @object = ResourceManager.GetObject("pushcompany.push.manifest", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] pushcompany_push1
		{
			get
			{
				object @object = ResourceManager.GetObject("pushcompany.push1", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace PushCompany.Assets.Scripts
{
	[HarmonyPatch]
	public class NetworkHandler
	{
		private static GameObject pushObject;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		private static void Init()
		{
			NetworkManager.Singleton.AddNetworkPrefab(PushCompanyBase.pushPrefab);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		private static void SpawnNetworkPrefab()
		{
			try
			{
				if (NetworkManager.Singleton.IsServer)
				{
					pushObject = Object.Instantiate<GameObject>(PushCompanyBase.pushPrefab);
					pushObject.GetComponent<NetworkObject>().Spawn(true);
				}
			}
			catch
			{
				PushCompanyBase.Instance.Value.mls.LogError((object)"Failed to instantiate network prefab!");
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	public static class PlayerControllerB_Patches
	{
		private static PushComponent pushComponent;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		private static void Update(PlayerControllerB __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)__instance).IsOwner)
			{
				return;
			}
			MovementActions movement = __instance.playerActions.Movement;
			if (((MovementActions)(ref movement)).Interact.WasPressedThisFrame())
			{
				if ((Object)(object)pushComponent == (Object)null)
				{
					pushComponent = Object.FindObjectOfType<PushComponent>();
				}
				if ((Object)(object)pushComponent != (Object)null)
				{
					pushComponent.PushServerRpc(((NetworkBehaviour)__instance).NetworkObjectId);
				}
			}
		}
	}
	public class PushComponent : NetworkBehaviour
	{
		private Dictionary<ulong, float> lastPushTimes = new Dictionary<ulong, float>();

		private NetworkVariable<float> PushCooldown = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		private NetworkVariable<float> PushRange = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		private NetworkVariable<float> PushForce = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		private NetworkVariable<float> PushCost = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public override void OnNetworkSpawn()
		{
			if (((NetworkBehaviour)this).IsServer)
			{
				PushCooldown.Value = PushCompanyBase.config_PushCooldown.Value;
				PushRange.Value = PushCompanyBase.config_PushRange.Value;
				PushForce.Value = PushCompanyBase.config_PushForce.Value;
				PushCost.Value = PushCompanyBase.config_PushCost.Value;
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void PushServerRpc(ulong playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0151: 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_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2433198804u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2433198804u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			if (lastPushTimes.TryGetValue(playerId, out var value))
			{
				if (Time.time - value < PushCooldown.Value)
				{
					return;
				}
			}
			else
			{
				lastPushTimes.Add(playerId, 0f);
			}
			GameObject playerById = GetPlayerById(playerId);
			PlayerControllerB component = playerById.GetComponent<PlayerControllerB>();
			Camera gameplayCamera = component.gameplayCamera;
			if (!CanPushPlayer(component))
			{
				return;
			}
			int num = 1 << playerById.layer;
			Vector3 forward = ((Component)gameplayCamera).transform.forward;
			Vector3 normalized = ((Vector3)(ref forward)).normalized;
			RaycastHit[] array = Physics.RaycastAll(((Component)gameplayCamera).transform.position, normalized, PushRange.Value, num);
			RaycastHit[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				RaycastHit val3 = array2[i];
				if ((Object)(object)((Component)((RaycastHit)(ref val3)).transform).gameObject != (Object)(object)playerById)
				{
					PlayerControllerB component2 = ((Component)((RaycastHit)(ref val3)).transform).GetComponent<PlayerControllerB>();
					if (!component2.inSpecialInteractAnimation)
					{
						PushClientRpc(((NetworkBehaviour)component).NetworkObjectId, ((NetworkBehaviour)component2).NetworkObjectId, normalized * PushForce.Value * Time.fixedDeltaTime);
						lastPushTimes[playerId] = Time.time;
					}
					break;
				}
			}
		}

		[ClientRpc]
		private void PushClientRpc(ulong pusherId, ulong playerId, Vector3 push)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3498116674u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, pusherId);
					BytePacker.WriteValueBitPacked(val2, playerId);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref push);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3498116674u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GameObject playerById = GetPlayerById(playerId);
					PlayerControllerB component = playerById.GetComponent<PlayerControllerB>();
					((MonoBehaviour)this).StartCoroutine(SmoothMove(component.thisController, push));
					component.movementAudio.PlayOneShot(StartOfRound.Instance.playerJumpSFX);
					GameObject playerById2 = GetPlayerById(pusherId);
					PlayerControllerB component2 = playerById2.GetComponent<PlayerControllerB>();
					component2.sprintMeter = Mathf.Clamp(component2.sprintMeter - PushCost.Value, 0f, 1f);
				}
			}
		}

		public IEnumerator SmoothMove(CharacterController controller, Vector3 push)
		{
			//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)
			float force = PushForce.Value / 12.5f;
			float smoothTime = ((Vector3)(ref push)).magnitude / force;
			Vector3 targetPosition = ((Component)controller).transform.position + push;
			Vector3 val = targetPosition - ((Component)controller).transform.position;
			Vector3 direction = ((Vector3)(ref val)).normalized;
			float distance = Vector3.Distance(((Component)controller).transform.position, targetPosition);
			for (float currentTime = 0f; currentTime < smoothTime; currentTime += Time.fixedDeltaTime)
			{
				float currentDistance = distance * Mathf.Min(currentTime, smoothTime) / smoothTime;
				controller.Move(direction * currentDistance);
				yield return null;
			}
		}

		private bool CanPushPlayer(PlayerControllerB player)
		{
			return !player.quickMenuManager.isMenuOpen && !player.inSpecialInteractAnimation && !player.isTypingChat && !player.isExhausted;
		}

		private static GameObject GetPlayerById(ulong playerId)
		{
			if (NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(playerId, out var value))
			{
				return ((Component)value).gameObject;
			}
			return null;
		}

		protected override void __initializeVariables()
		{
			if (PushCooldown == null)
			{
				throw new Exception("PushComponent.PushCooldown cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PushCooldown).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCooldown, "PushCooldown");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCooldown);
			if (PushRange == null)
			{
				throw new Exception("PushComponent.PushRange cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PushRange).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushRange, "PushRange");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushRange);
			if (PushForce == null)
			{
				throw new Exception("PushComponent.PushForce cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PushForce).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushForce, "PushForce");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushForce);
			if (PushCost == null)
			{
				throw new Exception("PushComponent.PushCost cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PushCost).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCost, "PushCost");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCost);
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_PushComponent()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2433198804u, new RpcReceiveHandler(__rpc_handler_2433198804));
			NetworkManager.__rpc_func_table.Add(3498116674u, new RpcReceiveHandler(__rpc_handler_3498116674));
		}

		private static void __rpc_handler_2433198804(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong playerId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((PushComponent)(object)target).PushServerRpc(playerId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3498116674(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong pusherId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref pusherId);
				ulong playerId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				Vector3 push = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref push);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((PushComponent)(object)target).PushClientRpc(pusherId, playerId, push);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "PushComponent";
		}
	}
}

BepInEx/plugins/notnotnotswipez-MoreCompany/MoreCompany.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreCompany.Cosmetics;
using MoreCompany.Utils;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MoreCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © NotNotSwipez 2023")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyTitle("MoreCompany")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 MoreCompany
{
	[HarmonyPatch(typeof(AudioMixer), "SetFloat")]
	public static class AudioMixerSetFloatPatch
	{
		public static bool Prefix(string name, float value)
		{
			if (name.StartsWith("PlayerVolume") || name.StartsWith("PlayerPitch"))
			{
				string s = name.Replace("PlayerVolume", "").Replace("PlayerPitch", "");
				int num = int.Parse(s);
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num];
				if ((Object)(object)val != (Object)null)
				{
					AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
					if (Object.op_Implicit((Object)(object)currentVoiceChatAudioSource))
					{
						if (name.StartsWith("PlayerVolume"))
						{
							currentVoiceChatAudioSource.volume = value / 16f;
						}
						else if (name.StartsWith("PlayerPitch"))
						{
							currentVoiceChatAudioSource.pitch = value;
						}
					}
					return false;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	public static class SendChatToServerPatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, int playerId = -1)
		{
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc") && DebugCommandRegistry.commandEnabled)
			{
				string text = chatMessage.Replace("/mc ", "");
				DebugCommandRegistry.HandleCommand(text.Split(' '));
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				ReflectionUtils.InvokeMethod(__instance, "AddPlayerChatMessageServerRpc", new object[2] { chatMessage, 99 });
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	public static class ServerReceiveMessagePatch
	{
		public static string previousDataMessage = "";

		public static bool Prefix(HUDManager __instance, ref string chatMessage, int playerId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]") && networkManager.IsServer)
			{
				previousDataMessage = chatMessage;
				chatMessage = "[replacewithdata]";
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
	public static class ConnectClientToPlayerObjectPatch
	{
		public static void Postfix(PlayerControllerB __instance)
		{
			string text = "[morecompanycosmetics]";
			text = text + ";" + __instance.playerClientId;
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				text = text + ";" + locallySelectedCosmetic;
			}
			HUDManager.Instance.AddTextToChatOnServer(text, -1);
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	public static class AddChatMessagePatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")]
	public static class ClientReceiveMessagePatch
	{
		public static bool ignoreSample;

		public static bool Prefix(ref HUDManager __instance, ref string chatMessage, int playerId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return false;
			}
			if (networkManager.IsServer)
			{
				if (chatMessage.StartsWith("[replacewithdata]"))
				{
					chatMessage = ServerReceiveMessagePatch.previousDataMessage;
					HandleDataMessage(ref chatMessage);
				}
				else if (chatMessage.StartsWith("[morecompanycosmetics]"))
				{
					return false;
				}
			}
			else if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				HandleDataMessage(ref chatMessage);
			}
			return true;
		}

		private static void HandleDataMessage(ref string chatMessage)
		{
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			if (ignoreSample)
			{
				return;
			}
			chatMessage = chatMessage.Replace("[morecompanycosmetics]", "");
			string[] array = chatMessage.Split(';');
			string text = array[1];
			int num = int.Parse(text);
			CosmeticApplication component = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.GetComponent<CosmeticApplication>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.ClearCosmetics();
				Object.Destroy((Object)(object)component);
			}
			CosmeticApplication cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.AddComponent<CosmeticApplication>();
			cosmeticApplication.ClearCosmetics();
			List<string> list = new List<string>();
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (!(text2 == text))
				{
					list.Add(text2);
					if (MainClass.showCosmetics)
					{
						cosmeticApplication.ApplyCosmetic(text2, startEnabled: true);
					}
				}
			}
			if (num == StartOfRound.Instance.thisClientPlayerId)
			{
				cosmeticApplication.ClearCosmetics();
			}
			foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
			}
			MainClass.playerIdsAndCosmetics.Remove(num);
			MainClass.playerIdsAndCosmetics.Add(num, list);
			if (!GameNetworkManager.Instance.isHostingGame || num == 0)
			{
				return;
			}
			ignoreSample = true;
			foreach (KeyValuePair<int, List<string>> playerIdsAndCosmetic in MainClass.playerIdsAndCosmetics)
			{
				string text3 = "[morecompanycosmetics]";
				text3 = text3 + ";" + playerIdsAndCosmetic.Key;
				foreach (string item in playerIdsAndCosmetic.Value)
				{
					text3 = text3 + ";" + item;
				}
				HUDManager.Instance.AddTextToChatOnServer(text3, -1);
			}
			ignoreSample = false;
		}
	}
	public class DebugCommandRegistry
	{
		public static bool commandEnabled;

		public static void HandleCommand(string[] args)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: 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_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			if (!commandEnabled)
			{
				return;
			}
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			switch (args[0])
			{
			case "money":
			{
				int groupCredits = int.Parse(args[1]);
				Terminal val5 = Resources.FindObjectsOfTypeAll<Terminal>().First();
				val5.groupCredits = groupCredits;
				break;
			}
			case "spawnscrap":
			{
				string text = "";
				for (int i = 1; i < args.Length; i++)
				{
					text = text + args[i] + " ";
				}
				text = text.Trim();
				Vector3 val = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f;
				SpawnableItemWithRarity val2 = null;
				foreach (SpawnableItemWithRarity item in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					if (item.spawnableItem.itemName.ToLower() == text.ToLower())
					{
						val2 = item;
						break;
					}
				}
				GameObject val3 = Object.Instantiate<GameObject>(val2.spawnableItem.spawnPrefab, val, Quaternion.identity, (Transform)null);
				GrabbableObject component = val3.GetComponent<GrabbableObject>();
				((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
				component.fallTime = 0f;
				NetworkObject component2 = val3.GetComponent<NetworkObject>();
				component2.Spawn(false);
				break;
			}
			case "spawnenemy":
			{
				string text2 = "";
				for (int j = 1; j < args.Length; j++)
				{
					text2 = text2 + args[j] + " ";
				}
				text2 = text2.Trim();
				SpawnableEnemyWithRarity val4 = null;
				foreach (SpawnableEnemyWithRarity enemy in StartOfRound.Instance.currentLevel.Enemies)
				{
					if (enemy.enemyType.enemyName.ToLower() == text2.ToLower())
					{
						val4 = enemy;
						break;
					}
				}
				RoundManager.Instance.SpawnEnemyGameObject(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f, 0f, -1, val4.enemyType);
				break;
			}
			case "listall":
				MainClass.StaticLogger.LogInfo((object)"Spawnable scrap:");
				foreach (SpawnableItemWithRarity item2 in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					MainClass.StaticLogger.LogInfo((object)item2.spawnableItem.itemName);
				}
				MainClass.StaticLogger.LogInfo((object)"Spawnable enemies:");
				{
					foreach (SpawnableEnemyWithRarity enemy2 in StartOfRound.Instance.currentLevel.Enemies)
					{
						MainClass.StaticLogger.LogInfo((object)enemy2.enemyType.enemyName);
					}
					break;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ForestGiantAI), "LookForPlayers")]
	public static class LookForPlayersForestGiantPatch
	{
		public static void Prefix(ref ForestGiantAI __instance)
		{
			if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount)
			{
				Array.Resize(ref __instance.playerStealthMeters, MainClass.newPlayerCount);
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					__instance.playerStealthMeters[i] = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(BlobAI), "Start")]
	public static class BlobAIStartPatch
	{
		public static void Postfix(ref BlobAI __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "ragdollColliders", value);
		}
	}
	[HarmonyPatch(typeof(CrawlerAI), "Start")]
	public static class CrawlerAIStartPatch
	{
		public static void Postfix(ref CrawlerAI __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "nearPlayerColliders", value);
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "Update")]
	public static class SpringManAIUpdatePatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call static float UnityEngine.Vector3::Distance(UnityEngine.Vector3 a, UnityEngine.Vector3 b)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
	public static class SpringManAIIntervalPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call void EnemyAI::SwitchToBehaviourState(int stateIndex)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
	public static class GetClosestPlayerPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					flag = true;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")]
	public static class GetAllPlayersInLineOfSightPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					flag = true;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	public static class HudChatPatch
	{
		public static void Prefix(HUDManager __instance, ref string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (!(__instance.lastChatMessage == chatMessage))
			{
				StringBuilder stringBuilder = new StringBuilder(chatMessage);
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					string oldValue = $"[playerNum{i}]";
					string playerUsername = StartOfRound.Instance.allPlayerScripts[i].playerUsername;
					stringBuilder.Replace(oldValue, playerUsername);
				}
				chatMessage = stringBuilder.ToString();
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager), "Awake")]
	public static class MenuManagerLogoOverridePatch
	{
		public static List<TMP_InputField> inputFields = new List<TMP_InputField>();

		public static void Postfix(MenuManager __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MainClass.ReadSettingsFromFile();
				GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
				Sprite sprite = Sprite.Create(MainClass.mainLogo, new Rect(0f, 0f, (float)((Texture)MainClass.mainLogo).width, (float)((Texture)MainClass.mainLogo).height), new Vector2(0.5f, 0.5f));
				Transform val = gameObject.transform.Find("MenuContainer/MainButtons/HeaderImage");
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.GetComponent<Image>().sprite = sprite;
				}
				Transform val2 = gameObject.transform.Find("MenuContainer/LoadingScreen");
				if ((Object)(object)val2 != (Object)null)
				{
					val2.localScale = new Vector3(1.02f, 1.06f, 1.02f);
					Transform val3 = val2.Find("Image");
					if ((Object)(object)val3 != (Object)null)
					{
						((Component)val3).GetComponent<Image>().sprite = sprite;
					}
				}
				CosmeticRegistry.SpawnCosmeticGUI();
				LANMenu.InitializeMenu();
				inputFields.Clear();
				Transform val4 = gameObject.transform.Find("MenuContainer/LobbyHostSettings/HostSettingsContainer/LobbyHostOptions");
				if ((Object)(object)val4 != (Object)null)
				{
					CreateCrewCountInput(val4.Find(GameNetworkManager.Instance.disableSteam ? "LANOptions" : "OptionsNormal"));
				}
				Transform val5 = gameObject.transform.Find("MenuContainer/LobbyJoinSettings/JoinSettingsContainer/LobbyJoinOptions");
				if ((Object)(object)val5 != (Object)null)
				{
					CreateCrewCountInput(val5.Find("LANOptions"));
				}
			}
			catch (Exception ex)
			{
				MainClass.StaticLogger.LogError((object)ex);
			}
		}

		private static void CreateCrewCountInput(Transform parent)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(MainClass.crewCountUI, parent);
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).localPosition = new Vector3(96.9f, -70f, -6.7f);
			TMP_InputField inputField = ((Component)val.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>();
			inputField.characterLimit = 3;
			inputField.text = MainClass.newPlayerCount.ToString();
			inputFields.Add(inputField);
			((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s)
			{
				if (!(inputField.text == MainClass.newPlayerCount.ToString()))
				{
					if (int.TryParse(s, out var result))
					{
						MainClass.newPlayerCount = Mathf.Clamp(result, MainClass.minPlayerCount, MainClass.maxPlayerCount);
						foreach (TMP_InputField inputField2 in inputFields)
						{
							inputField2.text = MainClass.newPlayerCount.ToString();
						}
						MainClass.SaveSettingsToFile();
						MainClass.StaticLogger.LogInfo((object)$"Changed Crew Count: {MainClass.newPlayerCount}");
					}
					else if (s.Length != 0)
					{
						foreach (TMP_InputField inputField3 in inputFields)
						{
							inputField3.text = MainClass.newPlayerCount.ToString();
							inputField3.caretPosition = 1;
						}
					}
				}
			});
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
	public static class AddUserPlayerListPatch
	{
		private static bool Prefix(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			MainClass.EnablePlayerObjectsBasedOnConnected();
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "RemoveUserFromPlayerList")]
	public static class RemoveUserPlayerListPatch
	{
		public static bool Prefix(QuickMenuManager __instance)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Update")]
	public static class QuickMenuUpdatePatch
	{
		public static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")]
	public static class QuickMenuDisplayPatch
	{
		public static bool Prefix(ref bool __result)
		{
			__result = false;
			for (int i = 1; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i];
				if (val.isPlayerControlled || val.isPlayerDead)
				{
					__result = true;
					break;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Start")]
	public static class QuickmenuVisualInjectPatch
	{
		public static GameObject quickMenuScrollInstance;

		public static void Postfix(QuickMenuManager __instance)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject;
			GameObject val = Object.Instantiate<GameObject>(MainClass.quickMenuScrollParent);
			val.transform.SetParent(gameObject.transform);
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).localPosition = new Vector3(0f, -31.2f, 0f);
			((Transform)component).localScale = Vector3.one;
			quickMenuScrollInstance = val;
		}

		public static void PopulateQuickMenu(QuickMenuManager __instance)
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Expected O, but got Unknown
			int childCount = quickMenuScrollInstance.transform.Find("Holder").childCount;
			List<GameObject> list = new List<GameObject>();
			for (int i = 0; i < childCount; i++)
			{
				list.Add(((Component)quickMenuScrollInstance.transform.Find("Holder").GetChild(i)).gameObject);
			}
			foreach (GameObject item in list)
			{
				Object.Destroy((Object)(object)item);
			}
			if (!Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				return;
			}
			for (int j = 0; j < StartOfRound.Instance.allPlayerScripts.Length; j++)
			{
				PlayerControllerB playerScript = StartOfRound.Instance.allPlayerScripts[j];
				if (!playerScript.isPlayerControlled && !playerScript.isPlayerDead)
				{
					continue;
				}
				GameObject val = Object.Instantiate<GameObject>(MainClass.playerEntry, quickMenuScrollInstance.transform.Find("Holder"));
				RectTransform component = val.GetComponent<RectTransform>();
				((Transform)component).localScale = Vector3.one;
				((Transform)component).localPosition = new Vector3(0f, 0f - ((Transform)component).localPosition.y, 0f);
				TextMeshProUGUI component2 = ((Component)val.transform.Find("PlayerNameButton").Find("PName")).GetComponent<TextMeshProUGUI>();
				((TMP_Text)component2).text = playerScript.playerUsername;
				Slider playerVolume = ((Component)val.transform.Find("PlayerVolumeSlider")).GetComponent<Slider>();
				int finalIndex = j;
				((UnityEvent<float>)(object)playerVolume.onValueChanged).AddListener((UnityAction<float>)delegate(float f)
				{
					if (playerScript.isPlayerControlled || playerScript.isPlayerDead)
					{
						float num = f / playerVolume.maxValue + 1f;
						if (num <= -1f)
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = -70f;
						}
						else
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = num;
						}
					}
				});
				if ((Object)(object)StartOfRound.Instance.localPlayerController != (Object)null && StartOfRound.Instance.localPlayerController.playerClientId == playerScript.playerClientId)
				{
					((Component)playerVolume).gameObject.SetActive(false);
					((Component)val.transform.Find("Text (1)")).gameObject.SetActive(false);
				}
				Button component3 = ((Component)val.transform.Find("KickButton")).GetComponent<Button>();
				((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
				{
					__instance.KickUserFromServer(finalIndex);
				});
				if (!GameNetworkManager.Instance.isHostingGame)
				{
					((Component)component3).gameObject.SetActive(false);
				}
				Button component4 = ((Component)val.transform.Find("ProfileIcon")).GetComponent<Button>();
				((UnityEvent)component4.onClick).AddListener((UnityAction)delegate
				{
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					if (!GameNetworkManager.Instance.disableSteam)
					{
						SteamFriends.OpenUserOverlay(SteamId.op_Implicit(playerScript.playerSteamId), "steamid");
					}
				});
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "ConfirmKickUserFromServer")]
	public static class KickPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "ldfld int QuickMenuManager::playerObjToKick")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.3 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(HUDManager), "UpdateBoxesSpectateUI")]
	public static class SpectatorBoxUpdatePatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Animator, PlayerControllerB> fieldValue = ReflectionUtils.GetFieldValue<Dictionary<Animator, PlayerControllerB>>(__instance, "spectatingPlayerBoxes");
			int num = -64;
			int num2 = 0;
			int num3 = 0;
			int num4 = -70;
			int num5 = 230;
			int num6 = 4;
			foreach (KeyValuePair<Animator, PlayerControllerB> item in fieldValue)
			{
				if (((Component)item.Key).gameObject.activeInHierarchy)
				{
					GameObject gameObject = ((Component)item.Key).gameObject;
					RectTransform component = gameObject.GetComponent<RectTransform>();
					int num7 = (int)Math.Floor((double)num3 / (double)num6);
					int num8 = num3 % num6;
					int num9 = num8 * num4;
					int num10 = num7 * num5;
					component.anchoredPosition = Vector2.op_Implicit(new Vector3((float)(num + num10), (float)(num2 + num9), 0f));
					num3++;
				}
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Start")]
	public static class HudStartPatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_011a: Unknown result type (might be due to invalid IL or missing references)
			EndOfGameStatUIElements statsUIElements = __instance.statsUIElements;
			GameObject gameObject = ((Component)((Component)statsUIElements.playerNamesText[0]).gameObject.transform.parent).gameObject;
			GameObject gameObject2 = ((Component)gameObject.transform.parent.parent).gameObject;
			GameObject gameObject3 = ((Component)gameObject2.transform.Find("BGBoxes")).gameObject;
			gameObject2.transform.parent.Find("DeathScreen").SetSiblingIndex(3);
			gameObject3.transform.localScale = new Vector3(2.5f, 1f, 1f);
			MakePlayerHolder(4, gameObject, statsUIElements, new Vector3(426.9556f, -0.7932f, 0f));
			MakePlayerHolder(5, gameObject, statsUIElements, new Vector3(426.9556f, -115.4483f, 0f));
			MakePlayerHolder(6, gameObject, statsUIElements, new Vector3(-253.6783f, -115.4483f, 0f));
			MakePlayerHolder(7, gameObject, statsUIElements, new Vector3(-253.6783f, -0.7932f, 0f));
			for (int i = 8; i < MainClass.newPlayerCount; i++)
			{
				MakePlayerHolder(i, gameObject, statsUIElements, new Vector3(10000f, 10000f, 0f));
			}
		}

		public static void MakePlayerHolder(int index, GameObject original, EndOfGameStatUIElements uiElements, Vector3 localPosition)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (index + 1 <= MainClass.newPlayerCount)
			{
				GameObject val = Object.Instantiate<GameObject>(original);
				RectTransform component = val.GetComponent<RectTransform>();
				RectTransform component2 = original.GetComponent<RectTransform>();
				((Transform)component).SetParent(((Transform)component2).parent);
				((Transform)component).localScale = new Vector3(1f, 1f, 1f);
				((Transform)component).localPosition = localPosition;
				GameObject gameObject = ((Component)val.transform.Find("PlayerName1")).gameObject;
				GameObject gameObject2 = ((Component)val.transform.Find("Notes")).gameObject;
				((Transform)gameObject2.GetComponent<RectTransform>()).localPosition = new Vector3(-95.7222f, 43.3303f, 0f);
				GameObject gameObject3 = ((Component)val.transform.Find("Symbol")).gameObject;
				if (index >= uiElements.playerNamesText.Length)
				{
					Array.Resize(ref uiElements.playerNamesText, index + 1);
					Array.Resize(ref uiElements.playerStates, index + 1);
					Array.Resize(ref uiElements.playerNotesText, index + 1);
				}
				uiElements.playerNamesText[index] = gameObject.GetComponent<TextMeshProUGUI>();
				uiElements.playerNotesText[index] = gameObject2.GetComponent<TextMeshProUGUI>();
				uiElements.playerStates[index] = gameObject3.GetComponent<Image>();
			}
		}
	}
	public class LANMenu : MonoBehaviour
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__0_0;

			internal void <InitializeMenu>b__0_0()
			{
				TextMeshProUGUI component = GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings/JoinSettingsContainer/PrivatePublicDescription").GetComponent<TextMeshProUGUI>();
				if ((Object)(object)component != (Object)null)
				{
					((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
				}
				GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true);
			}
		}

		public static void InitializeMenu()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005e: 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: Expected O, but got Unknown
			CreateUI();
			GameObject val = GameObject.Find("Canvas/MenuContainer/MainButtons/StartLAN");
			if (!((Object)(object)val != (Object)null))
			{
				return;
			}
			MainClass.StaticLogger.LogInfo((object)"LANMenu startLAN Patched");
			val.GetComponent<Button>().onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = val.GetComponent<Button>().onClick;
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				UnityAction val2 = delegate
				{
					TextMeshProUGUI component = GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings/JoinSettingsContainer/PrivatePublicDescription").GetComponent<TextMeshProUGUI>();
					if ((Object)(object)component != (Object)null)
					{
						((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
					}
					GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true);
				};
				<>c.<>9__0_0 = val2;
				obj = (object)val2;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
		}

		private static GameObject CreateUI()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Expected O, but got Unknown
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			if ((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings") != (Object)null)
			{
				return null;
			}
			GameObject val = GameObject.Find("Canvas/MenuContainer");
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject val2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings");
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			GameObject val3 = Object.Instantiate<GameObject>(val2, val2.transform.position, val2.transform.rotation, val.transform);
			((Object)val3).name = "LobbyJoinSettings";
			Transform val4 = val3.transform.Find("HostSettingsContainer");
			if ((Object)(object)val4 != (Object)null)
			{
				((Object)val4).name = "JoinSettingsContainer";
				((Object)((Component)val4).transform.Find("LobbyHostOptions")).name = "LobbyJoinOptions";
				Object.Destroy((Object)(object)((Component)val3.transform.Find("ChallengeLeaderboard")).gameObject);
				Object.Destroy((Object)(object)((Component)val3.transform.Find("FilesPanel")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/OptionsNormal")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/AllowRemote")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Local")).gameObject);
				Transform val5 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Header");
				if ((Object)(object)val5 != (Object)null)
				{
					((TMP_Text)((Component)val5).GetComponent<TextMeshProUGUI>()).text = "Join LAN Server:";
				}
				Transform val6 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/ServerNameField");
				if ((Object)(object)val6 != (Object)null)
				{
					((Component)val6).transform.localPosition = new Vector3(0f, 15f, -6.5f);
					((Component)val6).gameObject.SetActive(true);
				}
				TMP_InputField ip_field = ((Component)val6).GetComponent<TMP_InputField>();
				if ((Object)(object)ip_field != (Object)null)
				{
					TextMeshProUGUI ip_placeholder = ((Component)ip_field.placeholder).GetComponent<TextMeshProUGUI>();
					((TMP_Text)ip_placeholder).text = ES3.Load<string>("LANIPAddress", "LCGeneralSaveData", "127.0.0.1");
					Transform obj = ((Component)val4).transform.Find("Confirm");
					Button val7 = ((obj != null) ? ((Component)obj).GetComponent<Button>() : null);
					if ((Object)(object)val7 != (Object)null)
					{
						val7.onClick = new ButtonClickedEvent();
						((UnityEvent)val7.onClick).AddListener((UnityAction)delegate
						{
							string text = "127.0.0.1";
							text = ((!(ip_field.text != "")) ? ((TMP_Text)ip_placeholder).text : ip_field.text);
							ES3.Save<string>("LANIPAddress", text, "LCGeneralSaveData");
							GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(false);
							((Component)NetworkManager.Singleton).GetComponent<UnityTransport>().ConnectionData.Address = text;
							MainClass.StaticLogger.LogInfo((object)("Listening to LAN server: " + text));
							GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient();
						});
					}
				}
				TextMeshProUGUI component = ((Component)((Component)val4).transform.Find("PrivatePublicDescription")).GetComponent<TextMeshProUGUI>();
				if ((Object)(object)component != (Object)null)
				{
					((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
				}
				((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions")).gameObject.SetActive(true);
			}
			return val3;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SetConnectionDataBeforeConnecting")]
	public static class ConnectionDataPatch
	{
		public static void Postfix(ref GameNetworkManager __instance)
		{
			if (__instance.disableSteam)
			{
				NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + "," + MainClass.newPlayerCount);
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "OnLocalClientConnectionDisapproved")]
	public static class ConnectionDisapprovedPatch
	{
		private static int crewSizeMismatch;

		private static IEnumerator delayedReconnect()
		{
			yield return (object)new WaitForSeconds(0.5f);
			GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient();
		}

		private static void Prefix(ref GameNetworkManager __instance, ulong clientId)
		{
			crewSizeMismatch = 0;
			if (!__instance.disableSteam)
			{
				return;
			}
			try
			{
				if (!string.IsNullOrEmpty(NetworkManager.Singleton.DisconnectReason) && NetworkManager.Singleton.DisconnectReason.StartsWith("Crew size mismatch!"))
				{
					crewSizeMismatch = int.Parse(NetworkManager.Singleton.DisconnectReason.Split("Their size: ")[1].Split(". ")[0]);
				}
			}
			catch
			{
			}
		}

		private static void Postfix(ref GameNetworkManager __instance, ulong clientId)
		{
			if (__instance.disableSteam && crewSizeMismatch != 0)
			{
				MainClass.newPlayerCount = Mathf.Clamp(crewSizeMismatch, MainClass.minPlayerCount, MainClass.maxPlayerCount);
				GameObject.Find("MenuManager").GetComponent<MenuManager>().menuNotification.SetActive(false);
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(true, (RoomEnter)5, "");
				((MonoBehaviour)__instance).StartCoroutine(delayedReconnect());
				crewSizeMismatch = 0;
			}
		}
	}
	public static class PluginInformation
	{
		public const string PLUGIN_NAME = "MoreCompany";

		public const string PLUGIN_VERSION = "1.8.1";

		public const string PLUGIN_GUID = "me.swipez.melonloader.morecompany";
	}
	[BepInPlugin("me.swipez.melonloader.morecompany", "MoreCompany", "1.8.1")]
	public class MainClass : BaseUnityPlugin
	{
		public static int newPlayerCount = 32;

		public static int minPlayerCount = 4;

		public static int maxPlayerCount = 50;

		public static bool showCosmetics = true;

		public static List<PlayerControllerB> notSupposedToExistPlayers = new List<PlayerControllerB>();

		public static Texture2D mainLogo;

		public static GameObject quickMenuScrollParent;

		public static GameObject playerEntry;

		public static GameObject crewCountUI;

		public static GameObject cosmeticGUIInstance;

		public static GameObject cosmeticButton;

		public static ManualLogSource StaticLogger;

		public static Dictionary<int, List<string>> playerIdsAndCosmetics = new Dictionary<int, List<string>>();

		public static string cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics.txt";

		public static string moreCompanySave = Application.persistentDataPath + "/morecompanysave.txt";

		public static string dynamicCosmeticsPath = Paths.PluginPath + "/MoreCompanyCosmetics";

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			StaticLogger = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("me.swipez.melonloader.morecompany");
			try
			{
				val.PatchAll();
			}
			catch (Exception ex)
			{
				StaticLogger.LogError((object)("Failed to patch: " + ex));
			}
			StaticLogger.LogInfo((object)"Loading MoreCompany...");
			SteamFriends.OnGameLobbyJoinRequested += delegate(Lobby lobby, SteamId steamId)
			{
				newPlayerCount = ((Lobby)(ref lobby)).MaxMembers;
			};
			SteamMatchmaking.OnLobbyEntered += delegate(Lobby lobby)
			{
				newPlayerCount = ((Lobby)(ref lobby)).MaxMembers;
			};
			StaticLogger.LogInfo((object)("Checking: " + dynamicCosmeticsPath));
			if (!Directory.Exists(dynamicCosmeticsPath))
			{
				StaticLogger.LogInfo((object)"Creating cosmetics directory");
				Directory.CreateDirectory(dynamicCosmeticsPath);
			}
			ReadSettingsFromFile();
			ReadCosmeticsFromFile();
			StaticLogger.LogInfo((object)"Read settings and cosmetics");
			AssetBundle bundle = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.assets", Assembly.GetExecutingAssembly());
			AssetBundle val2 = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.cosmetics", Assembly.GetExecutingAssembly());
			CosmeticRegistry.LoadCosmeticsFromBundle(val2);
			val2.Unload(false);
			StaticLogger.LogInfo((object)"Loading USER COSMETICS...");
			RecursiveCosmeticLoad(Paths.PluginPath);
			LoadAssets(bundle);
			StaticLogger.LogInfo((object)"Loaded MoreCompany FULLY");
		}

		private void RecursiveCosmeticLoad(string directory)
		{
			string[] directories = Directory.GetDirectories(directory);
			foreach (string directory2 in directories)
			{
				RecursiveCosmeticLoad(directory2);
			}
			string[] files = Directory.GetFiles(directory);
			foreach (string text in files)
			{
				if (text.EndsWith(".cosmetics"))
				{
					AssetBundle val = AssetBundle.LoadFromFile(text);
					CosmeticRegistry.LoadCosmeticsFromBundle(val);
					val.Unload(false);
				}
			}
		}

		public static void EnablePlayerObjectsBasedOnConnected()
		{
			int connectedPlayersAmount = StartOfRound.Instance.connectedPlayersAmount;
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				for (int j = 0; j < connectedPlayersAmount + 1; j++)
				{
					if (!val.isPlayerControlled)
					{
						((Component)val).gameObject.SetActive(false);
					}
					else
					{
						((Component)val).gameObject.SetActive(true);
					}
				}
			}
		}

		private void ReadCosmeticsFromFile()
		{
			if (File.Exists(cosmeticSavePath))
			{
				string[] array = File.ReadAllLines(cosmeticSavePath);
				string[] array2 = array;
				foreach (string item in array2)
				{
					CosmeticRegistry.locallySelectedCosmetics.Add(item);
				}
			}
		}

		public static void WriteCosmeticsToFile()
		{
			string text = "";
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				text = text + locallySelectedCosmetic + "\n";
			}
			File.WriteAllText(cosmeticSavePath, text);
		}

		public static void SaveSettingsToFile()
		{
			string text = "";
			text = text + newPlayerCount + "\n";
			text = text + showCosmetics + "\n";
			File.WriteAllText(moreCompanySave, text);
		}

		public static void ReadSettingsFromFile()
		{
			if (File.Exists(moreCompanySave))
			{
				string[] array = File.ReadAllLines(moreCompanySave);
				try
				{
					newPlayerCount = Mathf.Clamp(int.Parse(array[0]), minPlayerCount, maxPlayerCount);
					showCosmetics = bool.Parse(array[1]);
				}
				catch (Exception)
				{
					StaticLogger.LogError((object)"Failed to read settings from file, resetting to default");
					newPlayerCount = 32;
					showCosmetics = true;
				}
			}
		}

		private static void LoadAssets(AssetBundle bundle)
		{
			if (Object.op_Implicit((Object)(object)bundle))
			{
				mainLogo = bundle.LoadPersistentAsset<Texture2D>("assets/morecompanyassets/morecompanytransparentred.png");
				quickMenuScrollParent = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/quickmenuoverride.prefab");
				playerEntry = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/playerlistslot.prefab");
				cosmeticGUIInstance = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/testoverlay.prefab");
				cosmeticButton = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/cosmeticinstance.prefab");
				crewCountUI = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/crewcountfield.prefab");
				bundle.Unload(false);
			}
		}

		public static void ResizePlayerCache(Dictionary<uint, Dictionary<int, NetworkObject>> ScenePlacedObjects)
		{
			//IL_0139: 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_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length != newPlayerCount)
			{
				StaticLogger.LogInfo((object)$"ResizePlayerCache: {newPlayerCount}");
				playerIdsAndCosmetics.Clear();
				uint num = 10000u;
				int num2 = instance.allPlayerObjects.Length;
				int num3 = newPlayerCount - num2;
				Array.Resize(ref instance.allPlayerObjects, newPlayerCount);
				Array.Resize(ref instance.allPlayerScripts, newPlayerCount);
				Array.Resize(ref instance.gameStats.allPlayerStats, newPlayerCount);
				Array.Resize(ref instance.playerSpawnPositions, newPlayerCount);
				StaticLogger.LogInfo((object)$"Resizing player cache from {num2} to {newPlayerCount} with difference of {num3}");
				if (num3 > 0)
				{
					GameObject val = instance.allPlayerObjects[3];
					for (int i = 0; i < num3; i++)
					{
						uint num4 = num + (uint)i;
						GameObject val2 = Object.Instantiate<GameObject>(val, val.transform.parent);
						NetworkObject component = val2.GetComponent<NetworkObject>();
						ReflectionUtils.SetFieldValue(component, "GlobalObjectIdHash", num4);
						Scene scene = ((Component)component).gameObject.scene;
						int handle = ((Scene)(ref scene)).handle;
						uint num5 = num4;
						if (!ScenePlacedObjects.ContainsKey(num5))
						{
							ScenePlacedObjects.Add(num5, new Dictionary<int, NetworkObject>());
						}
						if (ScenePlacedObjects[num5].ContainsKey(handle))
						{
							string arg = (((Object)(object)ScenePlacedObjects[num5][handle] != (Object)null) ? ((Object)ScenePlacedObjects[num5][handle]).name : "Null Entry");
							throw new Exception(((Object)component).name + " tried to registered with ScenePlacedObjects which already contains " + string.Format("the same {0} value {1} for {2}!", "GlobalObjectIdHash", num5, arg));
						}
						ScenePlacedObjects[num5].Add(handle, component);
						((Object)val2).name = $"Player ({4 + i})";
						PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>();
						notSupposedToExistPlayers.Add(componentInChildren);
						componentInChildren.playerClientId = (ulong)(4 + i);
						componentInChildren.playerUsername = $"Player #{componentInChildren.playerClientId}";
						componentInChildren.isPlayerControlled = false;
						componentInChildren.isPlayerDead = false;
						componentInChildren.DropAllHeldItems(false, false);
						componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true);
						UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false);
						instance.allPlayerObjects[num2 + i] = val2;
						instance.gameStats.allPlayerStats[num2 + i] = new PlayerStats();
						instance.allPlayerScripts[num2 + i] = componentInChildren;
						instance.playerSpawnPositions[num2 + i] = instance.playerSpawnPositions[3];
					}
				}
			}
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val3 in allPlayerScripts)
			{
				((TMP_Text)val3.usernameBillboardText).text = val3.playerUsername;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Start")]
	public static class PlayerControllerBStartPatch
	{
		public static void Postfix(ref PlayerControllerB __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "nearByPlayers", value);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")]
	public static class SendNewPlayerValuesServerRpcPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt virtual void System.Collections.Generic.List<ulong>::Add(ulong item)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")]
	public static class SendNewPlayerValuesClientRpcPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening || StartOfRound.Instance.mapScreen.radarTargets.Count == StartOfRound.Instance.allPlayerScripts.Length)
			{
				return;
			}
			List<PlayerControllerB> useless = new List<PlayerControllerB>();
			foreach (PlayerControllerB notSupposedToExistPlayer in MainClass.notSupposedToExistPlayers)
			{
				if (Object.op_Implicit((Object)(object)notSupposedToExistPlayer))
				{
					StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)notSupposedToExistPlayer).transform, notSupposedToExistPlayer.playerUsername, false));
				}
				else
				{
					useless.Add(notSupposedToExistPlayer);
				}
			}
			MainClass.notSupposedToExistPlayers.RemoveAll((PlayerControllerB x) => useless.Contains(x));
		}
	}
	[HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })]
	public static class SyncAllPlayerLevelsPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	public static class SyncShipUnlockablesPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ServerTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (num != 2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt bool Unity.Netcode.NetworkManager::get_IsHost()")
					{
						flag = true;
					}
					else if (((object)instruction).ToString().StartsWith("ldc.i4.4 NULL"))
					{
						num++;
						CodeInstruction val = new CodeInstruction(instruction);
						val.opcode = OpCodes.Ldsfld;
						val.operand = AccessTools.Field(typeof(MainClass), "newPlayerCount");
						list.Add(val);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ClientTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt void UnityEngine.Renderer::set_sharedMaterial(UnityEngine.Material value)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")]
	public static class ScenePlacedObjectsInitPatch
	{
		public static void Postfix(ref Dictionary<uint, Dictionary<int, NetworkObject>> ___ScenePlacedObjects)
		{
			MainClass.ResizePlayerCache(___ScenePlacedObjects);
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")]
	public static class LobbyDataJoinablePatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call int Steamworks.Data.Lobby::get_MemberCount()")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "maxPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
	public static class LobbyThingPatch
	{
		public static void Prefix(ref int maxMembers)
		{
			MainClass.ReadSettingsFromFile();
			maxMembers = MainClass.newPlayerCount;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
	public static class ConnectionApproval
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "ldfld int GameNetworkManager::connectedPlayers")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}

		private static void Postfix(ref GameNetworkManager __instance, ref ConnectionApprovalRequest request, ref ConnectionApprovalResponse response)
		{
			if (response.Approved && __instance.disableSteam)
			{
				string @string = Encoding.ASCII.GetString(request.Payload);
				string[] array = @string.Split(",");
				if (!string.IsNullOrEmpty(@string) && (array.Length < 2 || array[1] != MainClass.newPlayerCount.ToString()))
				{
					response.Reason = $"Crew size mismatch! Their size: {MainClass.newPlayerCount}. Your size: {array[1]}";
					response.Approved = false;
				}
			}
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)__instance.mimickingPlayer != (Object)null) || !MainClass.showCosmetics)
				{
					return;
				}
				List<string> list = MainClass.playerIdsAndCosmetics[(int)__instance.mimickingPlayer.playerClientId];
				Transform val = ((Component)__instance).transform.Find("ScavengerModel").Find("metarig");
				CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ClearCosmetics();
					Object.Destroy((Object)(object)component);
				}
				component = ((Component)val).gameObject.AddComponent<CosmeticApplication>();
				foreach (string item in list)
				{
					component.ApplyCosmetic(item, startEnabled: true);
				}
				foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics)
				{
					Transform transform = ((Component)spawnedCosmetic).transform;
					transform.localScale *= 0.38f;
				}
			}
		}
	}
	public class ReflectionUtils
	{
		public static void InvokeMethod(object obj, string methodName, object[] parameters)
		{
			Type type = obj.GetType();
			MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(obj, parameters);
		}

		public static void InvokeMethod(object obj, Type forceType, string methodName, object[] parameters)
		{
			MethodInfo method = forceType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(obj, parameters);
		}

		public static void SetPropertyValue(object obj, string propertyName, object value)
		{
			Type type = obj.GetType();
			PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			property.SetValue(obj, value);
		}

		public static T InvokeMethod<T>(object obj, string methodName, object[] parameters)
		{
			Type type = obj.GetType();
			MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			return (T)method.Invoke(obj, parameters);
		}

		public static T GetFieldValue<T>(object obj, string fieldName)
		{
			Type type = obj.GetType();
			FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			return (T)field.GetValue(obj);
		}

		public static void SetFieldValue(object obj, string fieldName, object value)
		{
			Type type = obj.GetType();
			FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			field.SetValue(obj, value);
		}
	}
	[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
	public static class ShipTeleporterAwakePatch
	{
		public static void Postfix(ref ShipTeleporter __instance)
		{
			int[] array = new int[MainClass.newPlayerCount];
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				array[i] = -1;
			}
			ReflectionUtils.SetFieldValue(__instance, "playersBeingTeleported", array);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
	public static class SpectatePatches
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SoundManager), "Start")]
	public static class SoundManagerStartPatch
	{
		public static void Postfix(ref SoundManager __instance)
		{
			Array.Resize(ref __instance.playerVoicePitchLerpSpeed, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoicePitchTargets, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoicePitches, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoiceVolumes, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoiceMixers, MainClass.newPlayerCount);
			AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice")));
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				__instance.playerVoicePitchLerpSpeed[i] = 3f;
				__instance.playerVoicePitchTargets[i] = 1f;
				__instance.playerVoicePitches[i] = 1f;
				__instance.playerVoiceVolumes[i] = 0.5f;
				if (!Object.op_Implicit((Object)(object)__instance.playerVoiceMixers[i]))
				{
					__instance.playerVoiceMixers[i] = val;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
	public static class SpawnPositionClampPatch
	{
		public static void Prefix(ref StartOfRound __instance, ref int playerNum, bool simpleTeleport = false)
		{
			if (!Object.op_Implicit((Object)(object)__instance.playerSpawnPositions[playerNum]))
			{
				playerNum = __instance.playerSpawnPositions.Length - 1;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
	public static class OnClientConnectedPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt virtual bool System.Collections.Generic.List<int>::Contains(int item)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public static class LoadLobbyListAndFilterPatch
	{
		private static void Postfix()
		{
			LobbySlot[] array = Object.FindObjectsOfType<LobbySlot>();
			LobbySlot[] array2 = array;
			foreach (LobbySlot val in array2)
			{
				((TMP_Text)val.playerCount).text = $"{((Lobby)(ref val.thisLobby)).MemberCount} / {((Lobby)(ref val.thisLobby)).MaxMembers}";
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Awake")]
	public static class GameNetworkAwakePatch
	{
		public static int originalVersion;

		public static void Postfix(GameNetworkManager __instance)
		{
			originalVersion = __instance.gameVersionNum;
			if (!AssemblyChecker.HasAssemblyLoaded("lc_api"))
			{
				__instance.gameVersionNum = 9999;
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager), "Awake")]
	public static class MenuManagerVersionDisplayPatch
	{
		public static void Postfix(MenuManager __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)__instance.versionNumberText != (Object)null)
			{
				((TMP_Text)__instance.versionNumberText).text = $"v{GameNetworkAwakePatch.originalVersion} (MC)";
			}
		}
	}
}
namespace MoreCompany.Utils
{
	public class AssemblyChecker
	{
		public static bool HasAssemblyLoaded(string name)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				if (assembly.GetName().Name.ToLower().Equals(name))
				{
					return true;
				}
			}
			return false;
		}
	}
	public class BundleUtilities
	{
		public static byte[] GetResourceBytes(string filename, Assembly assembly)
		{
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				if (!text.Contains(filename))
				{
					continue;
				}
				using Stream stream = assembly.GetManifestResourceStream(text);
				if (stream == null)
				{
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				return array;
			}
			return null;
		}

		public static AssetBundle LoadBundleFromInternalAssembly(string filename, Assembly assembly)
		{
			return AssetBundle.LoadFromMemory(GetResourceBytes(filename, assembly));
		}
	}
	public static class AssetBundleExtension
	{
		public static T LoadPersistentAsset<T>(this AssetBundle bundle, string name) where T : Object
		{
			Object val = bundle.LoadAsset(name);
			if (val != (Object)null)
			{
				val.hideFlags = (HideFlags)32;
				return (T)(object)val;
			}
			return default(T);
		}
	}
}
namespace MoreCompany.Cosmetics
{
	public class CosmeticApplication : MonoBehaviour
	{
		public Transform head;

		public Transform hip;

		public Transform lowerArmRight;

		public Transform shinLeft;

		public Transform shinRight;

		public Transform chest;

		public List<CosmeticInstance> spawnedCosmetics = new List<CosmeticInstance>();

		public void Awake()
		{
			head = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003")
				.Find("spine.004");
			chest = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003");
			lowerArmRight = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003")
				.Find("shoulder.R")
				.Find("arm.R_upper")
				.Find("arm.R_lower");
			hip = ((Component)this).transform.Find("spine");
			shinLeft = ((Component)this).transform.Find("spine").Find("thigh.L").Find("shin.L");
			shinRight = ((Component)this).transform.Find("spine").Find("thigh.R").Find("shin.R");
			RefreshAllCosmeticPositions();
		}

		private void OnDisable()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				((Component)spawnedCosmetic).gameObject.SetActive(false);
			}
		}

		private void OnEnable()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				((Component)spawnedCosmetic).gameObject.SetActive(true);
			}
		}

		public void ClearCosmetics()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				Object.Destroy((Object)(object)((Component)spawnedCosmetic).gameObject);
			}
			spawnedCosmetics.Clear();
		}

		public void ApplyCosmetic(string cosmeticId, bool startEnabled)
		{
			if (CosmeticRegistry.cosmeticInstances.ContainsKey(cosmeticId))
			{
				CosmeticInstance cosmeticInstance = CosmeticRegistry.cosmeticInstances[cosmeticId];
				GameObject val = Object.Instantiate<GameObject>(((Component)cosmeticInstance).gameObject);
				val.SetActive(startEnabled);
				CosmeticInstance component = val.GetComponent<CosmeticInstance>();
				spawnedCosmetics.Add(component);
				if (startEnabled)
				{
					ParentCosmetic(component);
				}
			}
		}

		public void RefreshAllCosmeticPositions()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				ParentCosmetic(spawnedCosmetic);
			}
		}

		private void ParentCosmetic(CosmeticInstance cosmeticInstance)
		{
			//IL_006d: 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)
			Transform val = null;
			switch (cosmeticInstance.cosmeticType)
			{
			case CosmeticType.HAT:
				val = head;
				break;
			case CosmeticType.R_LOWER_ARM:
				val = lowerArmRight;
				break;
			case CosmeticType.HIP:
				val = hip;
				break;
			case CosmeticType.L_SHIN:
				val = shinLeft;
				break;
			case CosmeticType.R_SHIN:
				val = shinRight;
				break;
			case CosmeticType.CHEST:
				val = chest;
				break;
			}
			((Component)cosmeticInstance).transform.position = val.position;
			((Component)cosmeticInstance).transform.rotation = val.rotation;
			((Component)cosmeticInstance).transform.parent = val;
		}
	}
	public class CosmeticInstance : MonoBehaviour
	{
		public CosmeticType cosmeticType;

		public string cosmeticId;

		public Texture2D icon;
	}
	public class CosmeticGeneric
	{
		public virtual string gameObjectPath { get; }

		public virtual string cosmeticId { get; }

		public virtual string textureIconPath { get; }

		public CosmeticType cosmeticType { get; }

		public void LoadFromBundle(AssetBundle bundle)
		{
			GameObject val = bundle.LoadPersistentAsset<GameObject>(gameObjectPath);
			Texture2D icon = bundle.LoadPersistentAsset<Texture2D>(textureIconPath);
			CosmeticInstance cosmeticInstance = val.AddComponent<CosmeticInstance>();
			cosmeticInstance.cosmeticId = cosmeticId;
			cosmeticInstance.icon = icon;
			cosmeticInstance.cosmeticType = cosmeticType;
			MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + cosmeticId + " from bundle: " + ((Object)bundle).name));
			CosmeticRegistry.cosmeticInstances.Add(cosmeticId, cosmeticInstance);
		}
	}
	public enum CosmeticType
	{
		HAT,
		WRIST,
		CHEST,
		R_LOWER_ARM,
		HIP,
		L_SHIN,
		R_SHIN
	}
	public class CosmeticRegistry
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__8_0;

			public static UnityAction <>9__8_1;

			internal void <SpawnCosmeticGUI>b__8_0()
			{
				MainClass.showCosmetics = true;
				MainClass.SaveSettingsToFile();
			}

			internal void <SpawnCosmeticGUI>b__8_1()
			{
				MainClass.showCosmetics = false;
				MainClass.SaveSettingsToFile();
			}
		}

		public static Dictionary<string, CosmeticInstance> cosmeticInstances = new Dictionary<string, CosmeticInstance>();

		public static GameObject cosmeticGUI;

		private static GameObject displayGuy;

		private static CosmeticApplication cosmeticApplication;

		public static List<string> locallySelectedCosmetics = new List<string>();

		public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f;

		public static void LoadCosmeticsFromBundle(AssetBundle bundle)
		{
			string[] allAssetNames = bundle.GetAllAssetNames();
			foreach (string text in allAssetNames)
			{
				if (!text.EndsWith(".prefab"))
				{
					continue;
				}
				GameObject val = bundle.LoadPersistentAsset<GameObject>(text);
				CosmeticInstance component = val.GetComponent<CosmeticInstance>();
				if (!((Object)(object)component == (Object)null))
				{
					MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + component.cosmeticId + " from bundle"));
					if (cosmeticInstances.ContainsKey(component.cosmeticId))
					{
						MainClass.StaticLogger.LogError((object)("Duplicate cosmetic id: " + component.cosmeticId));
					}
					else
					{
						cosmeticInstances.Add(component.cosmeticId, component);
					}
				}
			}
		}

		public static void LoadCosmeticsFromAssembly(Assembly assembly, AssetBundle bundle)
		{
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.IsSubclassOf(typeof(CosmeticGeneric)))
				{
					CosmeticGeneric cosmeticGeneric = (CosmeticGeneric)type.GetConstructor(new Type[0]).Invoke(new object[0]);
					cosmeticGeneric.LoadFromBundle(bundle);
				}
			}
		}

		public static void SpawnCosmeticGUI()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			cosmeticGUI = Object.Instantiate<GameObject>(MainClass.cosmeticGUIInstance);
			((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale")).transform.localScale = new Vector3(2f, 2f, 2f);
			displayGuy = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("ObjectHolder")
				.Find("ScavengerModel")
				.Find("metarig")).gameObject;
			cosmeticApplication = displayGuy.AddComponent<CosmeticApplication>();
			GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("EnableButton")).gameObject;
			ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick;
			object obj = <>c.<>9__8_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					MainClass.showCosmetics = true;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_0 = val;
				obj = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			GameObject gameObject2 = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("DisableButton")).gameObject;
			ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick;
			object obj2 = <>c.<>9__8_1;
			if (obj2 == null)
			{
				UnityAction val2 = delegate
				{
					MainClass.showCosmetics = false;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_1 = val2;
				obj2 = (object)val2;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			if (MainClass.showCosmetics)
			{
				gameObject.SetActive(false);
				gameObject2.SetActive(true);
			}
			else
			{
				gameObject.SetActive(true);
				gameObject2.SetActive(false);
			}
			PopulateCosmetics();
			UpdateCosmeticsOnDisplayGuy(startEnabled: false);
		}

		public static void PopulateCosmetics()
		{
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Expected O, but got Unknown
			GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("CosmeticsHolder")
				.Find("Content")).gameObject;
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				list.Add(gameObject.transform.GetChild(i));
			}
			foreach (Transform item in list)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
			foreach (KeyValuePair<string, CosmeticInstance> cosmeticInstance in cosmeticInstances)
			{
				GameObject val = Object.Instantiate<GameObject>(MainClass.cosmeticButton, gameObject.transform);
				val.transform.localScale = Vector3.one;
				GameObject disabledOverlay = ((Component)val.transform.Find("Deselected")).gameObject;
				disabledOverlay.SetActive(true);
				GameObject enabledOverlay = ((Component)val.transform.Find("Selected")).gameObject;
				enabledOverlay.SetActive(true);
				if (IsEquipped(cosmeticInstance.Value.cosmeticId))
				{
					enabledOverlay.SetActive(true);
					disabledOverlay.SetActive(false);
				}
				else
				{
					enabledOverlay.SetActive(false);
					disabledOverlay.SetActive(true);
				}
				RawImage component = ((Component)val.transform.Find("Icon")).GetComponent<RawImage>();
				component.texture = (Texture)(object)cosmeticInstance.Value.icon;
				Button component2 = val.GetComponent<Button>();
				((UnityEvent)component2.onClick).AddListener((UnityAction)delegate
				{
					ToggleCosmetic(cosmeticInstance.Value.cosmeticId);
					if (IsEquipped(cosmeticInstance.Value.cosmeticId))
					{
						enabledOverlay.SetActive(true);
						disabledOverlay.SetActive(false);
					}
					else
					{
						enabledOverlay.SetActive(false);
						disabledOverlay.SetActive(true);
					}
					MainClass.WriteCosmeticsToFile();
					UpdateCosmeticsOnDisplayGuy(startEnabled: true);
				});
			}
		}

		private static Color HexToColor(string hex)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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)
			Color result = default(Color);
			ColorUtility.TryParseHtmlString(hex, ref result);
			return result;
		}

		public static void UpdateCosmeticsOnDisplayGuy(bool startEnabled)
		{
			cosmeticApplication.ClearCosmetics();
			foreach (string locallySelectedCosmetic in locallySelectedCosmetics)
			{
				cosmeticApplication.ApplyCosmetic(locallySelectedCosmetic, startEnabled);
			}
			foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics)
			{
				RecursiveLayerChange(((Component)spawnedCosmetic).transform, 5);
			}
		}

		private static void RecursiveLayerChange(Transform transform, int layer)
		{
			((Component)transform).gameObject.layer = layer;
			for (int i = 0; i < transform.childCount; i++)
			{
				RecursiveLayerChange(transform.GetChild(i), layer);
			}
		}

		public static bool IsEquipped(string cosmeticId)
		{
			return locallySelectedCosmetics.Contains(cosmeticId);
		}

		public static void ToggleCosmetic(string cosmeticId)
		{
			if (locallySelectedCosmetics.Contains(cosmeticId))
			{
				locallySelectedCosmetics.Remove(cosmeticId);
			}
			else
			{
				locallySelectedCosmetics.Add(cosmeticId);
			}
		}
	}
}
namespace MoreCompany.Behaviors
{
	public class SpinDragger : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler
	{
		public float speed = 1f;

		private Vector2 lastMousePosition;

		private bool dragging = false;

		private Vector3 rotationalVelocity = Vector3.zero;

		public float dragSpeed = 1f;

		public float airDrag = 0.99f;

		public GameObject target;

		private void Update()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (dragging)
			{
				Vector3 val = Vector2.op_Implicit(((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue() - lastMousePosition);
				rotationalVelocity += new Vector3(0f, 0f - val.x, 0f) * dragSpeed;
				lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			}
			rotationalVelocity *= airDrag;
			target.transform.Rotate(rotationalVelocity * Time.deltaTime * speed, (Space)0);
		}

		public void OnPointerDown(PointerEventData eventData)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			dragging = true;
		}

		public void OnPointerUp(PointerEventData eventData)
		{
			dragging = false;
		}
	}
}

BepInEx/plugins/OrtonLongGaming-FreddyBracken/FreddyBracken.dll

Decompiled 9 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FreddyBracken")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreddyBracken")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("2ed810b2-476e-4150-b015-645ee4681b3d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace FreddyBracken
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "FreddyBracken";

		public const string PLUGIN_NAME = "FreddyBracken";

		public const string PLUGIN_VERSION = "1.0.4";
	}
	[BepInPlugin("FreddyBracken", "FreddyBracken", "1.0.4")]
	public class Plugin : BaseUnityPlugin
	{
		public static GameObject Visuals;

		public static AudioClip NeckCrackAudio;

		public static AudioClip AngeredAudio;

		public static Texture2D FreddyMaterial;

		public static Texture2D FreddyNormal;

		public static Texture2D FreddyEyes;

		public static ConfigEntry<bool> useFreddyTextures;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin FreddyBracken is loaded!");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "freddy.bundle");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			Visuals = val.LoadAsset<GameObject>("assets/prefabs/freddy.prefab");
			NeckCrackAudio = val.LoadAsset<AudioClip>("assets/prefabs/freddycrackneck.wav");
			AngeredAudio = val.LoadAsset<AudioClip>("assets/prefabs/freddyangered.wav");
			FreddyMaterial = val.LoadAsset<Texture2D>("assets/prefabs/freddy_albedo.png");
			FreddyNormal = val.LoadAsset<Texture2D>("assets/prefabs/freddy_normal.png");
			FreddyEyes = val.LoadAsset<Texture2D>("assets/prefabs/freddy_eyes_albedo.png");
			useFreddyTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("FreddyBracken", "UseFreddyTextures", false, "Swap out the default dark Bracken body material for Freddy's actual brown fur, bowtie, etc materials.");
			SkinnedMeshRenderer[] componentsInChildren = Visuals.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val2 in componentsInChildren)
			{
				((Component)val2).gameObject.layer = LayerMask.NameToLayer("Enemies");
			}
		}
	}
}
namespace FreddyBracken.Patches
{
	[HarmonyPatch(typeof(FlowermanAI), "Start")]
	internal class FlowermanPatch
	{
		private static void Postfix(FlowermanAI __instance)
		{
			//IL_00e3: 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_0105: 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_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected O, but got Unknown
			if ((Object)(object)Plugin.Visuals == (Object)null)
			{
				return;
			}
			Transform val = ((Component)__instance).transform.Find("FlowermanModel");
			object obj;
			if (val == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val.Find("LOD1");
				obj = ((obj2 != null) ? ((Component)obj2).GetComponent<SkinnedMeshRenderer>() : null);
			}
			SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)obj;
			object obj3;
			if (val == null)
			{
				obj3 = null;
			}
			else
			{
				Transform obj4 = val.Find("AnimContainer");
				obj3 = ((obj4 != null) ? obj4.Find("metarig") : null);
			}
			Transform val3 = (Transform)obj3;
			if (!((Object)(object)val2 == (Object)null) && ((Renderer)val2).enabled)
			{
				((Renderer)val2).enabled = false;
				Renderer[] componentsInChildren = ((Component)val3).gameObject.GetComponentsInChildren<Renderer>();
				foreach (Renderer val4 in componentsInChildren)
				{
					val4.enabled = false;
				}
				GameObject val5 = Object.Instantiate<GameObject>(Plugin.Visuals);
				val5.transform.SetParent(val);
				val5.transform.localPosition = Vector3.zero;
				val5.transform.localRotation = Quaternion.identity;
				val5.transform.localScale = Vector3.one;
				Transform val6 = val5.transform.Find("Container/Body_Geo");
				Transform val7 = val5.transform.Find("Container/metarig");
				val7.SetParent(val3.parent, true);
				((Component)val7).transform.localScale = ((Component)val3).transform.localScale;
				((Component)val7).transform.localRotation = ((Component)val3).transform.localRotation;
				((Component)val7).transform.localPosition = ((Component)val3).transform.localPosition;
				SkinnedMeshRenderer component = ((Component)val6).GetComponent<SkinnedMeshRenderer>();
				component.rootBone = val7;
				if (Plugin.useFreddyTextures.Value)
				{
					MaterialPropertyBlock val8 = new MaterialPropertyBlock();
					((Renderer)component).GetPropertyBlock(val8, 0);
					val8.SetColor("_BaseColor", Color.white);
					val8.SetColor("_Color", Color.white);
					val8.SetTexture("_BaseColorMap", (Texture)(object)Plugin.FreddyMaterial);
					val8.SetVector("_BaseColorMap_ST", new Vector4(1f, 1f, 0f, 0f));
					val8.SetFloat("_NormalMapSpace", 0f);
					val8.SetTexture("_NormalMap", (Texture)(object)Plugin.FreddyNormal);
					val8.SetVector("_NormalMap_ST", new Vector4(1f, 1f, 0f, 0f));
					val8.SetFloat("_Metallic", 0f);
					((Renderer)component).SetPropertyBlock(val8, 0);
					MaterialPropertyBlock val9 = new MaterialPropertyBlock();
					((Renderer)component).GetPropertyBlock(val9, 1);
					val8.SetTexture("_BaseColorMap", (Texture)(object)Plugin.FreddyEyes);
					((Renderer)component).SetPropertyBlock(val9, 1);
				}
				((Object)val3).name = "old-metarig";
				__instance.crackNeckSFX = Plugin.NeckCrackAudio;
				__instance.creatureAngerVoice.clip = Plugin.AngeredAudio;
				__instance.rightHandGrip = val7.Find("Torso1").Find("Torso2").Find("Torso3")
					.Find("Arm1.R")
					.Find("Arm2.R")
					.Find("Arm3.R")
					.Find("Hand1.R")
					.Find("HandGripPosition");
			}
		}
	}
}

BepInEx/plugins/RugbugRedfern-Skinwalkers/SkinwalkerMod.dll

Decompiled 9 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance;
using Dissonance.Config;
using HarmonyLib;
using SkinwalkerMod.Properties;
using Steamworks;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("SkinwalkerMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SkinwalkerMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("fd4979a2-cef0-46af-8bf8-97e630b11475")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>();
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>();
	}
}
namespace SkinwalkerMod
{
	internal class LogoManager : MonoBehaviour
	{
		private AssetBundle bundle;

		private readonly Logo[] logos = new Logo[6]
		{
			new Logo
			{
				fileName = "Teo",
				playerNames = new string[9] { "SAMMY", "paddy", "Ozias", "Teo", "Rugbug Redfern", "WuluKing", "Boolie", "TeaEditor", "FlashGamesNemesis" }
			},
			new Logo
			{
				fileName = "OfflineTV",
				playerNames = new string[3] { "Masayoshi", "QUARTERJADE", "DisguisedToast" }
			},
			new Logo
			{
				fileName = "Neuro",
				playerNames = new string[1] { "vedal" }
			},
			new Logo
			{
				fileName = "Mogul",
				playerNames = new string[2] { "ludwig", "AirCoots" }
			},
			new Logo
			{
				fileName = "Imp",
				playerNames = new string[1] { "camila" }
			},
			new Logo
			{
				fileName = "Iron",
				playerNames = new string[1] { "ironmouse" }
			}
		};

		private Image cachedHeader;

		private Image cachedLogoHeader;

		private void Awake()
		{
			try
			{
				bundle = AssetBundle.LoadFromMemory(Resources.logos);
				SceneManager.sceneLoaded += OnSceneLoaded;
			}
			catch (Exception ex)
			{
				SkinwalkerLogger.LogError("LogoManager Awake Error: " + ex.Message);
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			try
			{
				if (!(((Scene)(ref scene)).name == "MainMenu"))
				{
					return;
				}
				cachedHeader = GameObject.Find("HeaderImage").GetComponent<Image>();
				cachedLogoHeader = ((Component)GameObject.Find("Canvas/MenuContainer").transform.GetChild(0).GetChild(1)).GetComponent<Image>();
				string value = SteamClient.Name.ToString();
				Logo[] array = logos;
				foreach (Logo logo in array)
				{
					string[] playerNames = logo.playerNames;
					foreach (string text in playerNames)
					{
						if (text.Equals(value, StringComparison.OrdinalIgnoreCase))
						{
							((MonoBehaviour)this).StartCoroutine(I_ChangeLogo(bundle.LoadAsset<Sprite>("Assets/Logos/" + logo.fileName + ".png")));
							return;
						}
					}
				}
			}
			catch (Exception ex)
			{
				SkinwalkerLogger.LogError("LogoManager OnSceneLoaded Error: " + ex.Message + ". If you launched in LAN mode, then this is just gonna happen, it doesn't break anything so don't worry about it.");
			}
		}

		private IEnumerator I_ChangeLogo(Sprite sprite)
		{
			for (int i = 0; i < 20; i++)
			{
				if ((Object)(object)cachedHeader == (Object)null)
				{
					break;
				}
				if ((Object)(object)cachedLogoHeader == (Object)null)
				{
					break;
				}
				SetHeaderImage(sprite);
				yield return null;
			}
		}

		private void SetHeaderImage(Sprite sprite)
		{
			if (!((Object)(object)sprite == (Object)null))
			{
				cachedHeader.sprite = sprite;
				cachedLogoHeader.sprite = sprite;
			}
		}
	}
	internal class Logo
	{
		public string fileName;

		public string[] playerNames;
	}
	[BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "2.0.7")]
	internal class PluginLoader : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod");

		private const string modGUID = "RugbugRedfern.SkinwalkerMod";

		private const string modVersion = "2.0.7";

		private static bool initialized;

		public static PluginLoader Instance { get; private set; }

		private void Awake()
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			if (initialized)
			{
				return;
			}
			initialized = true;
			Instance = this;
			harmony.PatchAll(Assembly.GetExecutingAssembly());
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod");
			SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 2.0.7");
			SkinwalkerConfig.InitConfig();
			SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer;
			GameObject val = new GameObject("Skinwalker Mod");
			val.AddComponent<SkinwalkerModPersistent>();
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val);
			Logs.SetLogLevel((LogCategory)1, (LogLevel)4);
			Logs.SetLogLevel((LogCategory)3, (LogLevel)4);
			Logs.SetLogLevel((LogCategory)2, (LogLevel)4);
			GameObject val2 = new GameObject("Logo Manager");
			val2.AddComponent<LogoManager>();
			((Object)val2).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val2);
		}

		public void BindConfig<T>(ref ConfigEntry<T> config, string section, string key, T defaultValue, string description = "")
		{
			config = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description);
		}
	}
	internal class SkinwalkerBehaviour : MonoBehaviour
	{
		private AudioSource audioSource;

		public const float PLAY_INTERVAL_MIN = 15f;

		public const float PLAY_INTERVAL_MAX = 40f;

		private const float MAX_DIST = 100f;

		private float nextTimeToPlayAudio;

		private EnemyAI ai;

		public void Initialize(EnemyAI ai)
		{
			this.ai = ai;
			audioSource = ai.creatureVoice;
			SetNextTime();
		}

		private void Update()
		{
			if (Time.time > nextTimeToPlayAudio)
			{
				SetNextTime();
				AttemptPlaySound();
			}
		}

		private void AttemptPlaySound()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			float num = -1f;
			if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead)
			{
				if (((Object)((Component)ai).gameObject).name == "DressGirl(Clone)")
				{
					DressGirlAI val = (DressGirlAI)ai;
					if ((Object)(object)val.hauntingPlayer != (Object)(object)StartOfRound.Instance.localPlayerController)
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not haunted) EnemyAI: " + (object)ai);
						return;
					}
					if (!val.staringInHaunt && !((EnemyAI)val).moveTowardsDestination)
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not visible) EnemyAI: " + (object)ai);
						return;
					}
				}
				Vector3 val2 = (StartOfRound.Instance.localPlayerController.isPlayerDead ? ((Component)StartOfRound.Instance.spectateCamera).transform.position : ((Component)StartOfRound.Instance.localPlayerController).transform.position);
				if ((Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(val2, ((Component)this).transform.position)) < 100f)
				{
					AudioClip sample = SkinwalkerModPersistent.Instance.GetSample();
					if (Object.op_Implicit((Object)(object)sample))
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line 1");
						audioSource.PlayOneShot(sample);
					}
					else
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line 0");
					}
				}
				else
				{
					SkinwalkerLogger.Log(((Object)this).name + " played voice line no (too far away) " + num);
				}
			}
			else
			{
				SkinwalkerLogger.Log(((Object)this).name + " played voice line no (dead) EnemyAI: " + (object)ai);
			}
		}

		private void SetNextTime()
		{
			if (SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value <= 0f)
			{
				nextTimeToPlayAudio = Time.time + 100000000f;
			}
			else
			{
				nextTimeToPlayAudio = Time.time + Random.Range(15f, 40f) / SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value;
			}
		}

		private T CopyComponent<T>(T original, GameObject destination) where T : Component
		{
			Type type = ((object)original).GetType();
			Component val = destination.AddComponent(type);
			FieldInfo[] fields = type.GetFields();
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				fieldInfo.SetValue(val, fieldInfo.GetValue(original));
			}
			return (T)(object)((val is T) ? val : null);
		}
	}
	internal class SkinwalkerConfig
	{
		public static ConfigEntry<bool> VoiceEnabled_BaboonHawk;

		public static ConfigEntry<bool> VoiceEnabled_Bracken;

		public static ConfigEntry<bool> VoiceEnabled_BunkerSpider;

		public static ConfigEntry<bool> VoiceEnabled_Centipede;

		public static ConfigEntry<bool> VoiceEnabled_CoilHead;

		public static ConfigEntry<bool> VoiceEnabled_EyelessDog;

		public static ConfigEntry<bool> VoiceEnabled_ForestGiant;

		public static ConfigEntry<bool> VoiceEnabled_GhostGirl;

		public static ConfigEntry<bool> VoiceEnabled_GiantWorm;

		public static ConfigEntry<bool> VoiceEnabled_HoardingBug;

		public static ConfigEntry<bool> VoiceEnabled_Hygrodere;

		public static ConfigEntry<bool> VoiceEnabled_Jester;

		public static ConfigEntry<bool> VoiceEnabled_Masked;

		public static ConfigEntry<bool> VoiceEnabled_Nutcracker;

		public static ConfigEntry<bool> VoiceEnabled_SporeLizard;

		public static ConfigEntry<bool> VoiceEnabled_Thumper;

		public static ConfigEntry<bool> VoiceEnabled_OtherEnemies;

		public static ConfigEntry<float> VoiceLineFrequency;

		public static void InitConfig()
		{
			PluginLoader.Instance.BindConfig(ref VoiceLineFrequency, "Voice Settings", "VoiceLineFrequency", 1f, "1 is the default, and voice lines will occur every " + 15f.ToString("0") + " to " + 40f.ToString("0") + " seconds per enemy. Setting this to 2 means they will occur twice as often, 0.5 means half as often, etc.");
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_BaboonHawk, "Monster Voices", "Baboon Hawk", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Bracken, "Monster Voices", "Bracken", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_BunkerSpider, "Monster Voices", "Bunker Spider", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Centipede, "Monster Voices", "Centipede", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_CoilHead, "Monster Voices", "Coil Head", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_EyelessDog, "Monster Voices", "Eyeless Dog", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_ForestGiant, "Monster Voices", "Forest Giant", defaultValue: false);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_GhostGirl, "Monster Voices", "Ghost Girl", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_GiantWorm, "Monster Voices", "Giant Worm", defaultValue: false);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_HoardingBug, "Monster Voices", "Hoarding Bug", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Hygrodere, "Monster Voices", "Hygrodere", defaultValue: false);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Jester, "Monster Voices", "Jester", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Masked, "Monster Voices", "Masked", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Nutcracker, "Monster Voices", "Nutcracker", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_SporeLizard, "Monster Voices", "Spore Lizard", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_Thumper, "Monster Voices", "Thumper", defaultValue: true);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_OtherEnemies, "Monster Voices", "Other Enemies (Including Modded)", defaultValue: true);
			SkinwalkerLogger.Log("VoiceEnabled_BaboonHawk" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BaboonHawk.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Bracken" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Bracken.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_BunkerSpider" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BunkerSpider.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Centipede" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Centipede.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_CoilHead" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_CoilHead.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_EyelessDog" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_EyelessDog.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_ForestGiant" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_ForestGiant.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_GhostGirl" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GhostGirl.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_GiantWorm" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GiantWorm.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_HoardingBug" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_HoardingBug.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Hygrodere" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Hygrodere.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Jester" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Jester.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Masked" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Masked.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Nutcracker" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Nutcracker.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_SporeLizard" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_SporeLizard.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_Thumper" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Thumper.Value}]");
			SkinwalkerLogger.Log("VoiceEnabled_OtherEnemies" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_OtherEnemies.Value}]");
			SkinwalkerLogger.Log("VoiceLineFrequency" + $" VALUE LOADED FROM CONFIG: [{VoiceLineFrequency.Value}]");
		}
	}
	internal static class SkinwalkerLogger
	{
		internal static ManualLogSource logSource;

		public static void Initialize(string modGUID)
		{
			logSource = Logger.CreateLogSource(modGUID);
		}

		public static void Log(object message)
		{
			logSource.LogInfo(message);
		}

		public static void LogError(object message)
		{
			logSource.LogError(message);
		}

		public static void LogWarning(object message)
		{
			logSource.LogWarning(message);
		}
	}
	public class SkinwalkerModPersistent : MonoBehaviour
	{
		private string audioFolder;

		private List<AudioClip> cachedAudio = new List<AudioClip>();

		private float nextTimeToCheckFolder = 30f;

		private float nextTimeToCheckEnemies = 30f;

		private const float folderScanInterval = 8f;

		private const float enemyScanInterval = 5f;

		public static SkinwalkerModPersistent Instance { get; private set; }

		private void Awake()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			((Component)this).transform.position = Vector3.zero;
			SkinwalkerLogger.Log("Skinwalker Mod Object Initialized");
			audioFolder = Path.Combine(Application.dataPath, "..", "Dissonance_Diagnostics");
			EnableRecording();
			if (!Directory.Exists(audioFolder))
			{
				Directory.CreateDirectory(audioFolder);
			}
		}

		private void Start()
		{
			try
			{
				if (Directory.Exists(audioFolder))
				{
					Directory.Delete(audioFolder, recursive: true);
				}
			}
			catch (Exception message)
			{
				SkinwalkerLogger.Log(message);
			}
		}

		private void OnApplicationQuit()
		{
			DisableRecording();
		}

		private void EnableRecording()
		{
			DebugSettings.Instance.EnablePlaybackDiagnostics = true;
			DebugSettings.Instance.RecordFinalAudio = true;
		}

		private void Update()
		{
			if (Time.realtimeSinceStartup > nextTimeToCheckFolder)
			{
				nextTimeToCheckFolder = Time.realtimeSinceStartup + 8f;
				if (!Directory.Exists(audioFolder))
				{
					SkinwalkerLogger.Log("Audio folder not present. Don't worry about it, it will be created automatically when you play with friends. (" + audioFolder + ")");
					return;
				}
				string[] files = Directory.GetFiles(audioFolder);
				SkinwalkerLogger.Log($"Got audio file paths ({files.Length})");
				string[] array = files;
				foreach (string path in array)
				{
					((MonoBehaviour)this).StartCoroutine(LoadWavFile(path, delegate(AudioClip audioClip)
					{
						cachedAudio.Add(audioClip);
					}));
				}
			}
			if (!(Time.realtimeSinceStartup > nextTimeToCheckEnemies))
			{
				return;
			}
			nextTimeToCheckEnemies = Time.realtimeSinceStartup + 5f;
			EnemyAI[] array2 = Object.FindObjectsOfType<EnemyAI>(true);
			EnemyAI[] array3 = array2;
			SkinwalkerBehaviour skinwalkerBehaviour = default(SkinwalkerBehaviour);
			foreach (EnemyAI val in array3)
			{
				SkinwalkerLogger.Log("IsEnemyEnabled " + ((Object)val).name + " " + IsEnemyEnabled(val));
				if (IsEnemyEnabled(val) && !((Component)val).TryGetComponent<SkinwalkerBehaviour>(ref skinwalkerBehaviour))
				{
					((Component)val).gameObject.AddComponent<SkinwalkerBehaviour>().Initialize(val);
				}
			}
		}

		private bool IsEnemyEnabled(EnemyAI enemy)
		{
			if ((Object)(object)enemy == (Object)null)
			{
				return false;
			}
			return ((Object)((Component)enemy).gameObject).name switch
			{
				"MaskedPlayerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Masked.Value, 
				"NutcrackerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Nutcracker.Value, 
				"BaboonHawkEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BaboonHawk.Value, 
				"Flowerman(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Bracken.Value, 
				"SandSpider(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BunkerSpider.Value, 
				"RedLocustBees(Clone)" => false, 
				"Centipede(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Centipede.Value, 
				"SpringMan(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_CoilHead.Value, 
				"MouthDog(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_EyelessDog.Value, 
				"ForestGiant(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_ForestGiant.Value, 
				"DressGirl(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GhostGirl.Value, 
				"SandWorm(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GiantWorm.Value, 
				"HoarderBug(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_HoardingBug.Value, 
				"Blob(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Hygrodere.Value, 
				"JesterEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Jester.Value, 
				"PufferEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_SporeLizard.Value, 
				"Crawler(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Thumper.Value, 
				"DocileLocustBees(Clone)" => false, 
				"DoublewingedBird(Clone)" => false, 
				_ => SkinwalkerNetworkManager.Instance.VoiceEnabled_OtherEnemies.Value, 
			};
		}

		internal IEnumerator LoadWavFile(string path, Action<AudioClip> callback)
		{
			UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
			try
			{
				yield return www.SendWebRequest();
				if ((int)www.result == 1)
				{
					SkinwalkerLogger.Log("Loaded clip from path " + path);
					AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www);
					if (audioClip.length > 0.9f)
					{
						callback(audioClip);
					}
					try
					{
						File.Delete(path);
					}
					catch (Exception e)
					{
						SkinwalkerLogger.LogWarning(e);
					}
				}
			}
			finally
			{
				((IDisposable)www)?.Dispose();
			}
		}

		private void DisableRecording()
		{
			DebugSettings.Instance.EnablePlaybackDiagnostics = false;
			DebugSettings.Instance.RecordFinalAudio = false;
			if (Directory.Exists(audioFolder))
			{
				Directory.Delete(audioFolder, recursive: true);
			}
		}

		public AudioClip GetSample()
		{
			while (cachedAudio.Count > 200)
			{
				cachedAudio.RemoveAt(Random.Range(0, cachedAudio.Count));
			}
			if (cachedAudio.Count > 0)
			{
				int index = Random.Range(0, cachedAudio.Count - 1);
				AudioClip result = cachedAudio[index];
				cachedAudio.RemoveAt(index);
				return result;
			}
			return null;
		}

		public void ClearCache()
		{
			cachedAudio.Clear();
		}
	}
	internal static class SkinwalkerNetworkManagerHandler
	{
		internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if (((Scene)(ref sceneName)).name == "SampleSceneRelay")
			{
				GameObject val = new GameObject("SkinwalkerNetworkManager");
				val.AddComponent<NetworkObject>();
				val.AddComponent<SkinwalkerNetworkManager>();
				Debug.Log((object)"Initialized SkinwalkerNetworkManager");
			}
		}
	}
	internal class SkinwalkerNetworkManager : NetworkBehaviour
	{
		public NetworkVariable<bool> VoiceEnabled_BaboonHawk = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Bracken = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_BunkerSpider = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Centipede = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_CoilHead = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_EyelessDog = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_ForestGiant = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_GhostGirl = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_GiantWorm = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_HoardingBug = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Hygrodere = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Jester = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Masked = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Nutcracker = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_SporeLizard = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_Thumper = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<bool> VoiceEnabled_OtherEnemies = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public NetworkVariable<float> VoiceLineFrequency = new NetworkVariable<float>(1f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static SkinwalkerNetworkManager Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			if (GameNetworkManager.Instance.isHostingGame)
			{
				VoiceEnabled_BaboonHawk.Value = SkinwalkerConfig.VoiceEnabled_BaboonHawk.Value;
				VoiceEnabled_Bracken.Value = SkinwalkerConfig.VoiceEnabled_Bracken.Value;
				VoiceEnabled_BunkerSpider.Value = SkinwalkerConfig.VoiceEnabled_BunkerSpider.Value;
				VoiceEnabled_Centipede.Value = SkinwalkerConfig.VoiceEnabled_Centipede.Value;
				VoiceEnabled_CoilHead.Value = SkinwalkerConfig.VoiceEnabled_CoilHead.Value;
				VoiceEnabled_EyelessDog.Value = SkinwalkerConfig.VoiceEnabled_EyelessDog.Value;
				VoiceEnabled_ForestGiant.Value = SkinwalkerConfig.VoiceEnabled_ForestGiant.Value;
				VoiceEnabled_GhostGirl.Value = SkinwalkerConfig.VoiceEnabled_GhostGirl.Value;
				VoiceEnabled_GiantWorm.Value = SkinwalkerConfig.VoiceEnabled_GiantWorm.Value;
				VoiceEnabled_HoardingBug.Value = SkinwalkerConfig.VoiceEnabled_HoardingBug.Value;
				VoiceEnabled_Hygrodere.Value = SkinwalkerConfig.VoiceEnabled_Hygrodere.Value;
				VoiceEnabled_Jester.Value = SkinwalkerConfig.VoiceEnabled_Jester.Value;
				VoiceEnabled_Masked.Value = SkinwalkerConfig.VoiceEnabled_Masked.Value;
				VoiceEnabled_Nutcracker.Value = SkinwalkerConfig.VoiceEnabled_Nutcracker.Value;
				VoiceEnabled_SporeLizard.Value = SkinwalkerConfig.VoiceEnabled_SporeLizard.Value;
				VoiceEnabled_Thumper.Value = SkinwalkerConfig.VoiceEnabled_Thumper.Value;
				VoiceEnabled_OtherEnemies.Value = SkinwalkerConfig.VoiceEnabled_OtherEnemies.Value;
				VoiceLineFrequency.Value = SkinwalkerConfig.VoiceLineFrequency.Value;
				SkinwalkerLogger.Log("HOST SENDING CONFIG TO CLIENTS");
			}
			SkinwalkerLogger.Log("SkinwalkerNetworkManager Awake");
		}

		public override void OnDestroy()
		{
			((NetworkBehaviour)this).OnDestroy();
			SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy");
			SkinwalkerModPersistent.Instance?.ClearCache();
		}

		protected override void __initializeVariables()
		{
			if (VoiceEnabled_BaboonHawk == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk);
			if (VoiceEnabled_Bracken == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken);
			if (VoiceEnabled_BunkerSpider == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider);
			if (VoiceEnabled_Centipede == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede);
			if (VoiceEnabled_CoilHead == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead);
			if (VoiceEnabled_EyelessDog == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog);
			if (VoiceEnabled_ForestGiant == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant);
			if (VoiceEnabled_GhostGirl == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl);
			if (VoiceEnabled_GiantWorm == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm);
			if (VoiceEnabled_HoardingBug == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug);
			if (VoiceEnabled_Hygrodere == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere);
			if (VoiceEnabled_Jester == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester);
			if (VoiceEnabled_Masked == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked);
			if (VoiceEnabled_Nutcracker == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker);
			if (VoiceEnabled_SporeLizard == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard);
			if (VoiceEnabled_Thumper == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper);
			if (VoiceEnabled_OtherEnemies == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_OtherEnemies cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_OtherEnemies).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies, "VoiceEnabled_OtherEnemies");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies);
			if (VoiceLineFrequency == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency);
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "SkinwalkerNetworkManager";
		}
	}
}
namespace SkinwalkerMod.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("SkinwalkerMod.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] logos
		{
			get
			{
				object @object = ResourceManager.GetObject("logos", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}

BepInEx/plugins/SerasSquad-Axel_Metal_Bar/LethalClunk/LethalClunk.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalClunk")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Mod to replace the Large Axle drop sound with the metal bar meme sound")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+32ab32b67da71ea7b44296192ba03dfcf26f159a")]
[assembly: AssemblyProduct("LethalClunk")]
[assembly: AssemblyTitle("LethalClunk")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
public static class ExtensionMethods
{
	public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
	{
		TaskCompletionSource<object?> tcs = new TaskCompletionSource<object>();
		asyncOp.completed += delegate
		{
			tcs.SetResult(null);
		};
		return ((Task)tcs.Task).GetAwaiter();
	}
}
namespace LethalClunk
{
	[BepInPlugin("LethalClunk", "LethalClunk", "1.1.1")]
	[BepInProcess("Lethal Company.exe")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("LethalClunk");

		private readonly ManualLogSource logger;

		public Plugin()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			logger = Logger.CreateLogSource("LethalClunk");
		}

		public void Awake()
		{
			harmony.PatchAll();
			logger.LogInfo((object)"Plugin LethalClunk is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalClunk";

		public const string PLUGIN_NAME = "LethalClunk";

		public const string PLUGIN_VERSION = "1.1.1";
	}
}
namespace LethalClunk.Patches
{
	[HarmonyPatch(typeof(GrabbableObject))]
	internal class LethalClunkPatch
	{
		private static ManualLogSource logger = Logger.CreateLogSource("LethalClunk");

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static async void ReplaceLargeAxleSFX(GrabbableObject __instance)
		{
			Item item = __instance.itemProperties;
			AudioClip audioClip = await LoadAudioClip("metal_bar.wav");
			if (item.itemName == "Large axle")
			{
				logger.LogInfo((object)"Large Axle Spawned");
				if ((Object)(object)audioClip != (Object)null)
				{
					item.dropSFX = audioClip;
				}
			}
		}

		private static async Task<AudioClip?> LoadAudioClip(string clipName)
		{
			string fullPath = GetAssemblyFullPath(clipName);
			UnityWebRequest audioClipReq = UnityWebRequestMultimedia.GetAudioClip(fullPath, (AudioType)20);
			await (AsyncOperation)(object)audioClipReq.SendWebRequest();
			if (audioClipReq.error != null)
			{
				logger.LogError((object)audioClipReq.error);
				logger.LogError((object)"Failed to load audio clip for LethalClunk, sound will not be replaced");
				return null;
			}
			AudioClip audioClip = DownloadHandlerAudioClip.GetContent(audioClipReq);
			((Object)audioClip).name = Path.GetFileName(fullPath);
			return audioClip;
		}

		private static string GetAssemblyFullPath(string? additionalPath)
		{
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			string path = ((additionalPath != null) ? Path.Combine(directoryName, ".\\" + additionalPath) : directoryName);
			return Path.GetFullPath(path);
		}
	}
}

BepInEx/plugins/Sligili-More_Emotes/MoreEmotes1.3.3.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreEmotes.Patch;
using MoreEmotes.Scripts;
using RuntimeNetcodeRPCValidator;
using TMPro;
using Tools;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tools
{
	public class Ref
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

		public static object Method(object instance, string methodName, params object[] args)
		{
			MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(instance, args);
			}
			return null;
		}
	}
	public class D : MonoBehaviour
	{
		public static bool Debug;

		public static void L(string msg)
		{
			if (Debug)
			{
				Debug.Log((object)msg);
			}
		}

		public static void W(string msg)
		{
			if (Debug)
			{
				Debug.LogWarning((object)msg);
			}
		}
	}
}
namespace MoreEmotes
{
	[BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.3.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MoreEmotesInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private NetcodeValidator netcodeValidator;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<string> config_KeyWheel_c;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<bool> config_UseConfigFile;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private ConfigEntry<string> config_KeyEmote9;

		private ConfigEntry<string> config_KeyEmote10;

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			LoadAssetBundles();
			LoadAssets();
			ConfigFile();
			SearchForIncompatibleMods();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
			netcodeValidator = new NetcodeValidator("MoreEmotes");
			netcodeValidator.PatchAll();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SignEmoteText, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SyncAnimatorToOthers, PlayerControllerB>();
		}

		private void LoadAssetBundles()
		{
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle");
			string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle");
			try
			{
				EmotePatch.AnimationsBundle = AssetBundle.LoadFromFile(text);
				EmotePatch.AnimatorBundle = AssetBundle.LoadFromFile(text2);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load AssetBundles. Make sure \"animatorsbundle\" and \"animationsbundle\" are inside the MoreEmotes folder.\nError: " + ex.Message));
			}
		}

		private void LoadAssets()
		{
			string path = "Assets/MoreEmotes";
			EmotePatch.local = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarig.controller"));
			EmotePatch.others = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarigOtherPlayers.controller"));
			MoreEmotesEvents.ClapSounds[0] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote1.wav"));
			MoreEmotesEvents.ClapSounds[1] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote2.wav"));
			EmotePatch.SettingsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesPanel.prefab"));
			EmotePatch.ButtonPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesButton.prefab"));
			EmotePatch.LegsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/plegs.prefab"));
			EmotePatch.SignPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/Sign.prefab"));
			EmotePatch.SignUIPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/SignTextUI.prefab"));
			EmotePatch.WheelPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
		}

		private void ConfigFile()
		{
			EmotePatch.ConfigFile_Keybinds = new string[32];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind = config_KeyWheel.Value;
			config_KeyWheel_c = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL (Controller)", "Key", "leftshoulder", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind_controller = config_KeyWheel_c.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.ConfigFile_InventoryCheck = config_InventoryCheck.Value;
			config_UseConfigFile = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "ConfigFile", false, "Ignores all in-game saved settings and instead uses the config file");
			EmotePatch.UseConfigFile = config_UseConfigFile.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
			config_KeyEmote9 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Prisyadka", "9", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[8] = config_KeyEmote9.Value.Replace(" ", "");
			config_KeyEmote10 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Sign", "0", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[9] = config_KeyEmote10.Value.Replace(" ", "");
		}

		private void SearchForIncompatibleMods()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				BepInPlugin metadata = pluginInfo.Value.Metadata;
				if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades", StringComparison.OrdinalIgnoreCase) || metadata.GUID.Equals("Stoneman.LethalProgression", StringComparison.OrdinalIgnoreCase))
				{
					EmotePatch.IncompatibleStuff = true;
					break;
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string GUID = "MoreEmotes";

		public const string NAME = "MoreEmotes-Sligili";

		public const string VER = "1.3.3";
	}
}
namespace MoreEmotes.Patch
{
	public enum Emotes
	{
		D_Sign = 1010,
		D_Clap = 1004,
		D_Middle_Finger = 1003,
		Dance = 1,
		Point = 2,
		Middle_Finger = 3,
		Clap = 4,
		Shy = 5,
		The_Griddy = 6,
		Twerk = 7,
		Salute = 8,
		Prisyadka = 9,
		Sign = 10
	}
	public class EmotePatch
	{
		public static AssetBundle AnimationsBundle;

		public static AssetBundle AnimatorBundle;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		public static bool UseConfigFile;

		public static string[] ConfigFile_Keybinds;

		public static string ConfigFile_WheelKeybind;

		public static string ConfigFile_WheelKeybind_controller;

		public static bool ConfigFile_InventoryCheck;

		public static string EmoteWheelKeyboard;

		public static string EmoteWheelController;

		public static bool IncompatibleStuff;

		private static int s_currentEmoteID = 0;

		private static float s_defaultPlayerSpeed;

		private static bool[] s_wasPerformingEmote = new bool[32];

		public static bool IsEmoteWheelOpen;

		private static bool s_isPlayerFirstFrame;

		private static bool s_isFirstTimeOnMenu;

		private static bool s_isPlayerSpawning;

		public const int AlternateEmoteIDOffset = 1000;

		private static int[] s_doubleEmotesIDS = new int[2] { 3, 4 };

		public static bool LocalArmsSeparatedFromCamera;

		private static Transform s_freeArmsTarget;

		private static Transform s_lockedArmsTarget;

		private static CallbackContext emptyContext;

		public static GameObject ButtonPrefab;

		public static GameObject SettingsPrefab;

		public static GameObject LegsPrefab;

		public static GameObject SignPrefab;

		public static GameObject SignUIPrefab;

		public static GameObject WheelPrefab;

		private static GameObject s_localPlayerLevelBadge;

		private static GameObject s_localPlayerBetaBadge;

		private static Transform s_legsMesh;

		private static EmoteWheel s_selectionWheel;

		private static SignUI s_customSignInputField;

		private static SyncAnimatorToOthers s_syncAnimator;

		private static int _AlternateEmoteIDOffset => 1000;

		private static void InstantiateSettingsMenu(Transform container)
		{
			RebindButton.ConfigFile_Keybinds = ConfigFile_Keybinds;
			if (!PlayerPrefs.HasKey("InvCheck") || UseConfigFile)
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ToggleButton.s_InventoryCheck = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
			SetupUI.UseConfigFile = UseConfigFile;
			SetupUI.InventoryCheck = ToggleButton.s_InventoryCheck;
			GameObject gameObject = ((Component)((Component)container).transform.Find("SettingsPanel")).gameObject;
			Object.Instantiate<GameObject>(ButtonPrefab, gameObject.transform).transform.SetSiblingIndex(7);
			Object.Instantiate<GameObject>(SettingsPrefab, gameObject.transform);
			gameObject.AddComponent<SetupUI>();
		}

		private static void CheckEmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			Emotes emotes = (Emotes)emoteID;
			string text = emotes.ToString();
			bool flag;
			if (UseConfigFile)
			{
				flag = ConfigFile_InventoryCheck;
				keyBind = ConfigFile_Keybinds[emoteID - 1];
			}
			else
			{
				flag = PlayerPrefs.GetInt("InvCheck") == 1;
				if (PlayerPrefs.HasKey(text))
				{
					keyBind = PlayerPrefs.GetString(text);
				}
				else
				{
					PlayerPrefs.SetString(text, keyBind);
				}
			}
			if (!keyBind.Equals(string.Empty) && InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && (!player.isHoldingObject || !needsEmptyHands || !flag))
			{
				player.PerformEmote(emptyContext, emoteID);
			}
		}

		private static void CheckWheelInput(string keybind, string controller, PlayerControllerB player)
		{
			//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_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			bool flag2 = false;
			if (Gamepad.all.Count != 0 && !controller.Equals(string.Empty))
			{
				flag = InputControlExtensions.IsPressed(((InputControl)Gamepad.current)[controller], 0f);
			}
			if (keybind != string.Empty)
			{
				flag2 = InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keybind], 0f) && !((ButtonControl)Keyboard.current[(Key)55]).wasPressedThisFrame;
			}
			bool flag3 = flag || flag2;
			if (flag3 && !IsEmoteWheelOpen && !player.isPlayerDead && !player.inTerminalMenu && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen)
			{
				IsEmoteWheelOpen = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
				player.disableLookInput = true;
			}
			else
			{
				if (!IsEmoteWheelOpen || (flag3 && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen))
				{
					return;
				}
				int selectedEmoteID = s_selectionWheel.SelectedEmoteID;
				if (!player.quickMenuManager.isMenuOpen && !s_customSignInputField.IsSignUIOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (!player.isPlayerDead && !player.quickMenuManager.isMenuOpen)
				{
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !ConfigFile_InventoryCheck)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
					else if (!player.isHoldingObject)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
				}
				if (!s_customSignInputField.IsSignUIOpen)
				{
					player.disableLookInput = false;
				}
				IsEmoteWheelOpen = false;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
			}
		}

		private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB player)
		{
			s_isPlayerFirstFrame = false;
			TurnControllerIntoAnOverrideController(player.playerBodyAnimator.runtimeAnimatorController);
			s_syncAnimator = ((Component)player).GetComponent<SyncAnimatorToOthers>();
			s_customSignInputField.Player = player;
			s_freeArmsTarget = Object.Instantiate<Transform>(player.localArmsRotationTarget, player.localArmsRotationTarget.parent.parent);
			s_lockedArmsTarget = player.localArmsRotationTarget;
			Transform val = ((Component)player).transform.Find("ScavengerModel").Find("metarig").Find("spine")
				.Find("spine.001")
				.Find("spine.002")
				.Find("spine.003");
			s_localPlayerLevelBadge = ((Component)val.Find("LevelSticker")).gameObject;
			s_localPlayerBetaBadge = ((Component)val.Find("BetaBadge")).gameObject;
			player.SpawnPlayerAnimation();
		}

		private static void SpawnSign(PlayerControllerB player)
		{
			//IL_005e: 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)
			GameObject val = Object.Instantiate<GameObject>(SignPrefab, ((Component)((Component)((Component)player).transform.Find("ScavengerModel")).transform.Find("metarig")).transform);
			val.transform.SetSiblingIndex(6);
			((Object)val).name = "Sign";
			val.transform.localPosition = new Vector3(0.029f, -0.45f, 1.3217f);
			val.transform.localRotation = Quaternion.Euler(65.556f, 180f, 180f);
		}

		private static void SpawnLegs(PlayerControllerB player)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(LegsPrefab, ((Component)((Component)player.playerBodyAnimator).transform.parent).transform);
			s_legsMesh = val.transform.Find("Mesh");
			((Component)s_legsMesh).transform.parent = ((Component)player.playerBodyAnimator).transform.parent;
			((Object)s_legsMesh).name = "LEGS";
			GameObject gameObject = ((Component)val.transform.Find("Armature")).gameObject;
			gameObject.transform.parent = ((Component)player.playerBodyAnimator).transform;
			((Object)gameObject).name = "FistPersonLegs";
			gameObject.transform.position = new Vector3(0f, 0.197f, 0f);
			gameObject.transform.localScale = new Vector3(13.99568f, 13.99568f, 13.99568f);
			Object.Destroy((Object)(object)val);
		}

		private static void ResetIKWeights(PlayerControllerB player)
		{
			Transform val = ((Component)player.playerBodyAnimator).transform.Find("Rig 1");
			ChainIKConstraint component = ((Component)val.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component2 = ((Component)val.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			TwoBoneIKConstraint component3 = ((Component)val.Find("RightLeg")).GetComponent<TwoBoneIKConstraint>();
			TwoBoneIKConstraint component4 = ((Component)val.Find("LeftLeg")).GetComponent<TwoBoneIKConstraint>();
			Transform val2 = ((Component)player.playerBodyAnimator).transform.Find("ScavengerModelArmsOnly").Find("metarig").Find("spine.003")
				.Find("RigArms");
			ChainIKConstraint component5 = ((Component)val2.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component6 = ((Component)val2.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component2).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)component4).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component5).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component6).weight = 1f;
		}

		private static void UpdateLegsMaterial(PlayerControllerB player)
		{
			((Renderer)((Component)s_legsMesh).GetComponent<SkinnedMeshRenderer>()).material = ((Renderer)((Component)((Component)((Component)player.playerBodyAnimator).transform.parent).transform.Find("LOD1")).gameObject.GetComponent<SkinnedMeshRenderer>()).material;
		}

		private static void TogglePlayerBadges(bool enabled)
		{
			if ((Object)(object)s_localPlayerBetaBadge != (Object)null)
			{
				((Renderer)s_localPlayerBetaBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			if ((Object)(object)s_localPlayerLevelBadge != (Object)null)
			{
				((Renderer)s_localPlayerLevelBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			else
			{
				Debug.LogError((object)"[MoreEmotes-Sligili] Couldn't find the level badge");
			}
		}

		private static bool CheckIfTooManyEmotesIsPlaying(PlayerControllerB player)
		{
			//IL_000a: 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)
			Animator playerBodyAnimator = player.playerBodyAnimator;
			AnimatorStateInfo currentAnimatorStateInfo = playerBodyAnimator.GetCurrentAnimatorStateInfo(1);
			return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Dance1") && player.performingEmote && GetAnimatorEmoteClipName(playerBodyAnimator) != "Dance1";
		}

		private static string GetAnimatorEmoteClipName(Animator animator)
		{
			AnimatorClipInfo[] currentAnimatorClipInfo = animator.GetCurrentAnimatorClipInfo(1);
			return ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name;
		}

		private static void TurnControllerIntoAnOverrideController(RuntimeAnimatorController controller)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!(controller is AnimatorOverrideController))
			{
				controller = (RuntimeAnimatorController)new AnimatorOverrideController(controller);
			}
		}

		public static void UpdateWheelKeybinds()
		{
			if (UseConfigFile)
			{
				EmoteWheelKeyboard = ConfigFile_WheelKeybind;
				EmoteWheelController = ConfigFile_WheelKeybind_controller;
				return;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel_c"))
			{
				PlayerPrefs.SetString("Emote_Wheel_c", ConfigFile_WheelKeybind_controller);
			}
			EmoteWheelController = PlayerPrefs.GetString("Emote_Wheel_c");
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", ConfigFile_WheelKeybind);
			}
			EmoteWheelKeyboard = PlayerPrefs.GetString("Emote_Wheel");
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ConfigFile_InventoryCheck = PlayerPrefs.GetInt("InvCheck") == 1;
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			D.Debug = true;
			try
			{
				InstantiateSettingsMenu(((Component)((Component)__instance).transform.parent).transform.Find("MenuContainer"));
			}
			catch (Exception ex)
			{
				if (!s_isFirstTimeOnMenu)
				{
					s_isFirstTimeOnMenu = true;
				}
				else
				{
					Debug.LogError((object)(ex.Message + "\n[MoreEmotes-Sligili] Couldn't find MenuContainer"));
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		private static void AwakePost(RoundManager __instance)
		{
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			UpdateWheelKeybinds();
			GameObject gameObject = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
			InstantiateSettingsMenu(gameObject.transform.Find("QuickMenu"));
			s_selectionWheel = Object.Instantiate<GameObject>(WheelPrefab, gameObject.transform).AddComponent<EmoteWheel>();
			s_customSignInputField = Object.Instantiate<GameObject>(SignUIPrefab, gameObject.transform).AddComponent<SignUI>();
			EmoteWheel.Keybinds = new string[ConfigFile_Keybinds.Length + 1];
			EmoteWheel.Keybinds = ConfigFile_Keybinds;
			s_isPlayerFirstFrame = true;
		}

		[HarmonyPatch(typeof(HUDManager), "EnableChat_performed")]
		[HarmonyPrefix]
		private static bool OpenChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
		[HarmonyPrefix]
		private static bool SubmitChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject.AddComponent<MoreEmotesEvents>().Player = __instance;
			s_defaultPlayerSpeed = __instance.movementSpeed;
			((Component)__instance).gameObject.AddComponent<CustomAnimationObjects>();
			SpawnSign(__instance);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				TurnControllerIntoAnOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				if (s_isPlayerFirstFrame)
				{
					SpawnLegs(__instance);
				}
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
				if (s_isPlayerFirstFrame)
				{
					OnFirstLocalPlayerFrameWithNewAnimator(__instance);
				}
				if (s_isPlayerSpawning)
				{
					__instance.SpawnPlayerAnimation();
					s_isPlayerSpawning = false;
				}
			}
			if (!IncompatibleStuff)
			{
				if ((bool)Ref.Method(__instance, "CheckConditionsForEmote") && __instance.performingEmote)
				{
					switch (s_currentEmoteID)
					{
					case 6:
						__instance.movementSpeed = s_defaultPlayerSpeed / 2f;
						break;
					case 9:
						__instance.movementSpeed = s_defaultPlayerSpeed / 3f;
						break;
					}
				}
				else
				{
					__instance.movementSpeed = s_defaultPlayerSpeed;
				}
			}
			__instance.localArmsRotationTarget = (LocalArmsSeparatedFromCamera ? (__instance.localArmsRotationTarget = s_freeArmsTarget) : (__instance.localArmsRotationTarget = s_lockedArmsTarget));
			CheckWheelInput(EmoteWheelKeyboard, EmoteWheelController, __instance);
			if (!__instance.quickMenuManager.isMenuOpen && !IsEmoteWheelOpen)
			{
				CheckEmoteInput(ConfigFile_Keybinds[2], needsEmptyHands: false, 3, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[3], needsEmptyHands: true, 4, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[4], needsEmptyHands: true, 5, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[5], needsEmptyHands: false, 6, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[6], needsEmptyHands: true, 7, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[7], needsEmptyHands: true, 8, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[8], needsEmptyHands: true, 9, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[9], needsEmptyHands: true, 10, __instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		private static void UpdatePrefix(PlayerControllerB __instance)
		{
			if (__instance.performingEmote)
			{
				s_wasPerformingEmote[__instance.playerClientId] = true;
			}
			if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId])
			{
				s_wasPerformingEmote[__instance.playerClientId] = false;
				ResetIKWeights(__instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
		[HarmonyPrefix]
		private static void OnLocalPlayerSpawn(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				s_isPlayerSpawning = true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool CheckConditionsPrefix(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			bool flag2 = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isWalking");
			if (s_currentEmoteID == 6 || s_currentEmoteID == 9)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			if (s_currentEmoteID == 10 || s_currentEmoteID == 1010)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && !flag2 && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static bool PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID < 0 || CheckIfTooManyEmotesIsPlaying(__instance)) && emoteID > 2)
			{
				return false;
			}
			if ((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer)
			{
				return false;
			}
			if (s_customSignInputField.IsSignUIOpen && emoteID != 1010)
			{
				return false;
			}
			if (emoteID > 0 && emoteID < 3 && !IsEmoteWheelOpen && !((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			int[] array = s_doubleEmotesIDS;
			foreach (int num in array)
			{
				int num2 = num + _AlternateEmoteIDOffset;
				bool flag = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
				if (emoteID == num && s_currentEmoteID == emoteID && __instance.performingEmote && (!__instance.isHoldingObject || !flag))
				{
					if (emoteID == num)
					{
						emoteID += _AlternateEmoteIDOffset;
					}
					else
					{
						emoteID -= 1000;
					}
				}
			}
			if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote)
			{
				ResetIKWeights(__instance);
			}
			if (!(bool)Ref.Method(__instance, "CheckConditionsForEmote"))
			{
				return false;
			}
			if (__instance.timeSinceStartingEmote < 0.5f)
			{
				return false;
			}
			s_currentEmoteID = emoteID;
			Action action = delegate
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.performingEmote = true;
				__instance.StartPerformingEmoteServerRpc();
				s_syncAnimator.UpdateEmoteIDForOthers(emoteID);
				TogglePlayerBadges(enabled: false);
			};
			switch (emoteID)
			{
			case 9:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					UpdateLegsMaterial(__instance);
				});
				break;
			case 10:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					((Component)s_customSignInputField).gameObject.SetActive(true);
				});
				break;
			}
			action();
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "StopPerformingEmoteServerRpc")]
		[HarmonyPostfix]
		private static void StopPerformingEmoteServerPrefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				__instance.playerBodyAnimator.SetInteger("emoteNumber", 0);
			}
			TogglePlayerBadges(enabled: true);
			s_syncAnimator.UpdateEmoteIDForOthers(0);
			s_currentEmoteID = 0;
		}
	}
}
namespace MoreEmotes.Scripts
{
	public class MoreEmotesEvents : MonoBehaviour
	{
		private Animator _playerAnimator;

		private AudioSource _playerAudioSource;

		public static AudioClip[] ClapSounds = (AudioClip[])(object)new AudioClip[2];

		public PlayerControllerB Player;

		private void Start()
		{
			_playerAnimator = ((Component)this).GetComponent<Animator>();
			_playerAudioSource = Player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if (!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 4)
				{
					bool flag = Player.isInHangarShipRoom && Player.playersManager.hangarDoorsClosed;
					RoundManager.Instance.PlayAudibleNoise(((Component)Player).transform.position, 22f, 0.6f, 0, flag, 6);
					_playerAudioSource.pitch = Random.Range(0.59f, 0.79f);
					_playerAudioSource.PlayOneShot(ClapSounds[Random.Range(0, ClapSounds.Length)]);
				}
			}
		}

		public void PlayFootstepSound()
		{
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if ((!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 6 || currentEmoteID == 8 || currentEmoteID == 9) && ((Vector2)(ref Player.moveInputVector)).sqrMagnitude == 0f)
				{
					Player.PlayFootstepLocal();
					Player.PlayFootstepServer();
				}
			}
		}

		private int GetCurrentEmoteID()
		{
			int num = _playerAnimator.GetInteger("emoteNumber");
			if (num >= 1000)
			{
				num -= 1000;
			}
			return num;
		}
	}
	public class SignEmoteText : NetworkBehaviour
	{
		private PlayerControllerB _playerInstance;

		private TextMeshPro _signModelText;

		public string Text => ((TMP_Text)_signModelText).text;

		private void Start()
		{
			_playerInstance = ((Component)this).GetComponent<PlayerControllerB>();
			_signModelText = ((Component)((Component)_playerInstance).transform.Find("ScavengerModel").Find("metarig").Find("Sign")
				.Find("Text")).GetComponent<TextMeshPro>();
		}

		public void UpdateSignText(string newText)
		{
			if (((NetworkBehaviour)_playerInstance).IsOwner && _playerInstance.isPlayerControlled)
			{
				UpdateSignTextServerRpc(newText);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateSignTextServerRpc(string newText)
		{
			UpdateSignTextClientRpc(newText);
		}

		[ClientRpc]
		private void UpdateSignTextClientRpc(string newText)
		{
			((TMP_Text)_signModelText).text = newText;
		}
	}
	public class EmoteWheel : MonoBehaviour
	{
		private RectTransform _graphics_selectedBlock;

		private RectTransform _graphics_selectionArrow;

		private Text _graphics_emoteInformation;

		private Text _graphics_pageInformation;

		private int _blocksNumber = 8;

		private int _selectedBlock = 1;

		private float _changePageCooldown = 0.1f;

		private float _selectionArrowLerpSpeed = 30f;

		private float _angle;

		private GameObject[] _pages;

		public float WheelMovementDeadzone = 3.3f;

		public float WheelMovementDeadzoneController = 0.7f;

		public static string[] Keybinds;

		private Vector2 _wheelCenter;

		private Vector2 _lastMouseCoords;

		public int SelectedPageNumber { get; private set; }

		public int SelectedEmoteID { get; private set; }

		public bool IsUsingController { get; private set; }

		private void Awake()
		{
			GetVanillaKeybinds();
			FindGraphics();
			FindPages(((Component)this).gameObject.transform.Find("FunctionalContent"));
			UpdatePageInfo();
		}

		private void OnEnable()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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)
			_wheelCenter = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			Mouse.current.WarpCursorPosition(_wheelCenter);
		}

		private void GetVanillaKeybinds()
		{
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)" MoreEmotes: PlayerSettingsObject is null");
				return;
			}
			Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
		}

		private void FindGraphics()
		{
			_graphics_selectionArrow = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("SelectionArrow")).gameObject.GetComponent<RectTransform>();
			_graphics_selectedBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			_graphics_emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			_graphics_pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
		}

		private void FindPages(Transform contentParent)
		{
			_pages = (GameObject[])(object)new GameObject[((Component)contentParent).transform.childCount];
			_graphics_pageInformation.text = "< Page " + (SelectedPageNumber + 1) + "/" + _pages.Length + " >";
			for (int i = 0; i < ((Component)contentParent).transform.childCount; i++)
			{
				_pages[i] = ((Component)((Component)contentParent).transform.GetChild(i)).gameObject;
			}
		}

		private void Update()
		{
			ControllerInput();
			if (!IsUsingController)
			{
				MouseInput();
			}
			Cursor.visible = !IsUsingController;
			UpdateSelectionArrow();
			PageSelection();
			SelectedEmoteID = _selectedBlock + Mathf.RoundToInt((float)(_blocksNumber / 4)) + _blocksNumber * SelectedPageNumber;
			UpdateEmoteInfo();
		}

		private unsafe void ControllerInput()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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)
			if (Gamepad.all.Count == 0)
			{
				IsUsingController = false;
				return;
			}
			float num = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).x).ReadUnprocessedValue();
			float num2 = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).y).ReadUnprocessedValue();
			if (Mathf.Abs(num) < WheelMovementDeadzoneController && Mathf.Abs(num2) < WheelMovementDeadzoneController)
			{
				if (System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value) != _lastMouseCoords)
				{
					IsUsingController = false;
				}
			}
			else
			{
				IsUsingController = true;
				_lastMouseCoords = System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value);
				WheelSelection(Vector2.zero, num, num2);
			}
		}

		private void MouseInput()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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)
			if (!(Vector2.Distance(_wheelCenter, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < WheelMovementDeadzone))
			{
				WheelSelection(_wheelCenter, ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue(), ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue());
			}
		}

		private void WheelSelection(Vector2 origin, float xAxisValue, float yAxisValue)
		{
			//IL_0002: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			bool flag = xAxisValue > origin.x;
			bool flag2 = yAxisValue > origin.y;
			int num = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
			float num2 = (yAxisValue - origin.y) / (xAxisValue - origin.x);
			float num3 = 180 * (num - ((num <= 2) ? 1 : 2));
			_angle = Mathf.Atan(num2) * (180f / (float)Math.PI) + num3;
			if (_angle == 90f)
			{
				_angle = 270f;
			}
			else if (_angle == 270f)
			{
				_angle = 90f;
			}
			float num4 = 360 / _blocksNumber;
			_selectedBlock = Mathf.RoundToInt((_angle - num4 * 1.5f) / num4);
			((Transform)_graphics_selectedBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num4 * (float)_selectedBlock);
		}

		private void PageSelection()
		{
			UpdatePageInfo();
			if (_changePageCooldown > 0f)
			{
				_changePageCooldown -= Time.deltaTime;
				return;
			}
			int num;
			if (IsUsingController)
			{
				if (!Gamepad.current.dpad.left.isPressed && !Gamepad.current.dpad.right.isPressed)
				{
					return;
				}
				num = (Gamepad.current.dpad.left.isPressed ? 1 : (-1));
			}
			else
			{
				if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() == 0f)
				{
					return;
				}
				num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
			}
			GameObject[] pages = _pages;
			foreach (GameObject val in pages)
			{
				val.SetActive(false);
			}
			SelectedPageNumber = (SelectedPageNumber + num + _pages.Length) % _pages.Length;
			_pages[SelectedPageNumber].SetActive(true);
			_changePageCooldown = ((!IsUsingController) ? 0.1f : 0.3f);
		}

		private void UpdatePageInfo()
		{
			_graphics_pageInformation.text = $"<color=#fe6b02><</color> Page {SelectedPageNumber + 1}/{_pages.Length} <color=#fe6b02>></color>";
		}

		private void UpdateEmoteInfo()
		{
			string text = ((SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
			int num = 0;
			foreach (Emotes value in Enum.GetValues(typeof(Emotes)))
			{
				if (value >= Emotes.Dance && value < (Emotes)64)
				{
					num++;
				}
			}
			string text2 = ((SelectedEmoteID > num) ? "EMPTY" : ((Emotes)SelectedEmoteID).ToString().Replace("_", " "));
			if (SelectedEmoteID > 2 && SelectedEmoteID <= Keybinds.Length)
			{
				if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
				{
					PlayerPrefs.SetString(text2.Replace(" ", "_"), (SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
				}
				else
				{
					text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
				}
			}
			text = "<size=120>[" + text + "]</size>";
			_graphics_emoteInformation.text = text2 + "\n" + text.ToUpper();
		}

		private void UpdateSelectionArrow()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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)
			//IL_003e: 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)
			float num = 360 / _blocksNumber;
			Quaternion val = Quaternion.Euler(0f, 0f, _angle - num * 2f);
			((Transform)_graphics_selectionArrow).localRotation = Quaternion.Lerp(((Transform)_graphics_selectionArrow).localRotation, val, Time.deltaTime * _selectionArrowLerpSpeed);
		}
	}
	public class RebindButton : MonoBehaviour
	{
		public static string[] ConfigFile_Keybinds;

		private string _defaultKey;

		private string _playerPrefsString;

		private Transform _waitingForInput;

		private Text _keyInfo;

		public bool IsControllerButton { get; private set; } = false;


		private void Start()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			IsControllerButton = GetControllerFlag();
			_playerPrefsString = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_") + (IsControllerButton ? "_c" : "");
			_defaultKey = GetDefaultKey(text);
			FindComponents();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(_playerPrefsString))
			{
				PlayerPrefs.SetString(_playerPrefsString, _defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(_playerPrefsString));
		}

		private string GetDefaultKey(string emoteName)
		{
			if (Enum.TryParse<Emotes>(emoteName.Replace(" ", "_"), out var result))
			{
				return ConfigFile_Keybinds[(int)(result - 1)];
			}
			return IsControllerButton ? "leftshoulder" : "V";
		}

		private bool GetControllerFlag()
		{
			Transform val = ((Component)this).gameObject.transform.Find("Description").Find("Subtext");
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Text val2 = default(Text);
			if (((Component)val).TryGetComponent<Text>(ref val2))
			{
				return val2.text.Equals("(Controller)", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private void FindComponents()
		{
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteButton>();
			_keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			_waitingForInput = ((Component)this).transform.Find("wait");
		}

		public void SetKeybind(string key)
		{
			List<string> list = new List<string> { "up", "down", "left", "right" };
			if (list.Contains(key.ToLower()) && key.Length < 5)
			{
				key = "dpad/" + key;
			}
			PlayerPrefs.SetString(_playerPrefsString, key);
			_keyInfo.text = key.ToUpper();
			((MonoBehaviour)this).StopAllCoroutines();
			((Component)_waitingForInput).gameObject.SetActive(false);
		}

		private void GetKey()
		{
			((Component)_waitingForInput).gameObject.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame || (!((InputDevice)Gamepad.current).wasUpdatedThisFrame && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.leftStick, 0f) && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.rightStick, 0f)))
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback(((ctrl.device == Gamepad.current && IsControllerButton) || (ctrl.device == Keyboard.current && !IsControllerButton)) ? ctrl.name : _defaultKey);
				});
			}
		}
	}
	public class DeleteButton : MonoBehaviour
	{
		private void Start()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			RebindButton _rebindButton = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindButton>();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				_rebindButton.SetKeybind(string.Empty);
			});
		}
	}
	public class ToggleButton : MonoBehaviour
	{
		private Toggle _toggle;

		public static bool s_InventoryCheck;

		public string PlayerPrefsString;

		private void Start()
		{
			_toggle = ((Component)this).GetComponent<Toggle>();
			_toggle.isOn = s_InventoryCheck;
			((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(PlayerPrefsString))
			{
				SetNewValue(s_InventoryCheck);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(PlayerPrefsString, arg ? 1 : 0);
		}
	}
	public class EnableDisableButton : MonoBehaviour
	{
		public GameObject[] ToAlternateUI = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				GameObject[] toAlternateUI = ToAlternateUI;
				foreach (GameObject val in toAlternateUI)
				{
					val.SetActive((!val.activeInHierarchy) ? true : false);
				}
			});
			if (((Object)((Component)this).gameObject).name.Equals("BackButton", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}
	}
	public class SetupUI : MonoBehaviour
	{
		public static bool UseConfigFile;

		public static bool InventoryCheck;

		private void Awake()
		{
			Transform settingsUIPanel = ((Component)this).transform.Find("MoreEmotesPanel(Clone)");
			((Component)settingsUIPanel.Find("Version")).GetComponent<Text>().text = "1.3.3 - Sligili";
			SetupOpenSettingsButton();
			SetupBackButton();
			SetupRebindButtons(((Component)settingsUIPanel).transform.Find("KeybindButtons"));
			SetupRebindButtons(((Component)((Component)((Component)settingsUIPanel).transform.Find("Scroll View")).transform.Find("Viewport")).transform.Find("Content"));
			SetupInventoryCheckToggle();
			SetupUseConfigFileToggle();
			void SetupBackButton()
			{
				((Component)((Component)settingsUIPanel).transform.Find("BackButton")).gameObject.AddComponent<EnableDisableButton>();
			}
			void SetupInventoryCheckToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("Inv")).gameObject.AddComponent<ToggleButton>().PlayerPrefsString = "InvCheck";
			}
			void SetupOpenSettingsButton()
			{
				((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject.AddComponent<EnableDisableButton>();
			}
			static void SetupRebindButtons(Transform ButtonsParent)
			{
				Transform[] array = (Transform[])(object)new Transform[ButtonsParent.childCount];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = ButtonsParent.GetChild(i);
				}
				Transform[] array2 = array;
				foreach (Transform val in array2)
				{
					((Component)val.Find("Button")).gameObject.AddComponent<RebindButton>();
				}
			}
			void SetupUseConfigFileToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("cfg")).gameObject.GetComponent<Toggle>().isOn = UseConfigFile;
			}
		}

		private void Update()
		{
			EmotePatch.UpdateWheelKeybinds();
		}
	}
	public class SignUI : MonoBehaviour
	{
		public PlayerControllerB Player;

		private TMP_InputField _inputField;

		private Text _charactersLeftText;

		private TMP_Text _previewText;

		private Button _submitButton;

		private Button _cancelButton;

		public bool IsSignUIOpen;

		private void Awake()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			FindComponents();
			((UnityEvent)_submitButton.onClick).AddListener(new UnityAction(SubmitText));
			((UnityEvent)_cancelButton.onClick).AddListener((UnityAction)delegate
			{
				Close(cancelAction: true);
			});
			((UnityEvent<string>)(object)_inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string fieldText)
			{
				UpdatePreviewText(fieldText);
				UpdateCharactersLeftText();
			});
		}

		private void OnEnable()
		{
			Player.isTypingChat = true;
			IsSignUIOpen = true;
			((Selectable)_inputField).Select();
			_inputField.text = string.Empty;
			_previewText.text = "PREVIEW";
			Player.disableLookInput = true;
		}

		private void Update()
		{
			//IL_009e: 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)
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)2;
			if (!Player.performingEmote)
			{
				Close(cancelAction: true);
			}
			if (((ButtonControl)Keyboard.current[(Key)2]).wasPressedThisFrame && !((ButtonControl)Keyboard.current[(Key)51]).isPressed)
			{
				SubmitText();
			}
			if (Player.quickMenuManager.isMenuOpen || EmotePatch.IsEmoteWheelOpen || InputControlExtensions.IsPressed(((InputControl)Mouse.current)["rightButton"], 0f))
			{
				Close(cancelAction: true);
			}
			if (Gamepad.all.Count != 0)
			{
				if (Gamepad.current.buttonWest.isPressed || Gamepad.current.startButton.isPressed)
				{
					SubmitText();
				}
				if (Gamepad.current.buttonEast.isPressed || Gamepad.current.selectButton.isPressed)
				{
					Close(cancelAction: true);
				}
			}
		}

		private void FindComponents()
		{
			_inputField = ((Component)((Component)this).transform.Find("InputField")).GetComponent<TMP_InputField>();
			_charactersLeftText = ((Component)((Component)this).transform.Find("CharsLeft")).GetComponent<Text>();
			_submitButton = ((Component)((Component)this).transform.Find("Submit")).GetComponent<Button>();
			_cancelButton = ((Component)((Component)this).transform.Find("Cancel")).GetComponent<Button>();
			_previewText = ((Component)((Component)((Component)this).transform.Find("Sign")).transform.Find("Text")).GetComponent<TMP_Text>();
		}

		private void UpdateCharactersLeftText()
		{
			_charactersLeftText.text = $"CHARACTERS LEFT: <color=yellow>{_inputField.characterLimit - _inputField.text.Length}</color>";
		}

		private void UpdatePreviewText(string text)
		{
			_previewText.text = text;
		}

		private void SubmitText()
		{
			//IL_007c: 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)
			if (_inputField.text.Equals(string.Empty))
			{
				Close(cancelAction: true);
				return;
			}
			D.L("Submitted " + _inputField.text + " to server");
			((Component)Player).GetComponent<SignEmoteText>().UpdateSignText(_inputField.text);
			float num = 0.5f;
			if (Player.timeSinceStartingEmote > num)
			{
				Player.PerformEmote(default(CallbackContext), 1010);
			}
			Close(cancelAction: false);
		}

		private void Close(bool cancelAction)
		{
			Player.isTypingChat = false;
			IsSignUIOpen = false;
			if (cancelAction)
			{
				Player.performingEmote = false;
				Player.StopPerformingEmoteServerRpc();
			}
			if (!Player.quickMenuManager.isMenuOpen)
			{
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
			}
			Player.disableLookInput = false;
			((Component)this).gameObject.SetActive(false);
		}
	}
	public class SyncAnimatorToOthers : NetworkBehaviour
	{
		private PlayerControllerB _player;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		public void UpdateEmoteIDForOthers(int newID)
		{
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				UpdateCurrentEmoteIDServerRpc(newID);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateCurrentEmoteIDServerRpc(int newID)
		{
			UpdateCurrentEmoteIDClientRpc(newID);
		}

		[ClientRpc]
		private void UpdateCurrentEmoteIDClientRpc(int newID)
		{
			if (!((NetworkBehaviour)_player).IsOwner)
			{
				_player.playerBodyAnimator.SetInteger("emoteNumber", newID);
			}
		}
	}
	public class CustomAnimationObjects : MonoBehaviour
	{
		private PlayerControllerB _player;

		private MeshRenderer _sign;

		private GameObject _signText;

		private SkinnedMeshRenderer _legs;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		private void Update()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sign == (Object)null || (Object)(object)_signText == (Object)null)
			{
				FindSign();
				return;
			}
			((Component)_sign).transform.localPosition = ((Component)_sign).transform.parent.Find("spine").localPosition;
			if ((Object)(object)_legs == (Object)null && ((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				FindLegs();
				return;
			}
			DisableEverything();
			if (!_player.performingEmote)
			{
				return;
			}
			switch (_player.playerBodyAnimator.GetInteger("emoteNumber"))
			{
			case 10:
			case 1010:
				((Renderer)_sign).enabled = true;
				if (!_signText.activeSelf)
				{
					_signText.SetActive(true);
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			case 9:
				if ((Object)(object)_legs != (Object)null)
				{
					((Renderer)_legs).enabled = true;
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			}
		}

		private void DisableEverything()
		{
			if ((Object)(object)_legs != (Object)null)
			{
				((Renderer)_legs).enabled = false;
			}
			((Renderer)_sign).enabled = false;
			if (_signText.activeSelf)
			{
				_signText.SetActive(false);
			}
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				EmotePatch.LocalArmsSeparatedFromCamera = false;
			}
		}

		private void FindSign()
		{
			_sign = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("metarig").Find("Sign")).GetComponent<MeshRenderer>();
			_signText = ((Component)((Component)_sign).transform.Find("Text")).gameObject;
		}

		private void FindLegs()
		{
			_legs = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("LEGS")).GetComponent<SkinnedMeshRenderer>();
		}
	}
}

BepInEx/plugins/Steven-Custom_Boombox_Music/CustomBoomboxTracks.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomBoomboxTracks.Configuration;
using CustomBoomboxTracks.Managers;
using CustomBoomboxTracks.Utilities;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;

[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("CustomBoomboxTracks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
[assembly: AssemblyProduct("CustomBoomboxTracks")]
[assembly: AssemblyTitle("CustomBoomboxTracks")]
[assembly: AssemblyVersion("1.4.0.0")]
namespace CustomBoomboxTracks
{
	[BepInPlugin("com.steven.lethalcompany.boomboxmusic", "Custom Boombox Music", "1.4.0")]
	public class BoomboxPlugin : BaseUnityPlugin
	{
		private const string GUID = "com.steven.lethalcompany.boomboxmusic";

		private const string NAME = "Custom Boombox Music";

		private const string VERSION = "1.4.0";

		private static BoomboxPlugin Instance;

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			LogInfo("Loading...");
			AudioManager.GenerateFolders();
			Config.Init();
			new Harmony("com.steven.lethalcompany.boomboxmusic").PatchAll();
			LogInfo("Loading Complete!");
		}

		internal static void LogDebug(string message)
		{
			Instance.Log(message, (LogLevel)32);
		}

		internal static void LogInfo(string message)
		{
			Instance.Log(message, (LogLevel)16);
		}

		internal static void LogWarning(string message)
		{
			Instance.Log(message, (LogLevel)4);
		}

		internal static void LogError(string message)
		{
			Instance.Log(message, (LogLevel)2);
		}

		internal static void LogError(Exception ex)
		{
			Instance.Log(ex.Message + "\n" + ex.StackTrace, (LogLevel)2);
		}

		private void Log(string message, LogLevel logLevel)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.Log(logLevel, (object)message);
		}
	}
}
namespace CustomBoomboxTracks.Utilities
{
	public class SharedCoroutineStarter : MonoBehaviour
	{
		private static SharedCoroutineStarter _instance;

		public static Coroutine StartCoroutine(IEnumerator routine)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = new GameObject("Shared Coroutine Starter").AddComponent<SharedCoroutineStarter>();
				Object.DontDestroyOnLoad((Object)(object)_instance);
			}
			return ((MonoBehaviour)_instance).StartCoroutine(routine);
		}
	}
}
namespace CustomBoomboxTracks.Patches
{
	[HarmonyPatch(typeof(BoomboxItem), "PocketItem")]
	internal class BoomboxItem_PocketItem
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			bool flag = false;
			for (int i = 0; i < list.Count; i++)
			{
				if (!flag)
				{
					if (list[i].opcode == OpCodes.Call)
					{
						flag = true;
					}
					continue;
				}
				if (list[i].opcode == OpCodes.Ret)
				{
					break;
				}
				list[i].opcode = OpCodes.Nop;
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(BoomboxItem), "Start")]
	internal class BoomboxItem_Start
	{
		private static void Postfix(BoomboxItem __instance)
		{
			if (AudioManager.FinishedLoading)
			{
				AudioManager.ApplyClips(__instance);
				return;
			}
			AudioManager.OnAllSongsLoaded += delegate
			{
				AudioManager.ApplyClips(__instance);
			};
		}
	}
	[HarmonyPatch(typeof(BoomboxItem), "StartMusic")]
	internal class BoomboxItem_StartMusic
	{
		private static void Postfix(BoomboxItem __instance, bool startMusic)
		{
			if (startMusic)
			{
				BoomboxPlugin.LogInfo("Playing " + ((Object)__instance.boomboxAudio.clip).name);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Awake")]
	internal class StartOfRound_Awake
	{
		private static void Prefix()
		{
			AudioManager.Load();
		}
	}
}
namespace CustomBoomboxTracks.Managers
{
	internal static class AudioManager
	{
		private static string[] allSongPaths;

		private static List<AudioClip> clips = new List<AudioClip>();

		private static bool firstRun = true;

		private static bool finishedLoading = false;

		private static readonly string directory = Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music");

		public static bool FinishedLoading => finishedLoading;

		public static bool HasNoSongs => allSongPaths.Length == 0;

		public static event Action OnAllSongsLoaded;

		public static void GenerateFolders()
		{
			Directory.CreateDirectory(directory);
			BoomboxPlugin.LogInfo("Created directory at " + directory);
		}

		public static void Load()
		{
			if (!firstRun)
			{
				return;
			}
			firstRun = false;
			allSongPaths = Directory.GetFiles(directory);
			if (allSongPaths.Length == 0)
			{
				BoomboxPlugin.LogWarning("No songs found!");
				return;
			}
			BoomboxPlugin.LogInfo("Preparing to load AudioClips...");
			List<Coroutine> list = new List<Coroutine>();
			string[] array = allSongPaths;
			for (int i = 0; i < array.Length; i++)
			{
				Coroutine item = SharedCoroutineStarter.StartCoroutine(LoadAudioClip(array[i]));
				list.Add(item);
			}
			SharedCoroutineStarter.StartCoroutine(WaitForAllClips(list));
		}

		private static IEnumerator LoadAudioClip(string filePath)
		{
			BoomboxPlugin.LogInfo("Loading " + filePath + "!");
			if ((int)GetAudioType(filePath) == 0)
			{
				BoomboxPlugin.LogError("Failed to load AudioClip from " + filePath + "\nUnsupported file extension!");
				yield break;
			}
			UnityWebRequest loader = UnityWebRequestMultimedia.GetAudioClip(filePath, GetAudioType(filePath));
			if (Config.StreamFromDisk)
			{
				DownloadHandler downloadHandler = loader.downloadHandler;
				((DownloadHandlerAudioClip)((downloadHandler is DownloadHandlerAudioClip) ? downloadHandler : null)).streamAudio = true;
			}
			loader.SendWebRequest();
			while (!loader.isDone)
			{
				yield return null;
			}
			if (loader.error != null)
			{
				BoomboxPlugin.LogError("Error loading clip from path: " + filePath + "\n" + loader.error);
				BoomboxPlugin.LogError(loader.error);
				yield break;
			}
			AudioClip content = DownloadHandlerAudioClip.GetContent(loader);
			if (Object.op_Implicit((Object)(object)content) && (int)content.loadState == 2)
			{
				BoomboxPlugin.LogInfo("Loaded " + filePath);
				((Object)content).name = Path.GetFileName(filePath);
				clips.Add(content);
			}
			else
			{
				BoomboxPlugin.LogError("Failed to load clip at: " + filePath + "\nThis might be due to an mismatch between the audio codec and the file extension!");
			}
		}

		private static IEnumerator WaitForAllClips(List<Coroutine> coroutines)
		{
			foreach (Coroutine coroutine in coroutines)
			{
				yield return coroutine;
			}
			clips.Sort((AudioClip first, AudioClip second) => ((Object)first).name.CompareTo(((Object)second).name));
			finishedLoading = true;
			AudioManager.OnAllSongsLoaded?.Invoke();
			AudioManager.OnAllSongsLoaded = null;
		}

		public static void ApplyClips(BoomboxItem __instance)
		{
			BoomboxPlugin.LogInfo("Applying clips!");
			if (Config.UseDefaultSongs)
			{
				__instance.musicAudios = __instance.musicAudios.Concat(clips).ToArray();
			}
			else
			{
				__instance.musicAudios = clips.ToArray();
			}
			BoomboxPlugin.LogInfo($"Total Clip Count: {__instance.musicAudios.Length}");
		}

		private static AudioType GetAudioType(string path)
		{
			string text = Path.GetExtension(path).ToLower();
			switch (text)
			{
			case ".wav":
				return (AudioType)20;
			case ".ogg":
				return (AudioType)14;
			case ".mp3":
				return (AudioType)13;
			default:
				BoomboxPlugin.LogError("Unsupported extension type: " + text);
				return (AudioType)0;
			}
		}
	}
}
namespace CustomBoomboxTracks.Configuration
{
	internal static class Config
	{
		private const string CONFIG_FILE_NAME = "boombox.cfg";

		private static ConfigFile _config;

		private static ConfigEntry<bool> _useDefaultSongs;

		private static ConfigEntry<bool> _streamAudioFromDisk;

		public static bool UseDefaultSongs
		{
			get
			{
				if (!_useDefaultSongs.Value)
				{
					return AudioManager.HasNoSongs;
				}
				return true;
			}
		}

		public static bool StreamFromDisk => _streamAudioFromDisk.Value;

		public static void Init()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			BoomboxPlugin.LogInfo("Initializing config...");
			_config = new ConfigFile(Path.Combine(Paths.ConfigPath, "boombox.cfg"), true);
			_useDefaultSongs = _config.Bind<bool>("Config", "Use Default Songs", false, "Include the default songs in the rotation.");
			_streamAudioFromDisk = _config.Bind<bool>("Config", "Stream Audio From Disk", false, "Requires less memory and takes less time to load, but prevents playing the same song twice at once.");
			BoomboxPlugin.LogInfo("Config initialized!");
		}

		private static void PrintConfig()
		{
			BoomboxPlugin.LogInfo($"Use Default Songs: {_useDefaultSongs.Value}");
			BoomboxPlugin.LogInfo($"Stream From Disk: {_streamAudioFromDisk}");
		}
	}
}

BepInEx/plugins/sunnobunno-YippeeMod/YippeeMod.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using YippeeMod.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("YippeeMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("YippeeMod")]
[assembly: AssemblyTitle("YippeeMod")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace YippeeMod
{
	[BepInPlugin("sunnobunno.YippeeMod", "Yippee tbh mod", "1.2.3")]
	public class YippeeModBase : BaseUnityPlugin
	{
		private const string modGUID = "sunnobunno.YippeeMod";

		private const string modName = "Yippee tbh mod";

		private const string modVersion = "1.2.3";

		private readonly Harmony harmony = new Harmony("sunnobunno.YippeeMod");

		private static YippeeModBase? Instance;

		internal ManualLogSource? mls;

		internal static AudioClip[]? newSFX;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("sunnobunno.YippeeMod");
			mls.LogInfo((object)"sunnobunno.YippeeMod is loading.");
			string location = ((BaseUnityPlugin)Instance).Info.Location;
			string text = "YippeeMod.dll";
			string text2 = location.TrimEnd(text.ToCharArray());
			string text3 = text2 + "yippeesound";
			AssetBundle val = AssetBundle.LoadFromFile(text3);
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load audio assets!");
				return;
			}
			newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/yippee-tbh.mp3");
			harmony.PatchAll(typeof(HoarderBugPatch));
			mls.LogInfo((object)"sunnobunno.YippeeMod is loaded. Yippee!!!");
		}
	}
}
namespace YippeeMod.Patches
{
	[HarmonyPatch(typeof(HoarderBugAI))]
	internal class HoarderBugPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void hoarderBugAudioPatch(ref AudioClip[] ___chitterSFX)
		{
			AudioClip[] newSFX = YippeeModBase.newSFX;
			___chitterSFX = newSFX;
		}
	}
}

BepInEx/plugins/Suskitech-AlwaysHearActiveWalkies/AlwaysHearWalkie.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LCAlwaysHearWalkieMod.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AlwaysHearWalkie")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.4.4.0")]
[assembly: AssemblyInformationalVersion("1.4.4+29502bb52bcbc33187ec0645d5c274b3ffd1bc79")]
[assembly: AssemblyProduct("Always Hear Active Walkies")]
[assembly: AssemblyTitle("AlwaysHearWalkie")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.4.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 BepInEx5.PluginTemplate
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AlwaysHearWalkie";

		public const string PLUGIN_NAME = "Always Hear Active Walkies";

		public const string PLUGIN_VERSION = "1.4.4";
	}
}
namespace LCAlwaysHearWalkieMod
{
	public static class PluginInfo
	{
		public const string modGUID = "suskitech.LCAlwaysHearActiveWalkie";

		public const string modName = "LC Always Hear Active Walkies";

		public const string modVersion = "1.4.4";
	}
	[BepInPlugin("suskitech.LCAlwaysHearActiveWalkie", "LC Always Hear Active Walkies", "1.4.4")]
	public class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<float> configAudibleDistance;

		public static float AudibleDistance;

		private ConfigEntry<float> configWalkieRecordingRange;

		public static float WalkieRecordingRange;

		private ConfigEntry<float> configPlayerToPlayerSpatialHearingRange;

		public static float PlayerToPlayerSpatialHearingRange;

		public static ManualLogSource Log;

		private static Plugin Instance;

		public void Awake()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configAudibleDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "AudibleDistance", 12f, "");
			AudibleDistance = configAudibleDistance.Value;
			configWalkieRecordingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "WalkieRecordingRange", 20f, "");
			WalkieRecordingRange = configWalkieRecordingRange.Value;
			configPlayerToPlayerSpatialHearingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "PlayerToPlayerSpatialHearingRange", 20f, "");
			PlayerToPlayerSpatialHearingRange = configPlayerToPlayerSpatialHearingRange.Value;
			Log = Logger.CreateLogSource("suskitech.LCAlwaysHearActiveWalkie");
			Harmony val = new Harmony("suskitech.LCAlwaysHearActiveWalkie");
			val.PatchAll(typeof(Plugin));
			val.PatchAll(typeof(PlayerControllerBPatch));
			val.PatchAll(typeof(WalkieTalkiePatch));
			Log.LogInfo((object)"\\ /");
			Log.LogInfo((object)"/|\\");
			Log.LogInfo((object)" |----|");
			Log.LogInfo((object)" |[__]| Always Hear Active Walkies");
			Log.LogInfo((object)" |.  .| Version 1.4.4 Loaded");
			Log.LogInfo((object)" |____|");
			Log.LogInfo((object)"");
			Log.LogInfo((object)("AudibleDistance: " + AudibleDistance));
			Log.LogInfo((object)("WalkieRecordingRange: " + WalkieRecordingRange));
			Log.LogInfo((object)("PlayerToPlayerSpatialHearingRange: " + PlayerToPlayerSpatialHearingRange));
		}
	}
}
namespace LCAlwaysHearWalkieMod.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		private static readonly float throttleInterval = 0.35f;

		private static float throttle = 0f;

		private static readonly float AverageDistanceToHeldWalkie = 2f;

		private static readonly float AudibleDistance = Plugin.AudibleDistance;

		private static readonly float WalkieRecordingRange = Plugin.WalkieRecordingRange;

		private static readonly float PlayerToPlayerSpatialHearingRange = Plugin.PlayerToPlayerSpatialHearingRange;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void alwaysHearWalkieTalkiesPatch(ref bool ___holdingWalkieTalkie, ref PlayerControllerB __instance)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: 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)
			throttle += Time.deltaTime;
			if (throttle < throttleInterval)
			{
				return;
			}
			throttle = 0f;
			if ((Object)(object)__instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				List<WalkieTalkie> list = new List<WalkieTalkie>();
				List<WalkieTalkie> list2 = new List<WalkieTalkie>();
				for (int i = 0; i < WalkieTalkie.allWalkieTalkies.Count; i++)
				{
					float num = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[i]).transform.position, ((Component)__instance).transform.position);
					if (num <= AudibleDistance)
					{
						if (((GrabbableObject)WalkieTalkie.allWalkieTalkies[i]).isBeingUsed)
						{
							list.Add(WalkieTalkie.allWalkieTalkies[i]);
						}
					}
					else
					{
						list2.Add(WalkieTalkie.allWalkieTalkies[i]);
					}
				}
				bool flag = list.Count > 0;
				if (flag != __instance.holdingWalkieTalkie)
				{
					___holdingWalkieTalkie = flag;
					for (int j = 0; j < list2.Count; j++)
					{
						if (j < list.Count)
						{
							list2[j].thisAudio.Stop();
						}
					}
				}
				if (!flag)
				{
					return;
				}
			}
			PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript);
			for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
			{
				PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[k];
				if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController || val2.isPlayerDead || !val2.holdingWalkieTalkie)
				{
					continue;
				}
				float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position);
				float num3 = float.MaxValue;
				float num4 = float.MaxValue;
				for (int l = 0; l < WalkieTalkie.allWalkieTalkies.Count; l++)
				{
					if (!((GrabbableObject)WalkieTalkie.allWalkieTalkies[l]).isBeingUsed)
					{
						continue;
					}
					float num5 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l].target).transform.position, ((Component)val).transform.position);
					if (num5 < num4)
					{
						num4 = num5;
					}
					if (!WalkieTalkie.allWalkieTalkies[l].speakingIntoWalkieTalkie)
					{
						float num6 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l]).transform.position, ((Component)val2).transform.position);
						if (num6 < num3)
						{
							num3 = num6;
						}
					}
				}
				float num7 = Mathf.Min(1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num3), 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num4));
				float num8 = 1f - Mathf.InverseLerp(0f, PlayerToPlayerSpatialHearingRange, num2);
				val2.voicePlayerState.Volume = Mathf.Max(num7, num8);
				if (val2.speakingToWalkieTalkie && num7 > num8)
				{
					makePlayerSoundWalkieTalkie(val2);
				}
				else
				{
					makePlayerSoundSpatial(val2);
				}
			}
			static void makePlayerSoundSpatial(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
				OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
				((Behaviour)component2).enabled = false;
				((Behaviour)component).enabled = true;
				component3.overridingLowPass = playerController.voiceMuffledByEnemy;
				currentVoiceChatAudioSource.spatialBlend = 1f;
				playerController.currentVoiceChatIngameSettings.set2D = false;
				currentVoiceChatAudioSource.bypassListenerEffects = false;
				currentVoiceChatAudioSource.bypassEffects = false;
				currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				component.lowpassResonanceQ = 1f;
			}
			static void makePlayerSoundWalkieTalkie(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource2 = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component4 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component5 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioHighPassFilter>();
				OccludeAudio component6 = ((Component)currentVoiceChatAudioSource2).GetComponent<OccludeAudio>();
				((Behaviour)component5).enabled = true;
				((Behaviour)component4).enabled = true;
				component6.overridingLowPass = true;
				currentVoiceChatAudioSource2.spatialBlend = 0f;
				playerController.currentVoiceChatIngameSettings.set2D = true;
				currentVoiceChatAudioSource2.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				currentVoiceChatAudioSource2.bypassListenerEffects = false;
				currentVoiceChatAudioSource2.bypassEffects = false;
				currentVoiceChatAudioSource2.panStereo = (GameNetworkManager.Instance.localPlayerController.isPlayerDead ? 0f : 0.4f);
				component6.lowPassOverride = 4000f;
				component4.lowpassResonanceQ = 3f;
			}
		}
	}
	[HarmonyPatch(typeof(WalkieTalkie))]
	internal class WalkieTalkiePatch
	{
		[HarmonyPatch("EnableWalkieTalkieListening")]
		[HarmonyPrefix]
		private static bool alwaysHearWalkieTalkiesEnableWalkieTalkieListeningPatch(bool enable)
		{
			if (!enable)
			{
				return false;
			}
			return true;
		}
	}
}

BepInEx/plugins/x753-Mimics/Mimics.dll

Decompiled 9 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using DunGen;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyMimics.Properties;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mimics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that adds mimics to Lethal Company")]
[assembly: AssemblyFileVersion("2.3.2.0")]
[assembly: AssemblyInformationalVersion("2.3.2")]
[assembly: AssemblyProduct("Mimics")]
[assembly: AssemblyTitle("Mimics")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.2.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>();
	}
}
namespace LethalCompanyMimics.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("LethalCompanyMimics.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] mimicdoor
		{
			get
			{
				object @object = ResourceManager.GetObject("mimicdoor", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace Mimics
{
	[BepInPlugin("x753.Mimics", "Mimics", "2.3.2")]
	public class Mimics : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class GameNetworkManagerPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch()
			{
				((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(MimicNetworkerPrefab);
			}
		}

		[HarmonyPatch(typeof(StartOfRound))]
		internal class StartOfRoundPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch(ref StartOfRound __instance)
			{
				if (((NetworkBehaviour)__instance).IsServer && (Object)(object)MimicNetworker.Instance == (Object)null)
				{
					GameObject val = Object.Instantiate<GameObject>(MimicNetworkerPrefab);
					val.GetComponent<NetworkObject>().Spawn(true);
					MimicNetworker.SpawnWeight0.Value = SpawnRates[0];
					MimicNetworker.SpawnWeight1.Value = SpawnRates[1];
					MimicNetworker.SpawnWeight2.Value = SpawnRates[2];
					MimicNetworker.SpawnWeight3.Value = SpawnRates[3];
					MimicNetworker.SpawnWeight4.Value = SpawnRates[4];
					MimicNetworker.SpawnWeightMax.Value = SpawnRates[5];
					MimicNetworker.SpawnRateDynamic.Value = DynamicSpawnRate;
				}
			}
		}

		[HarmonyPatch(typeof(Terminal))]
		internal class TerminalPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch(ref StartOfRound __instance)
			{
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Expected O, but got Unknown
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Expected O, but got Unknown
				Terminal val = Object.FindObjectOfType<Terminal>();
				if (!Object.op_Implicit((Object)(object)val.enemyFiles.Find((TerminalNode node) => node.creatureName == "Mimics")))
				{
					MimicCreatureID = val.enemyFiles.Count;
					MimicFile.creatureFileID = MimicCreatureID;
					val.enemyFiles.Add(MimicFile);
					TerminalKeyword val2 = val.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
					TerminalKeyword val3 = new TerminalKeyword
					{
						word = "mimics",
						isVerb = false,
						defaultVerb = val2
					};
					List<CompatibleNoun> list = val2.compatibleNouns.ToList();
					list.Add(new CompatibleNoun
					{
						noun = val3,
						result = MimicFile
					});
					val2.compatibleNouns = list.ToArray();
					List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
					list2.Add(val3);
					val.terminalNodes.allKeywords = list2.ToArray();
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("SetExitIDs")]
			[HarmonyPostfix]
			private static void SetExitIDsPatch(ref RoundManager __instance, Vector3 mainEntrancePosition)
			{
				//IL_0536: Unknown result type (might be due to invalid IL or missing references)
				//IL_0547: Unknown result type (might be due to invalid IL or missing references)
				//IL_054c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0551: Unknown result type (might be due to invalid IL or missing references)
				//IL_0556: Unknown result type (might be due to invalid IL or missing references)
				//IL_0235: Unknown result type (might be due to invalid IL or missing references)
				//IL_0241: 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_025a: Unknown result type (might be due to invalid IL or missing references)
				//IL_025f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0272: Unknown result type (might be due to invalid IL or missing references)
				//IL_0286: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Unknown result type (might be due to invalid IL or missing references)
				//IL_029b: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_0565: Unknown result type (might be due to invalid IL or missing references)
				//IL_056a: Unknown result type (might be due to invalid IL or missing references)
				//IL_056c: Unknown result type (might be due to invalid IL or missing references)
				//IL_056e: Unknown result type (might be due to invalid IL or missing references)
				//IL_05a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_06c0: Unknown result type (might be due to invalid IL or missing references)
				//IL_06c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_06c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_06d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_06da: Unknown result type (might be due to invalid IL or missing references)
				//IL_06de: Unknown result type (might be due to invalid IL or missing references)
				//IL_06e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_033d: Unknown result type (might be due to invalid IL or missing references)
				//IL_034e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0353: Unknown result type (might be due to invalid IL or missing references)
				//IL_0358: Unknown result type (might be due to invalid IL or missing references)
				//IL_035d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0367: Unknown result type (might be due to invalid IL or missing references)
				//IL_036c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0371: Unknown result type (might be due to invalid IL or missing references)
				//IL_0377: Unknown result type (might be due to invalid IL or missing references)
				//IL_037f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0388: Unknown result type (might be due to invalid IL or missing references)
				//IL_0392: Unknown result type (might be due to invalid IL or missing references)
				//IL_067b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0414: Unknown result type (might be due to invalid IL or missing references)
				//IL_041c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0425: Unknown result type (might be due to invalid IL or missing references)
				//IL_042f: Unknown result type (might be due to invalid IL or missing references)
				//IL_07d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_07dd: Expected O, but got Unknown
				//IL_08ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_08d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_084d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0874: Unknown result type (might be due to invalid IL or missing references)
				//IL_0987: Unknown result type (might be due to invalid IL or missing references)
				//IL_09ae: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				MimicDoor.allMimics = new List<MimicDoor>();
				int num = 0;
				Dungeon currentDungeon = __instance.dungeonGenerator.Generator.CurrentDungeon;
				if (!((Object)currentDungeon.DungeonFlow).name.StartsWith("Level1") && !((Object)currentDungeon.DungeonFlow).name.StartsWith("Level2"))
				{
					return;
				}
				int num2 = 0;
				int[] array = new int[6]
				{
					MimicNetworker.SpawnWeight0.Value,
					MimicNetworker.SpawnWeight1.Value,
					MimicNetworker.SpawnWeight2.Value,
					MimicNetworker.SpawnWeight3.Value,
					MimicNetworker.SpawnWeight4.Value,
					MimicNetworker.SpawnWeightMax.Value
				};
				int num3 = 0;
				int[] array2 = array;
				foreach (int num4 in array2)
				{
					num3 += num4;
				}
				Random random = new Random(StartOfRound.Instance.randomMapSeed + 753);
				int num5 = random.Next(0, num3);
				int num6 = 0;
				for (int j = 0; j < array.Length; j++)
				{
					if (num5 < array[j] + num6)
					{
						num2 = j;
						break;
					}
					num6 += array[j];
				}
				if (num2 == 5)
				{
					num2 = 999;
				}
				EntranceTeleport[] array3 = Object.FindObjectsOfType<EntranceTeleport>(false);
				int num7 = (array3.Length - 2) / 2;
				if (MimicNetworker.SpawnRateDynamic.Value && num2 < num7 && num7 > 1)
				{
					num2 += random.Next(0, 2);
				}
				if (MimicNetworker.SpawnRateDynamic.Value && currentDungeon.AllTiles.Count > 100)
				{
					num2 += random.Next(0, 2);
				}
				List<Doorway> list = new List<Doorway>();
				Bounds val2 = default(Bounds);
				foreach (Tile allTile in currentDungeon.AllTiles)
				{
					foreach (Doorway unusedDoorway in allTile.UnusedDoorways)
					{
						if (unusedDoorway.HasDoorPrefabInstance || (Object)(object)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true) == (Object)null)
						{
							continue;
						}
						GameObject gameObject = ((Component)((Component)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject;
						if (!((Object)gameObject).name.StartsWith("AlleyExitDoorContainer") || gameObject.activeSelf)
						{
							continue;
						}
						bool flag = false;
						Matrix4x4 val = Matrix4x4.TRS(((Component)unusedDoorway).transform.position, ((Component)unusedDoorway).transform.rotation, new Vector3(1f, 1f, 1f));
						((Bounds)(ref val2))..ctor(new Vector3(0f, 1.5f, 5.5f), new Vector3(2f, 6f, 8f));
						((Bounds)(ref val2)).center = ((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref val2)).center);
						Collider[] array4 = Physics.OverlapBox(((Bounds)(ref val2)).center, ((Bounds)(ref val2)).extents, ((Component)unusedDoorway).transform.rotation, LayerMask.GetMask(new string[3] { "Room", "Railing", "MapHazards" }));
						Collider[] array5 = array4;
						int num8 = 0;
						if (num8 < array5.Length)
						{
							Collider val3 = array5[num8];
							flag = true;
						}
						if (flag)
						{
							continue;
						}
						foreach (Tile allTile2 in currentDungeon.AllTiles)
						{
							if (!((Object)(object)allTile == (Object)(object)allTile2))
							{
								Vector3 origin = ((Component)unusedDoorway).transform.position + 5f * ((Component)unusedDoorway).transform.forward;
								Bounds val4 = UnityUtil.CalculateProxyBounds(((Component)allTile2).gameObject, true, Vector3.up);
								Ray val5 = default(Ray);
								((Ray)(ref val5)).origin = origin;
								((Ray)(ref val5)).direction = Vector3.up;
								if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("Catwalk") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || (((Object)allTile2).name.Contains("StartRoom") && !((Object)allTile2).name.Contains("Manor"))))
								{
									flag = true;
								}
								val5 = default(Ray);
								((Ray)(ref val5)).origin = origin;
								((Ray)(ref val5)).direction = Vector3.down;
								if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("MediumRoomHallway1B") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || ((Object)allTile2).name.Contains("StartRoom")))
								{
									flag = true;
								}
							}
						}
						if (!flag)
						{
							list.Add(unusedDoorway);
						}
					}
				}
				Shuffle(list, StartOfRound.Instance.randomMapSeed);
				List<Vector3> list2 = new List<Vector3>();
				foreach (Doorway item in list)
				{
					if (num >= num2)
					{
						break;
					}
					bool flag2 = false;
					Vector3 val6 = ((Component)item).transform.position + 5f * ((Component)item).transform.forward;
					foreach (Vector3 item2 in list2)
					{
						if (Vector3.Distance(val6, item2) < 4f)
						{
							flag2 = true;
							break;
						}
					}
					if (flag2)
					{
						continue;
					}
					list2.Add(val6);
					GameObject gameObject2 = ((Component)((Component)((Component)item).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject;
					GameObject val7 = Object.Instantiate<GameObject>(MimicPrefab, ((Component)item).transform);
					val7.transform.position = gameObject2.transform.position;
					MimicDoor component = val7.GetComponent<MimicDoor>();
					component.scanNode.creatureScanID = MimicCreatureID;
					AudioSource[] componentsInChildren = val7.GetComponentsInChildren<AudioSource>(true);
					foreach (AudioSource val8 in componentsInChildren)
					{
						val8.volume = MimicVolume / 100f;
						val8.outputAudioMixerGroup = StartOfRound.Instance.ship3DAudio.outputAudioMixerGroup;
					}
					if (SpawnRates[5] == 9753 && num == 0)
					{
						val7.transform.position = new Vector3(-7f, 0f, -10f);
					}
					MimicDoor.allMimics.Add(component);
					component.mimicIndex = num;
					num++;
					GameObject gameObject3 = ((Component)((Component)item).transform.GetChild(0)).gameObject;
					gameObject3.SetActive(false);
					Bounds bounds = ((Collider)component.frameBox).bounds;
					Vector3 center = ((Bounds)(ref bounds)).center;
					bounds = ((Collider)component.frameBox).bounds;
					Collider[] array6 = Physics.OverlapBox(center, ((Bounds)(ref bounds)).extents, Quaternion.identity);
					foreach (Collider val9 in array6)
					{
						if (((Object)((Component)val9).gameObject).name.Contains("Shelf"))
						{
							((Component)val9).gameObject.SetActive(false);
						}
					}
					Light componentInChildren = gameObject2.GetComponentInChildren<Light>(true);
					((Component)componentInChildren).transform.parent.SetParent(val7.transform);
					MeshRenderer[] componentsInChildren2 = val7.GetComponentsInChildren<MeshRenderer>();
					MeshRenderer[] array7 = componentsInChildren2;
					foreach (MeshRenderer val10 in array7)
					{
						Material[] materials = ((Renderer)val10).materials;
						foreach (Material val11 in materials)
						{
							val11.shader = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.shader;
							val11.renderQueue = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.renderQueue;
						}
					}
					component.interactTrigger.onInteract = new InteractEvent();
					((UnityEvent<PlayerControllerB>)(object)component.interactTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)component.TouchMimic);
					if (MimicPerfection)
					{
						continue;
					}
					component.interactTrigger.timeToHold = 0.9f;
					if (!ColorBlindMode)
					{
						if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0)
						{
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.490566f, 0.1226415f, 0.1302275f);
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.4339623f, 0.1043965f, 0.1150277f);
							componentInChildren.colorTemperature = 1250f;
						}
						else
						{
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.5f, 0.1580188f, 0.1657038f);
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(43f / 106f, 0.1358579f, 0.1393619f);
							componentInChildren.colorTemperature = 1300f;
						}
					}
					else if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0)
					{
						component.interactTrigger.timeToHold = 1.1f;
					}
					else
					{
						component.interactTrigger.timeToHold = 1f;
					}
					if (!EasyMode)
					{
						continue;
					}
					Random random2 = new Random(StartOfRound.Instance.randomMapSeed + num);
					switch (random2.Next(0, 4))
					{
					case 0:
						if (!ColorBlindMode)
						{
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f);
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f);
						}
						else
						{
							component.interactTrigger.timeToHold = 1.5f;
						}
						break;
					case 1:
						component.interactTrigger.hoverTip = "Feed : [LMB]";
						component.interactTrigger.holdTip = "Feed : [LMB]";
						break;
					case 2:
						component.interactTrigger.hoverIcon = component.LostFingersIcon;
						break;
					case 3:
						component.interactTrigger.holdTip = "DIE : [LMB]";
						component.interactTrigger.timeToHold = 0.5f;
						break;
					default:
						component.interactTrigger.hoverTip = "BUG, REPORT TO DEVELOPER";
						break;
					}
				}
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem))]
		internal class SprayPaintItemPatch
		{
			private static FieldInfo SprayHit = typeof(SprayPaintItem).GetField("sprayHit", BindingFlags.Instance | BindingFlags.NonPublic);

			[HarmonyPatch("SprayPaintClientRpc")]
			[HarmonyPostfix]
			private static void SprayPaintClientRpcPatch(SprayPaintItem __instance, Vector3 sprayPos, Vector3 sprayRot)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				RaycastHit val = (RaycastHit)SprayHit.GetValue(__instance);
				if ((Object)(object)((RaycastHit)(ref val)).collider != (Object)null && ((Object)((RaycastHit)(ref val)).collider).name == "MimicSprayCollider")
				{
					MimicDoor component = ((Component)((Component)((RaycastHit)(ref val)).collider).transform.parent.parent).GetComponent<MimicDoor>();
					component.sprayCount++;
					if (component.sprayCount > 8)
					{
						MimicNetworker.Instance.MimicAddAnger(1, component.mimicIndex);
					}
				}
			}
		}

		[HarmonyPatch(typeof(LockPicker))]
		internal class LockPickerPatch
		{
			private static FieldInfo RayHit = typeof(LockPicker).GetField("hit", BindingFlags.Instance | BindingFlags.NonPublic);

			[HarmonyPatch("ItemActivate")]
			[HarmonyPostfix]
			private static void ItemActivatePatch(LockPicker __instance, bool used, bool buttonDown = true)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				RaycastHit val = (RaycastHit)RayHit.GetValue(__instance);
				if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((object)(RaycastHit)(ref val)).Equals((object)default(RaycastHit)) && !((Object)(object)((RaycastHit)(ref val)).transform.parent == (Object)null))
				{
					Transform parent = ((RaycastHit)(ref val)).transform.parent;
					if (((Object)parent).name.StartsWith("MimicDoor"))
					{
						MimicNetworker.Instance.MimicLockPick(__instance, ((Component)parent).GetComponent<MimicDoor>().mimicIndex);
					}
				}
			}
		}

		private const string modGUID = "x753.Mimics";

		private const string modName = "Mimics";

		private const string modVersion = "2.3.2";

		private readonly Harmony harmony = new Harmony("x753.Mimics");

		private static Mimics Instance;

		public static GameObject MimicPrefab;

		public static GameObject MimicNetworkerPrefab;

		public static TerminalNode MimicFile;

		public static int MimicCreatureID;

		public static int[] SpawnRates;

		public static bool MimicPerfection;

		public static bool EasyMode;

		public static bool ColorBlindMode;

		public static float MimicVolume;

		public static bool DynamicSpawnRate;

		private void Awake()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.mimicdoor);
			MimicPrefab = val.LoadAsset<GameObject>("Assets/MimicDoor.prefab");
			MimicNetworkerPrefab = val.LoadAsset<GameObject>("Assets/MimicNetworker.prefab");
			MimicFile = val.LoadAsset<TerminalNode>("Assets/MimicFile.asset");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Mimics is loaded!");
			SpawnRates = new int[6]
			{
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Zero Mimics", 23, "Weight of zero mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "One Mimic", 69, "Weight of one mimic spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Two Mimics", 7, "Weight of two mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Three Mimics", 1, "Weight of three mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Four Mimics", 0, "Weight of four mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Mimics", 0, "Weight of maximum mimics spawning").Value
			};
			DynamicSpawnRate = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawn Rate", "Dynamic Spawn Rate", true, "Increases mimic spawn rate based on dungeon size and the number of instances of the real thing.").Value;
			MimicPerfection = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Perfect Mimics", false, "Select this if you want mimics to be the exact same color as the real thing. Overrides all difficulty settings.").Value;
			EasyMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Easy Mode", false, "Each mimic will have one of several possible imperfections to help you tell if it's a mimic.").Value;
			ColorBlindMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Color Blind Mode", false, "Replaces all color differences with another way to differentiate mimics.").Value;
			MimicVolume = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SFX Volume", 100, "Volume of the mimic's SFX (0-100)").Value;
			if (MimicVolume < 0f)
			{
				MimicVolume = 0f;
			}
			if (MimicVolume > 100f)
			{
				MimicVolume = 100f;
			}
			((BaseUnityPlugin)this).Config.Bind<int>("Difficulty", "Difficulty Level", 0, "This is an old setting, ignore it.");
			((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Difficulty", "Difficulty Level"].Definition);
			((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Five Mimics", 0, "This is an old setting, ignore it.");
			((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Spawn Rate", "Five Mimics"].Definition);
			((BaseUnityPlugin)this).Config.Save();
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		public static void Shuffle<T>(IList<T> list, int seed)
		{
			Random random = new Random(seed);
			int num = list.Count;
			while (num > 1)
			{
				num--;
				int index = random.Next(num + 1);
				T value = list[index];
				list[index] = list[num];
				list[num] = value;
			}
		}
	}
	public class MimicNetworker : NetworkBehaviour
	{
		public static MimicNetworker Instance;

		public static NetworkVariable<int> SpawnWeight0 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight1 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight2 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight3 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight4 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeightMax = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<bool> SpawnRateDynamic = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		private void Awake()
		{
			Instance = this;
		}

		public void MimicAttack(int playerId, int mimicIndex, bool ownerOnly = false)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicAttackClientRpc(playerId, mimicIndex);
			}
			else if (!ownerOnly)
			{
				Instance.MimicAttackServerRpc(playerId, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicAttackClientRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2885019175u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2885019175u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].Attack(playerId));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicAttackServerRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1024971481u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1024971481u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicAttackClientRpc(playerId, mimicIndex);
				}
			}
		}

		public void MimicAddAnger(int amount, int mimicIndex)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicAddAngerClientRpc(amount, mimicIndex);
			}
			else
			{
				Instance.MimicAddAngerServerRpc(amount, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicAddAngerClientRpc(int amount, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1137632670u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, amount);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1137632670u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].AddAnger(amount));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicAddAngerServerRpc(int amount, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(669208889u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, amount);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 669208889u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicAddAngerClientRpc(amount, mimicIndex);
				}
			}
		}

		public void MimicLockPick(LockPicker lockPicker, int mimicIndex, bool ownerOnly = false)
		{
			int playerId = (int)((GrabbableObject)lockPicker).playerHeldBy.playerClientId;
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicLockPickClientRpc(playerId, mimicIndex);
			}
			else if (!ownerOnly)
			{
				Instance.MimicLockPickServerRpc(playerId, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicLockPickClientRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3716888238u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3716888238u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].MimicLockPick(playerId));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicLockPickServerRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1897916243u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1897916243u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicLockPickClientRpc(playerId, mimicIndex);
				}
			}
		}

		protected override void __initializeVariables()
		{
			if (SpawnWeight0 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight0 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight0).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight0, "SpawnWeight0");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight0);
			if (SpawnWeight1 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight1 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight1).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight1, "SpawnWeight1");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight1);
			if (SpawnWeight2 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight2 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight2).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight2, "SpawnWeight2");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight2);
			if (SpawnWeight3 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight3 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight3).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight3, "SpawnWeight3");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight3);
			if (SpawnWeight4 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight4 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight4).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight4, "SpawnWeight4");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight4);
			if (SpawnWeightMax == null)
			{
				throw new Exception("MimicNetworker.SpawnWeightMax cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeightMax).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeightMax, "SpawnWeightMax");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeightMax);
			if (SpawnRateDynamic == null)
			{
				throw new Exception("MimicNetworker.SpawnRateDynamic cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnRateDynamic).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnRateDynamic, "SpawnRateDynamic");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnRateDynamic);
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_MimicNetworker()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2885019175u, new RpcReceiveHandler(__rpc_handler_2885019175));
			NetworkManager.__rpc_func_table.Add(1024971481u, new RpcReceiveHandler(__rpc_handler_1024971481));
			NetworkManager.__rpc_func_table.Add(1137632670u, new RpcReceiveHandler(__rpc_handler_1137632670));
			NetworkManager.__rpc_func_table.Add(669208889u, new RpcReceiveHandler(__rpc_handler_669208889));
			NetworkManager.__rpc_func_table.Add(3716888238u, new RpcReceiveHandler(__rpc_handler_3716888238));
			NetworkManager.__rpc_func_table.Add(1897916243u, new RpcReceiveHandler(__rpc_handler_1897916243));
		}

		private static void __rpc_handler_2885019175(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MimicNetworker)(object)target).MimicAttackClientRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1024971481(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((MimicNetworker)(object)target).MimicAttackServerRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1137632670(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int amount = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref amount);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MimicNetworker)(object)target).MimicAddAngerClientRpc(amount, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_669208889(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int amount = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref amount);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((MimicNetworker)(object)target).MimicAddAngerServerRpc(amount, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3716888238(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MimicNetworker)(object)target).MimicLockPickClientRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1897916243(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((MimicNetworker)(object)target).MimicLockPickServerRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "MimicNetworker";
		}
	}
	public class MimicDoor : MonoBehaviour
	{
		public GameObject playerTarget;

		public BoxCollider frameBox;

		public Sprite LostFingersIcon;

		public Animator mimicAnimator;

		public GameObject grabPoint;

		public InteractTrigger interactTrigger;

		public ScanNodeProperties scanNode;

		public int anger;

		public bool angering;

		public int sprayCount;

		private bool attacking;

		public static List<MimicDoor> allMimics;

		public int mimicIndex;

		private static MethodInfo RetractClaws = typeof(LockPicker).GetMethod("RetractClaws", BindingFlags.Instance | BindingFlags.NonPublic);

		public void TouchMimic(PlayerControllerB player)
		{
			if (!attacking)
			{
				MimicNetworker.Instance.MimicAttack((int)player.playerClientId, mimicIndex);
			}
		}

		public IEnumerator Attack(int playerId)
		{
			attacking = true;
			interactTrigger.interactable = false;
			PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerId];
			mimicAnimator.SetTrigger("Attack");
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)frameBox).transform.position);
			if (num < 8f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num < 14f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
			yield return (object)new WaitForSeconds(0.2f);
			if (((NetworkBehaviour)player).IsOwner && Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) < 8.75f)
			{
				player.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0);
			}
			float startTime = Time.timeSinceLevelLoad;
			yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)player.deadBody != (Object)null || Time.timeSinceLevelLoad - startTime > 4f));
			if ((Object)(object)player.deadBody != (Object)null)
			{
				player.deadBody.attachedTo = grabPoint.transform;
				player.deadBody.attachedLimb = player.deadBody.bodyParts[5];
				player.deadBody.matchPositionExactly = true;
				for (int i = 0; i < player.deadBody.bodyParts.Length; i++)
				{
					((Component)player.deadBody.bodyParts[i]).GetComponent<Collider>().excludeLayers = LayerMask.op_Implicit(-1);
				}
			}
			yield return (object)new WaitForSeconds(2f);
			if ((Object)(object)player.deadBody != (Object)null)
			{
				player.deadBody.attachedTo = null;
				player.deadBody.attachedLimb = null;
				player.deadBody.matchPositionExactly = false;
				((Component)((Component)player.deadBody).transform.GetChild(0)).gameObject.SetActive(false);
				player.deadBody = null;
			}
			yield return (object)new WaitForSeconds(4.5f);
			attacking = false;
			interactTrigger.interactable = true;
		}

		public IEnumerator MimicLockPick(int playerId)
		{
			if (angering || attacking)
			{
				yield break;
			}
			LockPicker lockPicker = default(LockPicker);
			ref LockPicker reference = ref lockPicker;
			GrabbableObject currentlyHeldObjectServer = StartOfRound.Instance.allPlayerScripts[playerId].currentlyHeldObjectServer;
			reference = (LockPicker)(object)((currentlyHeldObjectServer is LockPicker) ? currentlyHeldObjectServer : null);
			if ((Object)(object)lockPicker == (Object)null)
			{
				yield break;
			}
			attacking = true;
			interactTrigger.interactable = false;
			AudioSource component = ((Component)lockPicker).GetComponent<AudioSource>();
			component.PlayOneShot(lockPicker.placeLockPickerClips[Random.Range(0, lockPicker.placeLockPickerClips.Length)]);
			lockPicker.armsAnimator.SetBool("mounted", true);
			lockPicker.armsAnimator.SetBool("picking", true);
			component.Play();
			component.pitch = Random.Range(0.94f, 1.06f);
			lockPicker.isOnDoor = true;
			lockPicker.isPickingLock = true;
			((GrabbableObject)lockPicker).grabbable = false;
			if (((NetworkBehaviour)lockPicker).IsOwner)
			{
				((GrabbableObject)lockPicker).playerHeldBy.DiscardHeldObject(true, ((NetworkBehaviour)MimicNetworker.Instance).NetworkObject, ((Component)this).transform.position + ((Component)this).transform.up * 1.5f - ((Component)this).transform.forward * 1.15f, true);
			}
			float startTime = Time.timeSinceLevelLoad;
			yield return (object)new WaitUntil((Func<bool>)(() => !((GrabbableObject)lockPicker).isHeld || Time.timeSinceLevelLoad - startTime > 10f));
			((Component)lockPicker).transform.localEulerAngles = new Vector3(((Component)this).transform.eulerAngles.x, ((Component)this).transform.eulerAngles.y + 90f, ((Component)this).transform.eulerAngles.z);
			yield return (object)new WaitForSeconds(5f);
			RetractClaws.Invoke(lockPicker, null);
			((Component)lockPicker).transform.SetParent((Transform)null);
			((GrabbableObject)lockPicker).startFallingPosition = ((Component)lockPicker).transform.position;
			((GrabbableObject)lockPicker).FallToGround(false);
			((GrabbableObject)lockPicker).grabbable = true;
			yield return (object)new WaitForSeconds(1f);
			anger = 3;
			attacking = false;
			interactTrigger.interactable = false;
			PlayerControllerB val = null;
			float num = 9999f;
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position);
				if (num2 < num)
				{
					num = num2;
					val = val2;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex);
			}
			else
			{
				interactTrigger.interactable = true;
			}
		}

		public IEnumerator AddAnger(int amount)
		{
			if (angering || attacking)
			{
				yield break;
			}
			angering = true;
			anger += amount;
			if (anger == 1)
			{
				Sprite oldIcon2 = interactTrigger.hoverIcon;
				interactTrigger.hoverIcon = LostFingersIcon;
				mimicAnimator.SetTrigger("Growl");
				yield return (object)new WaitForSeconds(2.75f);
				interactTrigger.hoverIcon = oldIcon2;
				sprayCount = 0;
				angering = false;
				yield break;
			}
			if (anger == 2)
			{
				interactTrigger.holdTip = "DIE : [LMB]";
				interactTrigger.timeToHold = 0.25f;
				Sprite oldIcon2 = interactTrigger.hoverIcon;
				interactTrigger.hoverIcon = LostFingersIcon;
				mimicAnimator.SetTrigger("Growl");
				yield return (object)new WaitForSeconds(2.75f);
				interactTrigger.hoverIcon = oldIcon2;
				sprayCount = 0;
				angering = false;
				yield break;
			}
			if (anger > 2)
			{
				PlayerControllerB val = null;
				float num = 9999f;
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				foreach (PlayerControllerB val2 in allPlayerScripts)
				{
					float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position);
					if (num2 < num)
					{
						num = num2;
						val = val2;
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex);
				}
			}
			sprayCount = 0;
			angering = false;
		}
	}
	public class MimicCollider : MonoBehaviour, IHittable
	{
		public MimicDoor mimic;

		bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			MimicNetworker.Instance.MimicAddAnger(force, mimic.mimicIndex);
			return true;
		}
	}
	public class MimicListener : MonoBehaviour, INoiseListener
	{
		public MimicDoor mimic;

		private int tolerance = 100;

		void INoiseListener.DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if ((noiseLoudness >= 0.9f || noiseID == 101158) && Vector3.Distance(noisePosition, ((Component)mimic).transform.position) < 5f)
			{
				switch (noiseID)
				{
				case 75:
					tolerance--;
					break;
				case 5:
					tolerance -= 15;
					break;
				case 101158:
					tolerance -= 35;
					break;
				default:
					tolerance -= 30;
					break;
				}
				if (tolerance <= 0)
				{
					tolerance = 100;
					MimicNetworker.Instance.MimicAddAnger(1, mimic.mimicIndex);
				}
			}
		}
	}
}