Decompiled source of Galaxy19 Modpack beta v6.0.1

plugins/Cosmetics/x753-More_Suits-1.4.1/MoreSuits.dll

Decompiled 10 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.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MoreSuits")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that adds more suit options to Lethal Company")]
[assembly: AssemblyFileVersion("1.4.1.0")]
[assembly: AssemblyInformationalVersion("1.4.1")]
[assembly: AssemblyProduct("MoreSuits")]
[assembly: AssemblyTitle("MoreSuits")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.1.0")]
[module: UnverifiableCode]
namespace MoreSuits;

[BepInPlugin("x753.More_Suits", "More Suits", "1.4.1")]
public class MoreSuitsMod : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref StartOfRound __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_067c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0687: Unknown result type (might be due to invalid IL or missing references)
			//IL_068c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Expected O, but got Unknown
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Expected O, but got Unknown
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			try
			{
				if (SuitsAdded)
				{
					return;
				}
				int count = __instance.unlockablesList.unlockables.Count;
				UnlockableItem val = new UnlockableItem();
				int num = 0;
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val2 = __instance.unlockablesList.unlockables[i];
					if (!((Object)(object)val2.suitMaterial != (Object)null) || !val2.alreadyUnlocked)
					{
						continue;
					}
					val = val2;
					List<string> list = Directory.GetDirectories(Paths.PluginPath, "moresuits", SearchOption.AllDirectories).ToList();
					List<string> list2 = new List<string>();
					List<string> list3 = new List<string>();
					List<string> list4 = DisabledSuits.ToLower().Replace(".png", "").Split(',')
						.ToList();
					List<string> list5 = new List<string>();
					if (!LoadAllSuits)
					{
						foreach (string item2 in list)
						{
							if (File.Exists(Path.Combine(item2, "!less-suits.txt")))
							{
								string[] collection = new string[9] { "glow", "kirby", "knuckles", "luigi", "mario", "minion", "skeleton", "slayer", "smile" };
								list5.AddRange(collection);
								break;
							}
						}
					}
					foreach (string item3 in list)
					{
						if (item3 != "")
						{
							string[] files = Directory.GetFiles(item3, "*.png");
							string[] files2 = Directory.GetFiles(item3, "*.matbundle");
							list2.AddRange(files);
							list3.AddRange(files2);
						}
					}
					list3.Sort();
					list2.Sort();
					try
					{
						foreach (string item4 in list3)
						{
							Object[] array = AssetBundle.LoadFromFile(item4).LoadAllAssets();
							foreach (Object val3 in array)
							{
								if (val3 is Material)
								{
									Material item = (Material)val3;
									customMaterials.Add(item);
								}
							}
						}
					}
					catch (Exception ex)
					{
						Debug.Log((object)("Something went wrong with More Suits! Could not load materials from asset bundle(s). Error: " + ex));
					}
					foreach (string item5 in list2)
					{
						if (list4.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()))
						{
							continue;
						}
						string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
						if (list5.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()) && item5.Contains(directoryName))
						{
							continue;
						}
						UnlockableItem val4;
						Material val5;
						if (Path.GetFileNameWithoutExtension(item5).ToLower() == "default")
						{
							val4 = val;
							val5 = val4.suitMaterial;
						}
						else
						{
							val4 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
							val5 = Object.Instantiate<Material>(val4.suitMaterial);
						}
						byte[] array2 = File.ReadAllBytes(item5);
						Texture2D val6 = new Texture2D(2, 2);
						ImageConversion.LoadImage(val6, array2);
						val5.mainTexture = (Texture)(object)val6;
						val4.unlockableName = Path.GetFileNameWithoutExtension(item5);
						try
						{
							string path = Path.Combine(Path.GetDirectoryName(item5), "advanced", val4.unlockableName + ".json");
							if (File.Exists(path))
							{
								string[] array3 = File.ReadAllLines(path);
								for (int j = 0; j < array3.Length; j++)
								{
									string[] array4 = array3[j].Trim().Split(':');
									if (array4.Length != 2)
									{
										continue;
									}
									string text = array4[0].Trim('"', ' ', ',');
									string text2 = array4[1].Trim('"', ' ', ',');
									if (text2.Contains(".png"))
									{
										byte[] array5 = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(item5), "advanced", text2));
										Texture2D val7 = new Texture2D(2, 2);
										ImageConversion.LoadImage(val7, array5);
										val5.SetTexture(text, (Texture)(object)val7);
										continue;
									}
									if (text == "PRICE" && int.TryParse(text2, out var result))
									{
										try
										{
											val4 = AddToRotatingShop(val4, result, __instance.unlockablesList.unlockables.Count);
										}
										catch (Exception ex2)
										{
											Debug.Log((object)("Something went wrong with More Suits! Could not add a suit to the rotating shop. Error: " + ex2));
										}
										continue;
									}
									switch (text2)
									{
									case "KEYWORD":
										val5.EnableKeyword(text);
										continue;
									case "DISABLEKEYWORD":
										val5.DisableKeyword(text);
										continue;
									case "SHADERPASS":
										val5.SetShaderPassEnabled(text, true);
										continue;
									case "DISABLESHADERPASS":
										val5.SetShaderPassEnabled(text, false);
										continue;
									}
									float result2;
									Vector4 vector;
									if (text == "SHADER")
									{
										Shader shader = Shader.Find(text2);
										val5.shader = shader;
									}
									else if (text == "MATERIAL")
									{
										foreach (Material customMaterial in customMaterials)
										{
											if (((Object)customMaterial).name == text2)
											{
												val5 = Object.Instantiate<Material>(customMaterial);
												val5.mainTexture = (Texture)(object)val6;
												break;
											}
										}
									}
									else if (float.TryParse(text2, out result2))
									{
										val5.SetFloat(text, result2);
									}
									else if (TryParseVector4(text2, out vector))
									{
										val5.SetVector(text, vector);
									}
								}
							}
						}
						catch (Exception ex3)
						{
							Debug.Log((object)("Something went wrong with More Suits! Error: " + ex3));
						}
						val4.suitMaterial = val5;
						if (val4.unlockableName.ToLower() != "default")
						{
							if (num == MaxSuits)
							{
								Debug.Log((object)"Attempted to add a suit, but you've already reached the max number of suits! Modify the config if you want more.");
								continue;
							}
							__instance.unlockablesList.unlockables.Add(val4);
							num++;
						}
					}
					SuitsAdded = true;
					break;
				}
				UnlockableItem val8 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
				val8.alreadyUnlocked = false;
				val8.hasBeenMoved = false;
				val8.placedPosition = Vector3.zero;
				val8.placedRotation = Vector3.zero;
				val8.unlockableType = 753;
				while (__instance.unlockablesList.unlockables.Count < count + MaxSuits)
				{
					__instance.unlockablesList.unlockables.Add(val8);
				}
			}
			catch (Exception ex4)
			{
				Debug.Log((object)("Something went wrong with More Suits! Error: " + ex4));
			}
		}

		[HarmonyPatch("PositionSuitsOnRack")]
		[HarmonyPrefix]
		private static bool PositionSuitsOnRackPatch(ref StartOfRound __instance)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: 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_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_00bd: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			List<UnlockableSuit> source = Object.FindObjectsOfType<UnlockableSuit>().ToList();
			source = source.OrderBy((UnlockableSuit suit) => suit.syncedSuitID.Value).ToList();
			int num = 0;
			foreach (UnlockableSuit item in source)
			{
				AutoParentToShip component = ((Component)item).gameObject.GetComponent<AutoParentToShip>();
				component.overrideOffset = true;
				float num2 = 0.18f;
				if (MakeSuitsFitOnRack && source.Count > 13)
				{
					num2 /= (float)Math.Min(source.Count, 20) / 12f;
				}
				component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + __instance.rightmostSuitPosition.forward * num2 * (float)num;
				component.rotationOffset = new Vector3(0f, 90f, 0f);
				num++;
			}
			return false;
		}
	}

	private const string modGUID = "x753.More_Suits";

	private const string modName = "More Suits";

	private const string modVersion = "1.4.1";

	private readonly Harmony harmony = new Harmony("x753.More_Suits");

	private static MoreSuitsMod Instance;

	public static bool SuitsAdded = false;

	public static string DisabledSuits;

	public static bool LoadAllSuits;

	public static bool MakeSuitsFitOnRack;

	public static int MaxSuits;

	public static List<Material> customMaterials = new List<Material>();

	private static TerminalNode cancelPurchase;

	private static TerminalKeyword buyKeyword;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		DisabledSuits = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Disabled Suit List", "UglySuit751.png,UglySuit752.png,UglySuit753.png", "Comma-separated list of suits that shouldn't be loaded").Value;
		LoadAllSuits = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ignore !less-suits.txt", false, "If true, ignores the !less-suits.txt file and will attempt to load every suit, except those in the disabled list. This should be true if you're not worried about having too many suits.").Value;
		MakeSuitsFitOnRack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Make Suits Fit on Rack", true, "If true, squishes the suits together so more can fit on the rack.").Value;
		MaxSuits = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Max Suits", 100, "The maximum number of suits to load. If you have more, some will be ignored.").Value;
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin More Suits is loaded!");
	}

	private static UnlockableItem AddToRotatingShop(UnlockableItem newSuit, int price, int unlockableID)
	{
		//IL_0065: 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_0070: 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_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Expected O, but got Unknown
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Expected O, but got Unknown
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Expected O, but got Unknown
		Terminal val = Object.FindObjectOfType<Terminal>();
		for (int i = 0; i < val.terminalNodes.allKeywords.Length; i++)
		{
			if (((Object)val.terminalNodes.allKeywords[i]).name == "Buy")
			{
				buyKeyword = val.terminalNodes.allKeywords[i];
				break;
			}
		}
		newSuit.alreadyUnlocked = false;
		newSuit.hasBeenMoved = false;
		newSuit.placedPosition = Vector3.zero;
		newSuit.placedRotation = Vector3.zero;
		newSuit.shopSelectionNode = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)newSuit.shopSelectionNode).name = newSuit.unlockableName + "SuitBuy1";
		newSuit.shopSelectionNode.creatureName = newSuit.unlockableName + " suit";
		newSuit.shopSelectionNode.displayText = "You have requested to order " + newSuit.unlockableName + " suits.\nTotal cost of item: [totalCost].\n\nPlease CONFIRM or DENY.\n\n";
		newSuit.shopSelectionNode.clearPreviousText = true;
		newSuit.shopSelectionNode.shipUnlockableID = unlockableID;
		newSuit.shopSelectionNode.itemCost = price;
		newSuit.shopSelectionNode.overrideOptions = true;
		CompatibleNoun val2 = new CompatibleNoun();
		val2.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val2.noun.word = "confirm";
		val2.noun.isVerb = true;
		val2.result = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)val2.result).name = newSuit.unlockableName + "SuitBuyConfirm";
		val2.result.creatureName = "";
		val2.result.displayText = "Ordered " + newSuit.unlockableName + " suits! Your new balance is [playerCredits].\n\n";
		val2.result.clearPreviousText = true;
		val2.result.shipUnlockableID = unlockableID;
		val2.result.buyUnlockable = true;
		val2.result.itemCost = price;
		val2.result.terminalEvent = "";
		CompatibleNoun val3 = new CompatibleNoun();
		val3.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val3.noun.word = "deny";
		val3.noun.isVerb = true;
		if ((Object)(object)cancelPurchase == (Object)null)
		{
			cancelPurchase = ScriptableObject.CreateInstance<TerminalNode>();
		}
		val3.result = cancelPurchase;
		((Object)val3.result).name = "MoreSuitsCancelPurchase";
		val3.result.displayText = "Cancelled order.\n";
		newSuit.shopSelectionNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { val2, val3 };
		TerminalKeyword val4 = ScriptableObject.CreateInstance<TerminalKeyword>();
		((Object)val4).name = newSuit.unlockableName + "Suit";
		val4.word = newSuit.unlockableName.ToLower() + " suit";
		val4.defaultVerb = buyKeyword;
		CompatibleNoun val5 = new CompatibleNoun();
		val5.noun = val4;
		val5.result = newSuit.shopSelectionNode;
		List<CompatibleNoun> list = buyKeyword.compatibleNouns.ToList();
		list.Add(val5);
		buyKeyword.compatibleNouns = list.ToArray();
		List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
		list2.Add(val4);
		list2.Add(val2.noun);
		list2.Add(val3.noun);
		val.terminalNodes.allKeywords = list2.ToArray();
		return newSuit;
	}

	public static bool TryParseVector4(string input, out Vector4 vector)
	{
		//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_0051: 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)
		vector = Vector4.zero;
		string[] array = input.Split(',');
		if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
		{
			vector = new Vector4(result, result2, result3, result4);
			return true;
		}
		return false;
	}
}

plugins/Cosmetics/Sligili-More_Emotes-1.3.2/MoreEmotes1.3.2.dll

Decompiled 10 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.2")]
	[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.2";
	}
}
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;
			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 SetIKWeights(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(PlayerControllerB player, 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");
			}
		}

		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 = false;
			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;
				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 (!((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				D.L(__instance.playerBodyAnimator.GetInteger("emoteNumber").ToString() ?? "");
			}
			if (__instance.performingEmote)
			{
				s_wasPerformingEmote[__instance.playerClientId] = true;
			}
			if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId])
			{
				s_wasPerformingEmote[__instance.playerClientId] = false;
				SetIKWeights(__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 ((!((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;
			}
			D.L("Emote ID pre doubleemote check " + emoteID);
			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;
					}
				}
			}
			D.L("Emote ID post doubleemote check " + emoteID);
			if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote)
			{
				SetIKWeights(__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(__instance, 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(__instance, enabled: true);
			s_syncAnimator.UpdateEmoteIDForOthers(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.2 - 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>();
		}
	}
}

plugins/Cosmetics/ScruffyRules-BatteryText-1.0.0/BatteryText.dll

Decompiled 10 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[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("LethalCompany-BatteryText")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A template for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9cc1d4fd0adf170014ec3aa6746cbb47034affcd")]
[assembly: AssemblyProduct("LethalCompany-BatteryText")]
[assembly: AssemblyTitle("LethalCompany-BatteryText")]
[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 ScruffyRuffles.LC.BatteryText
{
	[HarmonyPatch]
	internal class BatteryTextPatches
	{
		private static GameObject template;

		public static TextMeshProUGUI[] batteryTexts = (TextMeshProUGUI[])(object)new TextMeshProUGUI[0];

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		public static void Update(HUDManager __instance)
		{
			//IL_0061: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00a0: 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_00af: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < GameNetworkManager.Instance.localPlayerController.ItemSlots.Length; i++)
			{
				if (i >= batteryTexts.Length)
				{
					Array.Resize(ref batteryTexts, i + 1);
				}
				if ((Object)(object)batteryTexts[i] == (Object)null)
				{
					RectTransform rectTransform = ((Graphic)__instance.itemSlotIconFrames[i]).rectTransform;
					GameObject val = Object.Instantiate<GameObject>(template, ((Transform)rectTransform).parent);
					val.SetActive(true);
					val.transform.localScale = 0.5f * Vector3.one;
					batteryTexts[i] = val.GetComponent<TextMeshProUGUI>();
					RectTransform component = ((Component)batteryTexts[i]).GetComponent<RectTransform>();
					Vector2 anchorMin = (component.anchorMax = Vector2.op_Implicit(0.5f * Vector3.one));
					component.anchorMin = anchorMin;
					component.pivot = Vector2.op_Implicit(Vector3.one);
					float num = rectTransform.sizeDelta.x * 0.5f;
					component.anchoredPosition = rectTransform.anchoredPosition + new Vector2(num, 0f - num);
					component.anchoredPosition += new Vector2(Plugin.config.offsetX, Plugin.config.offsetY);
					((Transform)component).SetParent((Transform)(object)rectTransform, true);
				}
				GrabbableObject val3 = GameNetworkManager.Instance.localPlayerController.ItemSlots[i];
				if ((Object)(object)val3 != (Object)null)
				{
					if (val3.itemProperties.requiresBattery)
					{
						((TMP_Text)batteryTexts[i]).text = Mathf.Floor(val3.insertedBattery.charge * 100f) + "%";
						if (Plugin.config.showTimeRemaining)
						{
							TextMeshProUGUI obj = batteryTexts[i];
							((TMP_Text)obj).text = ((TMP_Text)obj).text + "\n" + TimeSpan.FromSeconds(val3.itemProperties.batteryUsage * val3.insertedBattery.charge).ToString("mm\\:ss");
						}
					}
					else
					{
						((TMP_Text)batteryTexts[i]).text = "";
					}
				}
				else
				{
					((TMP_Text)batteryTexts[i]).text = "";
				}
			}
		}

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPostfix]
		public static void Awake(HUDManager __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)
			//IL_002b: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			if ((Object)(object)__instance.weightCounter != (Object)null)
			{
				GameObject val = new GameObject("ItemSlotBatteryText")
				{
					layer = LayerMask.NameToLayer("UI")
				};
				val.SetActive(false);
				TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
				((TMP_Text)obj).font = ((TMP_Text)__instance.weightCounter).font;
				((TMP_Text)obj).fontSize = ((TMP_Text)__instance.weightCounter).fontSize;
				((Graphic)obj).color = ((Graphic)__instance.batteryIcon).color;
				((TMP_Text)obj).alignment = (TextAlignmentOptions)260;
				((TMP_Text)obj).enableAutoSizing = ((TMP_Text)__instance.weightCounter).enableAutoSizing;
				((TMP_Text)obj).fontSizeMin = ((TMP_Text)__instance.weightCounter).fontSizeMin;
				((TMP_Text)obj).fontSizeMax = ((TMP_Text)__instance.weightCounter).fontSizeMax;
				template = val;
			}
		}
	}
	[BepInPlugin("ScruffyRuffles.BatteryText", "BatteryText", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public class ConfigA
		{
			private readonly ConfigFile config;

			private readonly FileSystemWatcher watcher;

			private readonly ConfigEntry<bool> _showTimeRemaining;

			private readonly ConfigEntry<float> _offsetX;

			private readonly ConfigEntry<float> _offsetY;

			public bool showTimeRemaining => _showTimeRemaining.Value;

			public float offsetX => _offsetX.Value;

			public float offsetY => _offsetY.Value;

			public ConfigA(Plugin plugin)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Expected O, but got Unknown
				config = new ConfigFile(Path.Combine(Paths.ConfigPath, "ScruffyRuffles.BatteryText.cfg"), true, MetadataHelper.GetMetadata((object)plugin));
				_showTimeRemaining = config.Bind<bool>("General", "Show Time Remaining", true, "Shows the remaining time under the percentage");
				_offsetX = config.Bind<float>("General", "Offset X", 0f, "Position Offset on the X Axis");
				_offsetY = config.Bind<float>("General", "Offset Y", -2f, "Position Offset on the Y Axis");
				watcher = new FileSystemWatcher(Path.GetDirectoryName(config.ConfigFilePath), "*.cfg")
				{
					NotifyFilter = (NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.CreationTime | NotifyFilters.Security)
				};
				watcher.Changed += ConfigFileChanged;
				watcher.EnableRaisingEvents = true;
			}

			private void OnConfigReloaded()
			{
				//IL_002d: 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_0044: 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: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: 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_0076: 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_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009a: Unknown result type (might be due to invalid IL or missing references)
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				for (int i = 0; i < BatteryTextPatches.batteryTexts.Length; i++)
				{
					RectTransform component = ((Component)BatteryTextPatches.batteryTexts[i]).GetComponent<RectTransform>();
					RectTransform component2 = ((Component)((Transform)component).parent).GetComponent<RectTransform>();
					((Transform)component).SetParent(((Transform)component2).parent);
					component.anchoredPosition = component2.anchoredPosition + new Vector2(component2.sizeDelta.x * 0.5f, (0f - component2.sizeDelta.x) * 0.5f) * Vector2.op_Implicit(((Transform)component2).localScale);
					component.anchoredPosition += new Vector2(Plugin.config.offsetX, Plugin.config.offsetY) * Vector2.op_Implicit(((Transform)component2).localScale);
					((Transform)component).SetParent((Transform)(object)component2, true);
				}
			}

			private void ConfigFileChanged(object sender, FileSystemEventArgs e)
			{
				if (!(e.FullPath != config.ConfigFilePath))
				{
					config.Reload();
					OnConfigReloaded();
				}
			}
		}

		private const string modGUID = "ScruffyRuffles.BatteryText";

		private const string modName = "BatteryText";

		private const string modVersion = "1.0.0";

		public static ManualLogSource PluginLogger;

		public static ConfigA config;

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			PluginLogger = ((BaseUnityPlugin)this).Logger;
			PluginLogger.LogInfo((object)"Plugin LethalCompany-BatteryText is loaded!");
			new Harmony("LethalCompany-BatteryText").PatchAll();
			config = new ConfigA(this);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalCompany-BatteryText";

		public const string PLUGIN_NAME = "LethalCompany-BatteryText";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/Cosmetics/Jamil-Corporate_Restructure-1.0.6/CorporateRestructure.dll

Decompiled 10 months ago
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using CorporateRestructure.Component;
using CorporateRestructure.Patch;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("CorporateRestructure")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CorporateRestructure")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("91760104-3647-46D9-988A-6D5B72EA80C6")]
[assembly: AssemblyFileVersion("1.0.6")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.6.0")]
namespace CorporateRestructure
{
	[BepInPlugin("jamil.corporate_restructure", "Corporate Restructure", "1.0.6")]
	public class CorporateRestructure : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("jamil.corporate_restructure");

		public static ConfigFile config;

		public static CorporateRestructure Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> loading");
				Instance = this;
				config = ((BaseUnityPlugin)this).Config;
				CorporateConfig.Initialize();
				Instance.Patch();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> complete");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> Awoke a second time?");
			}
		}

		private void Patch()
		{
			Instance._harmony.PatchAll(typeof(MonitorPatch));
			Instance._harmony.PatchAll(typeof(WeatherPatch));
		}
	}
	public class CorporateConfig
	{
		public const string Guid = "jamil.corporate_restructure";

		public const string Name = "Corporate Restructure";

		public const string Version = "1.0.6";

		public static ConfigEntry<bool> HideWeather { get; private set; }

		public static void Initialize()
		{
			HideWeather = CorporateRestructure.config.Bind<bool>("General", "HideWeather", false, "Disables Weather from the navigation screen, and Terminal");
		}
	}
}
namespace CorporateRestructure.Patch
{
	internal class DevPatch
	{
	}
	internal class MonitorPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		private static void Initialize()
		{
			InitializeMonitorCluster();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")]
		private static void PlayerHasRevivedServerRpc()
		{
			LootMonitor.UpdateMonitor();
			CreditMonitor.UpdateMonitor();
			DayMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDManager), "ApplyPenalty")]
		private static void ApplyPenalty()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(DepositItemsDesk), "SellAndDisplayItemProfits")]
		private static void SellLoot()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "SyncNewProfitQuotaClientRpc")]
		private static void OvertimeBonus()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		private static void RefreshLootForClientOnStart()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private static void OnPlayerConenct()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "MoveTimeOfDay")]
		private static void RefreshClock()
		{
			TimeMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		private static void RefreshLootOnPickupClient(bool grabValidated, NetworkObjectReference grabbedObject)
		{
			NetworkObject val = default(NetworkObject);
			if (((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
			{
				GrabbableObject componentInChildren = ((Component)val).gameObject.GetComponentInChildren<GrabbableObject>();
				if (componentInChildren.isInShipRoom | componentInChildren.isInElevator)
				{
					LootMonitor.UpdateMonitor();
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ThrowObjectClientRpc")]
		private static void RefreshLootOnThrowClient(bool droppedInElevator, bool droppedInShipRoom, Vector3 targetFloorPosition, NetworkObjectReference grabbedObject)
		{
			if (droppedInShipRoom || droppedInElevator)
			{
				LootMonitor.UpdateMonitor();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ChangeLevelClientRpc")]
		private static void SwitchPlanets()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "SyncGroupCreditsClientRpc")]
		private static void RefreshMoney()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "EndOfGameClientRpc")]
		private static void RefreshDay()
		{
			DayMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "StartGame")]
		private static void StartGame()
		{
			DayMonitor.UpdateMonitor();
		}

		private static void InitializeMonitorCluster()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0088: 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_00ae: 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_00c3: 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)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_0155: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038d: 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)
			GameObject val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" ?? "");
			GameObject val2 = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/HeaderText");
			Object.Destroy((Object)(object)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/BG"));
			GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/HeaderText (1)");
			Object.Destroy((Object)(object)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/BG (1)"));
			GameObject val3 = new GameObject("lootMonitor");
			val3.transform.parent = val.transform;
			val3.transform.position = val.transform.position;
			val3.transform.localPosition = val.transform.localPosition;
			val3.transform.localScale = Vector3.one;
			val3.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj = Object.Instantiate<GameObject>(val2, val3.transform);
			((Object)obj).name = "lootMonitorText";
			obj.transform.localPosition = new Vector3(-95f, 450f, 220f);
			obj.transform.rotation = Quaternion.Euler(new Vector3(-20f, 90f, 0f));
			obj.AddComponent<LootMonitor>();
			GameObject val4 = new GameObject("timeMonitor");
			val4.transform.parent = val.transform;
			val4.transform.position = val.transform.position;
			val4.transform.localPosition = val.transform.localPosition;
			val4.transform.localScale = Vector3.one;
			val4.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj2 = Object.Instantiate<GameObject>(val2, val4.transform);
			((Object)obj2).name = "timeMonitorText";
			obj2.transform.localPosition = new Vector3(-95f, 450f, -250f);
			obj2.transform.rotation = Quaternion.Euler(new Vector3(-20f, 90f, 0f));
			obj2.AddComponent<TimeMonitor>();
			GameObject val5 = new GameObject("creditMonitor");
			val5.transform.parent = val.transform;
			val5.transform.position = val.transform.position;
			val5.transform.localPosition = val.transform.localPosition;
			val5.transform.localScale = Vector3.one;
			val5.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj3 = Object.Instantiate<GameObject>(val2, val5.transform);
			((Object)obj3).name = "creditMonitorText";
			obj3.transform.localPosition = new Vector3(-198f, 450f, -750f);
			obj3.transform.rotation = Quaternion.Euler(new Vector3(-20f, 117f, 0f));
			obj3.AddComponent<CreditMonitor>();
			GameObject val6 = new GameObject("dayMonitor");
			val6.transform.parent = val.transform;
			val6.transform.position = val.transform.position;
			val6.transform.localPosition = val.transform.localPosition;
			val6.transform.localScale = Vector3.one;
			val6.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj4 = Object.Instantiate<GameObject>(val2, val6.transform);
			((Object)obj4).name = "dayMonitorText";
			obj4.transform.localPosition = new Vector3(-413f, 450f, -1185f);
			obj4.transform.rotation = Quaternion.Euler(new Vector3(-21f, 117f, 0f));
			obj4.AddComponent<DayMonitor>();
		}
	}
	internal class WeatherPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SetMapScreenInfoToCurrentLevel")]
		private static void ColorWeather(ref TextMeshProUGUI ___screenLevelDescription, ref SelectableLevel ___currentLevel)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Orbiting: " + ___currentLevel.PlanetName + "\n");
			stringBuilder.Append("Weather: " + FormatWeather(___currentLevel.currentWeather) + "\n");
			stringBuilder.Append(___currentLevel.LevelDescription ?? "");
			((TMP_Text)___screenLevelDescription).text = stringBuilder.ToString();
		}

		private static string FormatWeather(LevelWeatherType currentWeather)
		{
			//IL_0023: 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_0047: Expected I4, but got Unknown
			string text = "FFFFFF";
			if (CorporateConfig.HideWeather.Value)
			{
				return "<color=#" + text + ">UNKNOWN</color>";
			}
			switch (currentWeather - -1)
			{
			case 0:
			case 1:
				text = "69FF6B";
				break;
			case 2:
			case 4:
				text = "FFDC00";
				break;
			case 3:
			case 5:
				text = "FF9300";
				break;
			case 6:
				text = "FF0000";
				break;
			}
			return "<color=#" + text + ">" + ((object)(LevelWeatherType)(ref currentWeather)).ToString() + "</color>";
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
		private static string HideWeatherConditions(string __result)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (CorporateConfig.HideWeather.Value)
			{
				foreach (LevelWeatherType value in Enum.GetValues(typeof(LevelWeatherType)))
				{
					LevelWeatherType val = value;
					__result = __result.Replace("(" + ((object)(LevelWeatherType)(ref val)).ToString() + ")", "");
				}
			}
			return __result;
		}
	}
}
namespace CorporateRestructure.Component
{
	public class DayMonitor : MonoBehaviour
	{
		private static StartOfRound _startOfRound;

		private static TextMeshProUGUI _textMesh;

		private static EndOfGameStats _stats;

		public void Start()
		{
			_startOfRound = StartOfRound.Instance;
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			_stats = _startOfRound.gameStats;
			if (!((NetworkBehaviour)_startOfRound).IsHost)
			{
				((TMP_Text)_textMesh).text = "DAY:\n?";
			}
			else
			{
				UpdateMonitor();
			}
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = $"DAY:\n{_stats.daysSpent}";
		}
	}
	public class LootMonitor : MonoBehaviour
	{
		private static LootMonitor _lootMonitor;

		private static TextMeshProUGUI _textMesh;

		private static GameObject _ship;

		public void Start()
		{
			_lootMonitor = this;
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			((TMP_Text)_textMesh).text = "LOOT:\n$NaN";
			_ship = GameObject.Find("/Environment/HangarShip");
			UpdateMonitor();
		}

		public static void UpdateMonitor()
		{
			float num = Calculate();
			((TMP_Text)_textMesh).text = $"LOOT:\n${num}";
		}

		private static float Calculate()
		{
			return (from x in _ship.GetComponentsInChildren<GrabbableObject>()
				where x.itemProperties.isScrap && !x.isPocketed && !x.isHeld
				select x).Sum((GrabbableObject x) => x.scrapValue);
		}
	}
	public class CreditMonitor : MonoBehaviour
	{
		private static Terminal _terminal;

		private static TextMeshProUGUI _textMesh;

		public void Start()
		{
			_terminal = Object.FindObjectOfType<Terminal>();
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			UpdateMonitor();
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = $"CREDITS:\n${_terminal.groupCredits}";
		}
	}
	public class TimeMonitor : MonoBehaviour
	{
		private static TextMeshProUGUI _textMesh;

		private static TextMeshProUGUI _timeMesh;

		public void Start()
		{
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			_timeMesh = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/ProfitQuota/Container/Box/TimeNumber").GetComponent<TextMeshProUGUI>();
			((TMP_Text)_textMesh).text = "TIME:\n7:30\nAM";
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = "TIME:\n" + ((TMP_Text)_timeMesh).text;
		}
	}
}

plugins/Cosmetics/FlipMods-MoreBlood-1.0.2 (2)/MoreBlood.dll

Decompiled 10 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreBlood.Config;
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("MoreBlood")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreBlood")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d1f1321d-30a3-4600-9bf8-1e69fe1abf8c")]
[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 MoreBlood
{
	[BepInPlugin("FlipMods.MoreBlood", "MoreBlood", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			instance = this;
			_harmony = new Harmony("MoreBlood");
			ConfigSettings.BindConfigSettings();
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreBlood loaded");
		}

		public static void Log(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)message);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.MoreBlood";

		public const string PLUGIN_NAME = "MoreBlood";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}
namespace MoreBlood.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class MoreBloodPatcher
	{
		private static int bloodCount;

		[HarmonyPatch("DropBlood")]
		[HarmonyPostfix]
		public static void MoreBlood(PlayerControllerB __instance, Vector3 direction = default(Vector3), bool leaveBlood = true, bool leaveFootprint = false)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			bloodCount++;
			if (bloodCount < ConfigSettings.numBloodPools.Value)
			{
				__instance.DropBlood(direction, leaveBlood, leaveFootprint);
			}
			else
			{
				bloodCount = 0;
			}
		}

		[HarmonyPatch("RandomizeBloodRotationAndScale")]
		[HarmonyPostfix]
		public static void RandomizeBloodScale(ref Transform blood, PlayerControllerB __instance)
		{
			//IL_0004: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = blood;
			obj.localScale *= ConfigSettings.bloodScale.Value;
			blood.position += new Vector3((float)Random.Range(-1, 1) * ConfigSettings.bloodScale.Value, 0.55f, (float)Random.Range(-1, 1) * ConfigSettings.bloodScale.Value);
		}
	}
}
namespace MoreBlood.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<float> bloodScale;

		public static ConfigEntry<int> numBloodPools;

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			bloodScale = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("MoreBlood", "BloodScale", 4f, "The size of the blood pools");
			numBloodPools = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("MoreBlood", "NumberOfBloodPools", 4, "Max number of blood pools spread around the blood source.");
		}
	}
}

plugins/Cosmetics/ficcialfaint-Spectator_Voice_Icon_Fix-1.0.0/SpectatorVoiceIconFix.dll

Decompiled 10 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 Dissonance;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[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("SpectatorVoiceIconFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Fix wrong voice icon in spectator mode")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SpectatorVoiceIconFix")]
[assembly: AssemblyTitle("SpectatorVoiceIconFix")]
[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 SpectatorVoiceIconFix
{
	[BepInPlugin("SpectatorVoiceIconFix", "SpectatorVoiceIconFix", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("SpectatorVoiceIconFix");

		private void Awake()
		{
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin SpectatorVoiceIconFix is loaded!");
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	public class SpectatorPatch
	{
		private static readonly int Speaking = Animator.StringToHash("speaking");

		[HarmonyPatch("UpdateSpectateBoxSpeakerIcons")]
		[HarmonyPostfix]
		private static void FixAudioIcon()
		{
			foreach (KeyValuePair<Animator, PlayerControllerB> item in Traverse.Create((object)HUDManager.Instance).Field("spectatingPlayerBoxes").GetValue<Dictionary<Animator, PlayerControllerB>>())
			{
				if ((item.Value.isPlayerControlled || item.Value.isPlayerDead) && !((Object)(object)item.Value != (Object)(object)GameNetworkManager.Instance.localPlayerController) && !string.IsNullOrEmpty(StartOfRound.Instance.voiceChatModule.LocalPlayerName))
				{
					VoicePlayerState val = StartOfRound.Instance.voiceChatModule.FindPlayer(StartOfRound.Instance.voiceChatModule.LocalPlayerName);
					if (val != null)
					{
						item.Key.SetBool(Speaking, val.IsSpeaking && val.Amplitude > 0.005f && !StartOfRound.Instance.voiceChatModule.IsMuted);
					}
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "SpectatorVoiceIconFix";

		public const string PLUGIN_NAME = "SpectatorVoiceIconFix";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/Cosmetics/akechii-DiscountAlert-2.3.0/DiscountAlert.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
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.Configuration;
using DiscountAlert;
using HarmonyLib;
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: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("DiscountAlert")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A template for Lethal Company")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: AssemblyInformationalVersion("2.3.0.0")]
[assembly: AssemblyProduct("DiscountAlert")]
[assembly: AssemblyTitle("DiscountAlert")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.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.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[HarmonyPatch(typeof(StartMatchLever))]
public class StartMatchLever_Patches
{
	private static string priceUpColor = Plugin.Instance.PRICE_UP_COLOR;

	private static string priceDownColor = Plugin.Instance.PRICE_DOWN_COLOR;

	private static string noDiscountColor = Plugin.Instance.NO_DISCOUNT_COLOR;

	private static string noDiscountText = Plugin.Instance.noDiscountText.Value;

	private static string titleColor = Plugin.Instance.TITLE_COLOR;

	private static string titleText = Plugin.Instance.titleText.Value;

	private static int delayAfterLeverIsPulled = Plugin.Instance.delayAfterLeverIsPulled.Value;

	private static bool colorsEnabled = Plugin.Instance.colorsEnabled.Value;

	private static bool alertEnabledWhenNoDiscounts = Plugin.Instance.alertEnabledWhenNoDiscounts.Value;

	public static bool playerAlerted = false;

	public static int counter = 0;

	[HarmonyPatch("PlayLeverPullEffectsClientRpc")]
	[HarmonyPostfix]
	public static void PlayLeverPullEffectsClientRpcPatch()
	{
		playerAlerted = false;
		counter++;
		if (StartOfRound.Instance.inShipPhase && !playerAlerted && counter == 1)
		{
			playerAlerted = true;
			((MonoBehaviour)HUDManager.Instance).StartCoroutine(DisplayAlert());
		}
		else if (counter > 1)
		{
			counter = 0;
		}
	}

	private static IEnumerator DisplayAlert()
	{
		yield return (object)new WaitForSeconds((float)delayAfterLeverIsPulled);
		Debug.Log((object)"Displaying alert");
		StringBuilder discount_list = new StringBuilder();
		for (int i = 0; i < HUDManager.Instance.terminalScript.buyableItemsList.Length; i++)
		{
			if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] != 100)
			{
				if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] < 0)
				{
					discount_list.Append("\n" + ((priceUpColor != null) ? ("<color=" + priceUpColor + ">* ") : "* ") + HUDManager.Instance.terminalScript.buyableItemsList[i].itemName + $" ${(float)HUDManager.Instance.terminalScript.buyableItemsList[i].creditsWorth * (1f - (float)HUDManager.Instance.terminalScript.itemSalesPercentages[i] / 100f)} " + string.Format("({0}% UP!){1}", Math.Abs(HUDManager.Instance.terminalScript.itemSalesPercentages[i]), (priceUpColor != null) ? "</color>" : ""));
				}
				else if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] > 0)
				{
					discount_list.Append("\n" + ((priceDownColor != null) ? ("<color=" + priceDownColor + ">* ") : "* ") + HUDManager.Instance.terminalScript.buyableItemsList[i].itemName + $" ${(float)HUDManager.Instance.terminalScript.buyableItemsList[i].creditsWorth * (float)HUDManager.Instance.terminalScript.itemSalesPercentages[i] / 100f} " + string.Format("({0}% OFF!){1}", 100 - HUDManager.Instance.terminalScript.itemSalesPercentages[i], (priceDownColor != null) ? "</color>" : ""));
				}
			}
		}
		if ((!(discount_list.ToString() == "") && discount_list != null) || alertEnabledWhenNoDiscounts)
		{
			if ((discount_list.ToString() == "" || discount_list == null) && alertEnabledWhenNoDiscounts)
			{
				discount_list.Append(((noDiscountColor != null) ? ("<color=" + noDiscountColor + "> ") : " ") + noDiscountText + ((noDiscountColor != null) ? "</color>" : ""));
			}
			HUDManager.Instance.DisplayTip(((titleColor != null) ? ("<color=" + titleColor + "> ") : " ") + titleText + ((titleColor != null) ? "</color>" : ""), discount_list.ToString(), false, false, "LC_Tip1");
		}
	}
}
namespace DiscountAlert
{
	[BepInPlugin("discount.alert", "DiscountAlert", "2.3.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "discount.alert";

		private const string modName = "DiscountAlert";

		private const string modVersion = "2.3.0.0";

		public ConfigEntry<string> priceUpColor;

		public ConfigEntry<string> priceDownColor;

		public ConfigEntry<string> noDiscountColor;

		public ConfigEntry<string> noDiscountText;

		public ConfigEntry<string> titleColor;

		public ConfigEntry<string> titleText;

		public ConfigEntry<int> delayAfterLeverIsPulled;

		public ConfigEntry<bool> colorsEnabled;

		public ConfigEntry<bool> alertEnabledWhenNoDiscounts;

		public string PRICE_UP_COLOR;

		public string PRICE_DOWN_COLOR;

		public string NO_DISCOUNT_COLOR;

		public string TITLE_COLOR;

		private readonly Harmony harmony = new Harmony("discount.alert");

		public static Plugin? Instance;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			priceUpColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "PriceUpColor", "#990000", "Text color when the price goes up (currently only possible with other mods)");
			priceDownColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "PriceDownColor", "#008000", "Text color when the price goes down");
			delayAfterLeverIsPulled = ((BaseUnityPlugin)this).Config.Bind<int>("Alert", "DelayAfterLeverIsPulled", 4, "Number of seconds to wait after the \"Land ship\" or \"Start Game\" lever is pulled before showing the alert.");
			colorsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Alert", "ColorsEnabled", true, "Enable or disable text colors");
			noDiscountColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "NoDiscountColor", "", "Text color when there are no discounts");
			titleColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "TitleColor", "", "Text color for the alert's title");
			titleText = ((BaseUnityPlugin)this).Config.Bind<string>("Alert", "TitleText", "Today's discounts", "Alert title text");
			noDiscountText = ((BaseUnityPlugin)this).Config.Bind<string>("Alert", "NoDiscountText", "None :( \n Check back tomorrow!", "Alert text when there are no discounts");
			alertEnabledWhenNoDiscounts = ((BaseUnityPlugin)this).Config.Bind<bool>("Alert", "AlertEnabledWhenNoDiscounts", true, "Show alert when there are no discounts");
			if (!IsValidHexCode(priceUpColor.Value))
			{
				PRICE_UP_COLOR = null;
			}
			else
			{
				PRICE_UP_COLOR = priceUpColor.Value;
			}
			if (!IsValidHexCode(priceDownColor.Value))
			{
				PRICE_DOWN_COLOR = null;
			}
			else
			{
				PRICE_DOWN_COLOR = priceDownColor.Value;
			}
			if (!IsValidHexCode(noDiscountColor.Value))
			{
				NO_DISCOUNT_COLOR = null;
			}
			else
			{
				NO_DISCOUNT_COLOR = noDiscountColor.Value;
			}
			if (!IsValidHexCode(titleColor.Value))
			{
				TITLE_COLOR = null;
			}
			else
			{
				TITLE_COLOR = titleColor.Value;
			}
			if (!colorsEnabled.Value)
			{
				PRICE_UP_COLOR = null;
				PRICE_DOWN_COLOR = null;
				NO_DISCOUNT_COLOR = null;
				TITLE_COLOR = null;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin discount.alert is loaded!");
			harmony.PatchAll();
		}

		public static bool IsValidHexCode(string hexCode)
		{
			string pattern = "^#?([0-9A-Fa-f]{3}){1,2}$";
			return Regex.IsMatch(hexCode, pattern);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/Cosmetics/EliteMasterEric-Coroner-1.5.3/Coroner.dll

Decompiled 10 months ago
using System;
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.Xml.Linq;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Coroner.LCAPI;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using TMPro;
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("EliteMasterEric")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Rework the Performance Report with new info, including cause of death.")]
[assembly: AssemblyFileVersion("1.5.3.0")]
[assembly: AssemblyInformationalVersion("1.5.3+3f9dc5379bdbfe1ac1cf1b0df31bb040630db71f")]
[assembly: AssemblyProduct("Coroner")]
[assembly: AssemblyTitle("Coroner")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.3.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 Coroner
{
	public class AdvancedDeathTracker
	{
		public const int PLAYER_CAUSE_OF_DEATH_DROPSHIP = 300;

		private static readonly Dictionary<int, AdvancedCauseOfDeath> PlayerCauseOfDeath = new Dictionary<int, AdvancedCauseOfDeath>();

		public static void ClearDeathTracker()
		{
			PlayerCauseOfDeath.Clear();
		}

		public static void SetCauseOfDeath(int playerIndex, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true)
		{
			PlayerCauseOfDeath[playerIndex] = causeOfDeath;
			if (broadcast)
			{
				DeathBroadcaster.BroadcastCauseOfDeath(playerIndex, causeOfDeath);
			}
		}

		public static void SetCauseOfDeath(int playerIndex, CauseOfDeath causeOfDeath, bool broadcast = true)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			SetCauseOfDeath(playerIndex, ConvertCauseOfDeath(causeOfDeath), broadcast);
		}

		public static void SetCauseOfDeath(PlayerControllerB playerController, CauseOfDeath causeOfDeath, bool broadcast = true)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			SetCauseOfDeath((int)playerController.playerClientId, ConvertCauseOfDeath(causeOfDeath), broadcast);
		}

		public static void SetCauseOfDeath(PlayerControllerB playerController, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true)
		{
			SetCauseOfDeath((int)playerController.playerClientId, causeOfDeath, broadcast);
		}

		public static AdvancedCauseOfDeath GetCauseOfDeath(int playerIndex)
		{
			PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerIndex];
			return GetCauseOfDeath(playerController);
		}

		public static AdvancedCauseOfDeath GetCauseOfDeath(PlayerControllerB playerController)
		{
			if (!PlayerCauseOfDeath.ContainsKey((int)playerController.playerClientId))
			{
				Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has no custom cause of death stored! Using fallback...");
				return GuessCauseOfDeath(playerController);
			}
			Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has custom cause of death stored! {PlayerCauseOfDeath[(int)playerController.playerClientId]}");
			return PlayerCauseOfDeath[(int)playerController.playerClientId];
		}

		public static AdvancedCauseOfDeath GuessCauseOfDeath(PlayerControllerB playerController)
		{
			//IL_0041: 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_001e: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Invalid comparison between Unknown and I4
			if (playerController.isPlayerDead)
			{
				if (IsHoldingJetpack(playerController))
				{
					if ((int)playerController.causeOfDeath == 2)
					{
						return AdvancedCauseOfDeath.Player_Jetpack_Gravity;
					}
					if ((int)playerController.causeOfDeath == 3)
					{
						return AdvancedCauseOfDeath.Player_Jetpack_Blast;
					}
				}
				return ConvertCauseOfDeath(playerController.causeOfDeath);
			}
			return AdvancedCauseOfDeath.Unknown;
		}

		public static bool IsHoldingJetpack(PlayerControllerB playerController)
		{
			GrabbableObject currentlyHeldObjectServer = playerController.currentlyHeldObjectServer;
			if ((Object)(object)currentlyHeldObjectServer == (Object)null)
			{
				return false;
			}
			GameObject gameObject = ((Component)currentlyHeldObjectServer).gameObject;
			if ((Object)(object)gameObject == (Object)null)
			{
				return false;
			}
			GrabbableObject component = gameObject.GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null)
			{
				return false;
			}
			if (component is JetpackItem)
			{
				return true;
			}
			return false;
		}

		public static AdvancedCauseOfDeath ConvertCauseOfDeath(CauseOfDeath causeOfDeath)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected I4, but got Unknown
			return (int)causeOfDeath switch
			{
				0 => AdvancedCauseOfDeath.Unknown, 
				1 => AdvancedCauseOfDeath.Bludgeoning, 
				2 => AdvancedCauseOfDeath.Gravity, 
				3 => AdvancedCauseOfDeath.Blast, 
				4 => AdvancedCauseOfDeath.Strangulation, 
				5 => AdvancedCauseOfDeath.Suffocation, 
				6 => AdvancedCauseOfDeath.Mauling, 
				7 => AdvancedCauseOfDeath.Gunshots, 
				8 => AdvancedCauseOfDeath.Crushing, 
				9 => AdvancedCauseOfDeath.Drowning, 
				10 => AdvancedCauseOfDeath.Abandoned, 
				11 => AdvancedCauseOfDeath.Electrocution, 
				_ => AdvancedCauseOfDeath.Unknown, 
			};
		}

		public static string StringifyCauseOfDeath(CauseOfDeath causeOfDeath)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return StringifyCauseOfDeath(ConvertCauseOfDeath(causeOfDeath), Plugin.RANDOM);
		}

		public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath)
		{
			return StringifyCauseOfDeath(causeOfDeath, Plugin.RANDOM);
		}

		public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath, Random random)
		{
			string[] array = SelectCauseOfDeath(causeOfDeath);
			if (array.Length > 1 && (!causeOfDeath.HasValue || !Plugin.Instance.PluginConfig.ShouldUseSeriousDeathMessages()))
			{
				return array[random.Next(array.Length)];
			}
			return array[0];
		}

		public static string[] SelectCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath)
		{
			if (!causeOfDeath.HasValue)
			{
				return LanguageHandler.GetValuesByTag("FunnyNote");
			}
			return causeOfDeath switch
			{
				AdvancedCauseOfDeath.Bludgeoning => LanguageHandler.GetValuesByTag("DeathBludgeoning"), 
				AdvancedCauseOfDeath.Gravity => LanguageHandler.GetValuesByTag("DeathGravity"), 
				AdvancedCauseOfDeath.Blast => LanguageHandler.GetValuesByTag("DeathBlast"), 
				AdvancedCauseOfDeath.Strangulation => LanguageHandler.GetValuesByTag("DeathStrangulation"), 
				AdvancedCauseOfDeath.Suffocation => LanguageHandler.GetValuesByTag("DeathSuffocation"), 
				AdvancedCauseOfDeath.Mauling => LanguageHandler.GetValuesByTag("DeathMauling"), 
				AdvancedCauseOfDeath.Gunshots => LanguageHandler.GetValuesByTag("DeathGunshots"), 
				AdvancedCauseOfDeath.Crushing => LanguageHandler.GetValuesByTag("DeathCrushing"), 
				AdvancedCauseOfDeath.Drowning => LanguageHandler.GetValuesByTag("DeathDrowning"), 
				AdvancedCauseOfDeath.Abandoned => LanguageHandler.GetValuesByTag("DeathAbandoned"), 
				AdvancedCauseOfDeath.Electrocution => LanguageHandler.GetValuesByTag("DeathElectrocution"), 
				AdvancedCauseOfDeath.Kicking => LanguageHandler.GetValuesByTag("DeathKicking"), 
				AdvancedCauseOfDeath.Enemy_Bracken => LanguageHandler.GetValuesByTag("DeathEnemyBracken"), 
				AdvancedCauseOfDeath.Enemy_EyelessDog => LanguageHandler.GetValuesByTag("DeathEnemyEyelessDog"), 
				AdvancedCauseOfDeath.Enemy_ForestGiant => LanguageHandler.GetValuesByTag("DeathEnemyForestGiant"), 
				AdvancedCauseOfDeath.Enemy_CircuitBees => LanguageHandler.GetValuesByTag("DeathEnemyCircuitBees"), 
				AdvancedCauseOfDeath.Enemy_GhostGirl => LanguageHandler.GetValuesByTag("DeathEnemyGhostGirl"), 
				AdvancedCauseOfDeath.Enemy_EarthLeviathan => LanguageHandler.GetValuesByTag("DeathEnemyEarthLeviathan"), 
				AdvancedCauseOfDeath.Enemy_BaboonHawk => LanguageHandler.GetValuesByTag("DeathEnemyBaboonHawk"), 
				AdvancedCauseOfDeath.Enemy_Jester => LanguageHandler.GetValuesByTag("DeathEnemyJester"), 
				AdvancedCauseOfDeath.Enemy_CoilHead => LanguageHandler.GetValuesByTag("DeathEnemyCoilHead"), 
				AdvancedCauseOfDeath.Enemy_SnareFlea => LanguageHandler.GetValuesByTag("DeathEnemySnareFlea"), 
				AdvancedCauseOfDeath.Enemy_Hygrodere => LanguageHandler.GetValuesByTag("DeathEnemyHygrodere"), 
				AdvancedCauseOfDeath.Enemy_HoarderBug => LanguageHandler.GetValuesByTag("DeathEnemyHoarderBug"), 
				AdvancedCauseOfDeath.Enemy_SporeLizard => LanguageHandler.GetValuesByTag("DeathEnemySporeLizard"), 
				AdvancedCauseOfDeath.Enemy_BunkerSpider => LanguageHandler.GetValuesByTag("DeathEnemyBunkerSpider"), 
				AdvancedCauseOfDeath.Enemy_Thumper => LanguageHandler.GetValuesByTag("DeathEnemyThumper"), 
				AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerWear"), 
				AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerVictim"), 
				AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerKicked"), 
				AdvancedCauseOfDeath.Enemy_Nutcracker_Shot => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerShot"), 
				AdvancedCauseOfDeath.Player_Jetpack_Gravity => LanguageHandler.GetValuesByTag("DeathPlayerJetpackGravity"), 
				AdvancedCauseOfDeath.Player_Jetpack_Blast => LanguageHandler.GetValuesByTag("DeathPlayerJetpackBlast"), 
				AdvancedCauseOfDeath.Player_Murder_Melee => LanguageHandler.GetValuesByTag("DeathPlayerMurderMelee"), 
				AdvancedCauseOfDeath.Player_Murder_Shotgun => LanguageHandler.GetValuesByTag("DeathPlayerMurderShotgun"), 
				AdvancedCauseOfDeath.Player_Quicksand => LanguageHandler.GetValuesByTag("DeathPlayerQuicksand"), 
				AdvancedCauseOfDeath.Player_StunGrenade => LanguageHandler.GetValuesByTag("DeathPlayerStunGrenade"), 
				AdvancedCauseOfDeath.Other_DepositItemsDesk => LanguageHandler.GetValuesByTag("DeathOtherDepositItemsDesk"), 
				AdvancedCauseOfDeath.Other_Dropship => LanguageHandler.GetValuesByTag("DeathOtherItemDropship"), 
				AdvancedCauseOfDeath.Other_Landmine => LanguageHandler.GetValuesByTag("DeathOtherLandmine"), 
				AdvancedCauseOfDeath.Other_Turret => LanguageHandler.GetValuesByTag("DeathOtherTurret"), 
				AdvancedCauseOfDeath.Other_Lightning => LanguageHandler.GetValuesByTag("DeathOtherLightning"), 
				_ => LanguageHandler.GetValuesByTag("DeathUnknown"), 
			};
		}

		internal static void SetCauseOfDeath(PlayerControllerB playerControllerB, object enemy_BaboonHawk)
		{
			throw new NotImplementedException();
		}
	}
	public enum AdvancedCauseOfDeath
	{
		Unknown,
		Bludgeoning,
		Gravity,
		Blast,
		Strangulation,
		Suffocation,
		Mauling,
		Gunshots,
		Crushing,
		Drowning,
		Abandoned,
		Electrocution,
		Kicking,
		Enemy_BaboonHawk,
		Enemy_Bracken,
		Enemy_CircuitBees,
		Enemy_CoilHead,
		Enemy_EarthLeviathan,
		Enemy_EyelessDog,
		Enemy_ForestGiant,
		Enemy_GhostGirl,
		Enemy_Hygrodere,
		Enemy_Jester,
		Enemy_SnareFlea,
		Enemy_SporeLizard,
		Enemy_HoarderBug,
		Enemy_Thumper,
		Enemy_BunkerSpider,
		Enemy_MaskedPlayer_Wear,
		Enemy_MaskedPlayer_Victim,
		Enemy_Nutcracker_Kicked,
		Enemy_Nutcracker_Shot,
		Player_Jetpack_Gravity,
		Player_Jetpack_Blast,
		Player_Quicksand,
		Player_Murder_Melee,
		Player_Murder_Shotgun,
		Player_StunGrenade,
		Other_Landmine,
		Other_Turret,
		Other_Lightning,
		Other_DepositItemsDesk,
		Other_Dropship
	}
	internal class DeathBroadcaster
	{
		private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death";

		public static void Initialize()
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				DeathBroadcasterLCAPI.Initialize();
			}
			else
			{
				Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping registration...");
			}
		}

		public static void BroadcastCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath)
		{
			AttemptBroadcast(BuildDataCauseOfDeath(playerId, causeOfDeath), "com.elitemastereric.coroner.death");
		}

		private static string BuildDataCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath)
		{
			string text = playerId.ToString();
			int num = (int)causeOfDeath;
			return text + "|" + num;
		}

		private static void AttemptBroadcast(string data, string signature)
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				DeathBroadcasterLCAPI.AttemptBroadcast(data, signature);
			}
			else
			{
				Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping broadcast...");
			}
		}
	}
	internal class LanguageHandler
	{
		public const string DEFAULT_LANGUAGE = "en";

		public static readonly string[] AVAILABLE_LANGUAGES = new string[4] { "en", "ru", "nl", "fr" };

		public const string TAG_FUNNY_NOTES = "FunnyNote";

		public const string TAG_UI_NOTES = "UINotes";

		public const string TAG_UI_DEATH = "UICauseOfDeath";

		public const string TAG_DEATH_GENERIC_BLUDGEONING = "DeathBludgeoning";

		public const string TAG_DEATH_GENERIC_GRAVITY = "DeathGravity";

		public const string TAG_DEATH_GENERIC_BLAST = "DeathBlast";

		public const string TAG_DEATH_GENERIC_STRANGULATION = "DeathStrangulation";

		public const string TAG_DEATH_GENERIC_SUFFOCATION = "DeathSuffocation";

		public const string TAG_DEATH_GENERIC_MAULING = "DeathMauling";

		public const string TAG_DEATH_GENERIC_GUNSHOTS = "DeathGunshots";

		public const string TAG_DEATH_GENERIC_CRUSHING = "DeathCrushing";

		public const string TAG_DEATH_GENERIC_DROWNING = "DeathDrowning";

		public const string TAG_DEATH_GENERIC_ABANDONED = "DeathAbandoned";

		public const string TAG_DEATH_GENERIC_ELECTROCUTION = "DeathElectrocution";

		public const string TAG_DEATH_GENERIC_KICKING = "DeathKicking";

		public const string TAG_DEATH_ENEMY_BRACKEN = "DeathEnemyBracken";

		public const string TAG_DEATH_ENEMY_EYELESS_DOG = "DeathEnemyEyelessDog";

		public const string TAG_DEATH_ENEMY_FOREST_GIANT = "DeathEnemyForestGiant";

		public const string TAG_DEATH_ENEMY_CIRCUIT_BEES = "DeathEnemyCircuitBees";

		public const string TAG_DEATH_ENEMY_GHOST_GIRL = "DeathEnemyGhostGirl";

		public const string TAG_DEATH_ENEMY_EARTH_LEVIATHAN = "DeathEnemyEarthLeviathan";

		public const string TAG_DEATH_ENEMY_BABOON_HAWK = "DeathEnemyBaboonHawk";

		public const string TAG_DEATH_ENEMY_JESTER = "DeathEnemyJester";

		public const string TAG_DEATH_ENEMY_COILHEAD = "DeathEnemyCoilHead";

		public const string TAG_DEATH_ENEMY_SNARE_FLEA = "DeathEnemySnareFlea";

		public const string TAG_DEATH_ENEMY_HYGRODERE = "DeathEnemyHygrodere";

		public const string TAG_DEATH_ENEMY_HOARDER_BUG = "DeathEnemyHoarderBug";

		public const string TAG_DEATH_ENEMY_SPORE_LIZARD = "DeathEnemySporeLizard";

		public const string TAG_DEATH_ENEMY_BUNKER_SPIDER = "DeathEnemyBunkerSpider";

		public const string TAG_DEATH_ENEMY_THUMPER = "DeathEnemyThumper";

		public const string TAG_DEATH_ENEMY_MASKED_PLAYER_WEAR = "DeathEnemyMaskedPlayerWear";

		public const string TAG_DEATH_ENEMY_MASKED_PLAYER_VICTIM = "DeathEnemyMaskedPlayerVictim";

		public const string TAG_DEATH_ENEMY_NUTCRACKER_KICKED = "DeathEnemyNutcrackerKicked";

		public const string TAG_DEATH_ENEMY_NUTCRACKER_SHOT = "DeathEnemyNutcrackerShot";

		public const string TAG_DEATH_PLAYER_JETPACK_GRAVITY = "DeathPlayerJetpackGravity";

		public const string TAG_DEATH_PLAYER_JETPACK_BLAST = "DeathPlayerJetpackBlast";

		public const string TAG_DEATH_PLAYER_MURDER_MELEE = "DeathPlayerMurderMelee";

		public const string TAG_DEATH_PLAYER_MURDER_SHOTGUN = "DeathPlayerMurderShotgun";

		public const string TAG_DEATH_PLAYER_QUICKSAND = "DeathPlayerQuicksand";

		public const string TAG_DEATH_PLAYER_STUN_GRENADE = "DeathPlayerStunGrenade";

		public const string TAG_DEATH_OTHER_DEPOSIT_ITEMS_DESK = "DeathOtherDepositItemsDesk";

		public const string TAG_DEATH_OTHER_ITEM_DROPSHIP = "DeathOtherItemDropship";

		public const string TAG_DEATH_OTHER_LANDMINE = "DeathOtherLandmine";

		public const string TAG_DEATH_OTHER_TURRET = "DeathOtherTurret";

		public const string TAG_DEATH_OTHER_LIGHTNING = "DeathOtherLightning";

		public const string TAG_DEATH_UNKNOWN = "DeathUnknown";

		private static XDocument languageData;

		public static void Initialize()
		{
			Plugin.Instance.PluginLogger.LogInfo("Coroner Language Support: " + Plugin.Instance.PluginConfig.GetSelectedLanguage());
			ValidateLanguage(Plugin.Instance.PluginConfig.GetSelectedLanguage());
			LoadLanguageData(Plugin.Instance.PluginConfig.GetSelectedLanguage());
		}

		private static void ValidateLanguage(string languageCode)
		{
			if (!AVAILABLE_LANGUAGES.Contains(languageCode))
			{
				Plugin.Instance.PluginLogger.LogWarning("Coroner Unknown language code: " + languageCode);
				Plugin.Instance.PluginLogger.LogWarning("Coroner There may be issues loading language data.");
			}
		}

		private static void LoadLanguageData(string languageCode)
		{
			try
			{
				languageData = XDocument.Load(Plugin.AssemblyDirectory + "/Strings_" + languageCode + ".xml");
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Coroner Error loading language data: " + ex.Message);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
				if (languageCode != "en")
				{
					LoadLanguageData("en");
				}
			}
		}

		public static string GetLanguageList()
		{
			return "(" + string.Join(", ", AVAILABLE_LANGUAGES) + ")";
		}

		public static string GetValueByTag(string tag)
		{
			return languageData.Descendants(tag).FirstOrDefault()?.Attribute("text")?.Value;
		}

		public static string[] GetValuesByTag(string tag)
		{
			IEnumerable<XElement> source = languageData.Descendants(tag);
			IEnumerable<string> source2 = source.Select((XElement item) => item.Attribute("text")?.Value);
			IEnumerable<string> source3 = source2.Where((string item) => item != null);
			return source3.ToArray();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_ID = "Coroner";

		public const string PLUGIN_NAME = "Coroner";

		public const string PLUGIN_AUTHOR = "EliteMasterEric";

		public const string PLUGIN_VERSION = "1.5.3";

		public const string PLUGIN_GUID = "com.elitemastereric.coroner";
	}
	[BepInPlugin("com.elitemastereric.coroner", "Coroner", "1.5.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static readonly Random RANDOM = new Random();

		public PluginLogger PluginLogger;

		public PluginConfig PluginConfig;

		public bool IsLCAPIPresent = false;

		public static Plugin Instance { get; private set; }

		public static string AssemblyDirectory
		{
			get
			{
				string codeBase = Assembly.GetExecutingAssembly().CodeBase;
				UriBuilder uriBuilder = new UriBuilder(codeBase);
				string path = Uri.UnescapeDataString(uriBuilder.Path);
				return Path.GetDirectoryName(path);
			}
		}

		private void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Instance = this;
			PluginLogger = new PluginLogger(((BaseUnityPlugin)this).Logger, (LogLevel)16);
			Harmony val = new Harmony("com.elitemastereric.coroner");
			val.PatchAll();
			PluginLogger.LogInfo("Plugin Coroner (com.elitemastereric.coroner) is loaded!");
			LoadConfig();
			LanguageHandler.Initialize();
			QueryLCAPI();
			DeathBroadcaster.Initialize();
		}

		private void QueryLCAPI()
		{
			PluginLogger.LogInfo("Checking for LC_API...");
			if (Chainloader.PluginInfos.ContainsKey("LC_API"))
			{
				Chainloader.PluginInfos.TryGetValue("LC_API", out var value);
				if (value == null)
				{
					PluginLogger.LogError("Detected LC_API, but could not get plugin info!");
					IsLCAPIPresent = false;
				}
				else
				{
					PluginLogger.LogInfo("LCAPI is present! " + value.Metadata.GUID + ":" + value.Metadata.Version);
					IsLCAPIPresent = true;
				}
			}
			else
			{
				PluginLogger.LogInfo("LCAPI is not present.");
				IsLCAPIPresent = false;
			}
		}

		private void LoadConfig()
		{
			PluginConfig = new PluginConfig();
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
		}
	}
	public class PluginLogger
	{
		private ManualLogSource manualLogSource;

		private LogLevel logLevel;

		public PluginLogger(ManualLogSource manualLogSource, LogLevel logLevel = 16)
		{
			//IL_0010: 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)
			this.manualLogSource = manualLogSource;
			this.logLevel = logLevel;
		}

		public void LogFatal(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 1)
			{
				manualLogSource.LogFatal(data);
			}
		}

		public void LogError(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 2)
			{
				manualLogSource.LogError(data);
			}
		}

		public void LogWarning(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 4)
			{
				manualLogSource.LogWarning(data);
			}
		}

		public void LogMessage(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 8)
			{
				manualLogSource.LogMessage(data);
			}
		}

		public void LogInfo(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 16)
			{
				manualLogSource.LogInfo(data);
			}
		}

		public void LogDebug(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 32)
			{
				manualLogSource.LogDebug(data);
			}
		}
	}
	public class PluginConfig
	{
		private ConfigEntry<bool> DisplayCauseOfDeath;

		private ConfigEntry<bool> SeriousDeathMessages;

		private ConfigEntry<bool> DisplayFunnyNotes;

		private ConfigEntry<bool> DeathReplacesNotes;

		private ConfigEntry<string> LanguagePicker;

		public void BindConfig(ConfigFile _config)
		{
			DisplayCauseOfDeath = _config.Bind<bool>("General", "DisplayCauseOfDeath", true, "Display the cause of death in the player notes.");
			SeriousDeathMessages = _config.Bind<bool>("General", "SeriousDeathMessages", false, "Cause of death messages are more to-the-point.");
			DisplayFunnyNotes = _config.Bind<bool>("General", "DisplayFunnyNotes", true, "Display a random note when the player has no notes.");
			DeathReplacesNotes = _config.Bind<bool>("General", "DeathReplacesNotes", true, "True to replace notes when the player dies, false to append.");
			LanguagePicker = _config.Bind<string>("Language", "LanguagePicker", "en", "Select a language to use " + LanguageHandler.GetLanguageList());
		}

		public bool ShouldDisplayCauseOfDeath()
		{
			return DisplayCauseOfDeath.Value;
		}

		public bool ShouldUseSeriousDeathMessages()
		{
			return SeriousDeathMessages.Value;
		}

		public bool ShouldDisplayFunnyNotes()
		{
			return DisplayFunnyNotes.Value;
		}

		public bool ShouldDeathReplaceNotes()
		{
			return DeathReplacesNotes.Value;
		}

		public string GetSelectedLanguage()
		{
			return LanguagePicker.Value;
		}
	}
}
namespace Coroner.Patch
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	[HarmonyPatch("KillPlayer")]
	internal class PlayerControllerBKillPlayerPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref CauseOfDeath causeOfDeath)
		{
			try
			{
				if ((int)causeOfDeath == 300)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player died from item dropship! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Other_Dropship);
					causeOfDeath = (CauseOfDeath)8;
				}
				else if (__instance.isSinking && (int)causeOfDeath == 5)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player died of suffociation while sinking in quicksand! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Quicksand);
				}
				else if ((int)causeOfDeath != 3)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is dying! No cause of death registered in hook...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBKillPlayerPatch.Prefix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(DepositItemsDesk))]
	[HarmonyPatch("AnimationGrabPlayer")]
	internal class DepositItemsDeskAnimationGrabPlayerPatch
	{
		public static void Postfix(int playerID)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after tentacle devouring...");
				PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerID];
				Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Other_DepositItemsDesk);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in DepositItemsDeskAnimationGrabPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(JesterAI))]
	[HarmonyPatch("killPlayerAnimation")]
	internal class JesterAIKillPlayerAnimationPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Jester mauling...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Jester);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in JesterAIKillPlayerAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SandWormAI))]
	[HarmonyPatch("EatPlayer")]
	internal class SandWormAIEatPlayerPatch
	{
		public static void Postfix(PlayerControllerB playerScript)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Sand Worm devouring...");
				if ((Object)(object)playerScript == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerScript, AdvancedCauseOfDeath.Enemy_EarthLeviathan);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SandWormAIEatPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(RedLocustBees))]
	[HarmonyPatch("BeeKillPlayerOnLocalClient")]
	internal class RedLocustBeesBeeKillPlayerOnLocalClientPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Circuit Bee electrocution...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (val.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_CircuitBees);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in RedLocustBeesBeeKillPlayerOnLocalClientPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(DressGirlAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class DressGirlAIOnCollideWithPlayerPatch
	{
		public static void Postfix(DressGirlAI __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Processing Ghost Girl player collision...");
				if ((Object)(object)__instance.hauntingPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after collision!");
				}
				else if (__instance.hauntingPlayer.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance.hauntingPlayer, AdvancedCauseOfDeath.Enemy_GhostGirl);
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in DressGirlAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(FlowermanAI))]
	[HarmonyPatch("killAnimation")]
	internal class FlowermanAIKillAnimationPatch
	{
		public static void Postfix(FlowermanAI __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Bracken snapping neck...");
				if ((Object)(object)((EnemyAI)__instance).inSpecialAnimationWithPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after snapping neck!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(((EnemyAI)__instance).inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_Bracken);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in FlowermanAIKillAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ForestGiantAI))]
	[HarmonyPatch("EatPlayerAnimation")]
	internal class ForestGiantAIEatPlayerAnimationPatch
	{
		public static void Postfix(PlayerControllerB playerBeingEaten)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Forest Giant devouring...");
				if ((Object)(object)playerBeingEaten == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerBeingEaten, AdvancedCauseOfDeath.Enemy_ForestGiant);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ForestGiantAIEatPlayerAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(MouthDogAI))]
	[HarmonyPatch("KillPlayer")]
	internal class MouthDogAIKillPlayerPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after dog devouring...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_EyelessDog);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in MouthDogAIKillPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(CentipedeAI))]
	[HarmonyPatch("DamagePlayerOnIntervals")]
	internal class CentipedeAIDamagePlayerOnIntervalsPatch
	{
		public static void Postfix(CentipedeAI __instance)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Snare Flea damage...");
				if ((Object)(object)__instance.clingingToPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player being clung to!");
				}
				else if (__instance.clingingToPlayer.isPlayerDead && (int)__instance.clingingToPlayer.causeOfDeath == 5)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance.clingingToPlayer, AdvancedCauseOfDeath.Enemy_SnareFlea);
				}
				else if (__instance.clingingToPlayer.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player somehow died while attacked by Snare Flea! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in CentipedeAIDamagePlayerOnIntervalsPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(BaboonBirdAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class BaboonBirdAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Baboon Hawk damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BaboonHawk);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in BaboonBirdAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	[HarmonyPatch("DamagePlayerFromOtherClientClientRpc")]
	internal class PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch
	{
		public static void Postfix(PlayerControllerB __instance)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling friendly fire damage...");
				if ((Object)(object)__instance == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access victim after death!");
				}
				else if (__instance.isPlayerDead)
				{
					if ((int)__instance.causeOfDeath == 1)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee);
					}
					else if ((int)__instance.causeOfDeath == 6)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee);
					}
					else if ((int)__instance.causeOfDeath == 7)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Shotgun);
					}
					else
					{
						Plugin.Instance.PluginLogger.LogWarning("Player was killed by someone else but we don't know how! " + ((object)(CauseOfDeath)(ref __instance.causeOfDeath)).ToString());
					}
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(PufferAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class PufferAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Spore Lizard damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_SporeLizard);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PufferAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class SpringManAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Coil Head damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_CoilHead);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SpringManAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(BlobAI))]
	[HarmonyPatch("SlimeKillPlayerEffectServerRpc")]
	internal class BlobAISlimeKillPlayerEffectServerRpcPatch
	{
		public static void Postfix(int playerKilled)
		{
			try
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerKilled];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (val.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Hygrodere);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in BlobAISlimeKillPlayerEffectServerRpcPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(HoarderBugAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class HoarderBugAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Hoarder Bug damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_HoarderBug);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HoarderBugAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(CrawlerAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class CrawlerAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Thumper damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_Thumper);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in CrawlerAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SandSpiderAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class SandSpiderAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Bunker Spider damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BunkerSpider);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SandSpiderAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(NutcrackerEnemyAI))]
	[HarmonyPatch("LegKickPlayer")]
	internal class NutcrackerEnemyAILegKickPlayerPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Nutcracker kicked a player to death!");
				PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerId];
				Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in NutcrackerEnemyAILegKickPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ShotgunItem))]
	[HarmonyPatch("ShootGun")]
	internal class ShotgunItemShootGunPatch
	{
		public static void Postfix(ShotgunItem __instance)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling shotgun shot...");
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if ((Object)(object)localPlayerController == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access local player after shotgun shot!");
				}
				else if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7)
				{
					if (((GrabbableObject)__instance).isHeldByEnemy)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Shot);
					}
					else
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Player_Murder_Shotgun);
					}
				}
				else if (localPlayerController.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogWarning("Player died while attacked by shotgun? Skipping... " + ((object)(CauseOfDeath)(ref localPlayerController.causeOfDeath)).ToString());
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ShotgunItemShootGunPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	[HarmonyPatch("killAnimation")]
	internal class MaskedPlayerEnemykillAnimationPatch
	{
		public static void Postfix(MaskedPlayerEnemy __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone...");
				PlayerControllerB inSpecialAnimationWithPlayer = ((EnemyAI)__instance).inSpecialAnimationWithPlayer;
				if ((Object)(object)inSpecialAnimationWithPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in MaskedPlayerEnemykillAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(HauntedMaskItem))]
	[HarmonyPatch("FinishAttaching")]
	internal class HauntedMaskItemFinishAttachingPatch
	{
		public static void Postfix(HauntedMaskItem __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone...");
				PlayerControllerB value = Traverse.Create((object)__instance).Field("previousPlayerHeldBy").GetValue<PlayerControllerB>();
				if ((Object)(object)value == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (value.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(value, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HauntedMaskItemFinishAttachingPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ExtensionLadderItem))]
	[HarmonyPatch("StartLadderAnimation")]
	internal class ExtensionLadderItemStartLadderAnimationPatch
	{
		public static void Postfix(ExtensionLadderItem __instance)
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Extension ladder started animation! Modifying kill trigger...");
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ExtensionLadderItem.");
				}
				Transform val = gameObject.transform.Find("AnimContainer/MeshContainer/LadderMeshContainer/BaseLadder/LadderSecondPart/KillTrigger");
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ExtensionLadderItem.");
				}
				GameObject gameObject2 = ((Component)val).gameObject;
				if ((Object)(object)gameObject2 == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ExtensionLadderItem.");
				}
				KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject.");
				}
				component.causeOfDeath = (CauseOfDeath)8;
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ExtensionLadderItemStartLadderAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ItemDropship))]
	[HarmonyPatch("Start")]
	internal class ItemDropshipStartPatch
	{
		public static void Postfix(ItemDropship __instance)
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Item dropship spawned! Modifying kill trigger...");
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ItemDropship.");
				}
				Transform val = gameObject.transform.Find("ItemShip/KillTrigger");
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ItemDropship.");
				}
				GameObject gameObject2 = ((Component)val).gameObject;
				if ((Object)(object)gameObject2 == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ItemDropship.");
				}
				KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject.");
				}
				component.causeOfDeath = (CauseOfDeath)300;
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ItemDropshipStartPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(Turret))]
	[HarmonyPatch("Update")]
	public class TurretUpdatePatch
	{
		public static void Postfix(Turret __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			if ((int)__instance.turretMode == 2)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Other_Turret);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Landmine))]
	[HarmonyPatch("SpawnExplosion")]
	public class LandmineSpawnExplosionPatch
	{
		private const string KILL_PLAYER_SIGNATURE = "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)";

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			List<CodeInstruction> list2 = BuildInstructionsToInsert(method);
			if (list2 == null)
			{
				Plugin.Instance.PluginLogger.LogError("Could not build instructions to insert in LandmineSpawnExplosionPatch! Safely aborting...");
				return instructions;
			}
			int num = -1;
			for (int i = 0; i < list.Count; i++)
			{
				CodeInstruction val = list[i];
				if (val.opcode == OpCodes.Callvirt && val.operand.ToString() == "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)")
				{
					num = i;
					break;
				}
			}
			if (num == -1)
			{
				Plugin.Instance.PluginLogger.LogError("Could not find PlayerControllerB.KillPlayer call in LandmineSpawnExplosionPatch! Safely aborting...");
				return instructions;
			}
			Plugin.Instance.PluginLogger.LogInfo("Injecting patch into Landmine.SpawnExplosion...");
			list.InsertRange(num, list2);
			Plugin.Instance.PluginLogger.LogInfo("Done.");
			return list;
		}

		private static List<CodeInstruction> BuildInstructionsToInsert(MethodBase method)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 2;
			IList<LocalVariableInfo> localVariables = method.GetMethodBody().LocalVariables;
			LocalVariableInfo localVariableInfo = null;
			for (int i = 0; i < localVariables.Count; i++)
			{
				LocalVariableInfo localVariableInfo2 = localVariables[i];
				if (localVariableInfo2.LocalType == typeof(PlayerControllerB))
				{
					if (localVariableInfo != null)
					{
						Plugin.Instance.PluginLogger.LogError("Found multiple PlayerControllerB local variables in LandmineSpawnExplosionPatch!");
						return null;
					}
					localVariableInfo = localVariableInfo2;
					break;
				}
			}
			list.Add(new CodeInstruction(OpCodes.Ldloc_S, (object)localVariableInfo.LocalIndex));
			list.Add(new CodeInstruction(OpCodes.Ldarg, (object)num));
			list.Add(new CodeInstruction(OpCodes.Call, (object)typeof(LandmineSpawnExplosionPatch).GetMethod("RewriteCauseOfDeath")));
			return list;
		}

		public static void RewriteCauseOfDeath(PlayerControllerB targetPlayer, float killRange)
		{
			AdvancedCauseOfDeath causeOfDeath = AdvancedCauseOfDeath.Blast;
			if (killRange == 5f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Player_Jetpack_Blast;
			}
			else if (killRange == 5.7f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Other_Landmine;
			}
			else if (killRange == 2.4f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Other_Lightning;
			}
			AdvancedDeathTracker.SetCauseOfDeath(targetPlayer, causeOfDeath);
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	[HarmonyPatch("FillEndGameStats")]
	internal class HUDManagerFillEndGameStatsPatch
	{
		private const string EMPTY_NOTES = "Notes: \n";

		public static void Postfix(HUDManager __instance)
		{
			try
			{
				OverridePerformanceReport(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HUDManagerFillEndGameStatsPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}

		private static Random BuildSyncedRandom()
		{
			int randomMapSeed = StartOfRound.Instance.randomMapSeed;
			Plugin.Instance.PluginLogger.LogDebug("Syncing randomization to map seed: '" + randomMapSeed + "'");
			return new Random(randomMapSeed);
		}

		private static void OverridePerformanceReport(HUDManager __instance)
		{
			Plugin.Instance.PluginLogger.LogDebug("Applying Coroner patches to player notes...");
			Random random = BuildSyncedRandom();
			for (int i = 0; i < __instance.statsUIElements.playerNotesText.Length; i++)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[i];
				if (!val.disconnectedMidGame && !val.isPlayerDead && !val.isPlayerControlled)
				{
					Plugin.Instance.PluginLogger.LogInfo("Player " + i + " is not controlled by a player. Skipping...");
					continue;
				}
				TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i];
				if (val.isPlayerDead)
				{
					if (Plugin.Instance.PluginConfig.ShouldDisplayCauseOfDeath())
					{
						if (Plugin.Instance.PluginConfig.ShouldDeathReplaceNotes())
						{
							Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Replacing notes with Cause of Death...");
							((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UICauseOfDeath") + "\n";
						}
						else
						{
							Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Appending notes with Cause of Death...");
						}
						AdvancedCauseOfDeath causeOfDeath = AdvancedDeathTracker.GetCauseOfDeath(val);
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(causeOfDeath, random) + "\n";
					}
					else
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead, but Config says leave it be...");
					}
				}
				else if (((TMP_Text)val2).text == "Notes: \n")
				{
					if (Plugin.Instance.PluginConfig.ShouldDisplayFunnyNotes())
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes! Injecting something funny...");
						((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UINotes") + "\n";
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(null, random) + "\n";
					}
					else
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes, but Config says leave it be...");
					}
				}
				else
				{
					Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has notes, don't override them...");
				}
			}
			AdvancedDeathTracker.ClearDeathTracker();
		}
	}
}
namespace Coroner.LCAPI
{
	internal class DeathBroadcasterLCAPI
	{
		private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death";

		public static void Initialize()
		{
			Plugin.Instance.PluginLogger.LogDebug("Initializing DeathBroadcaster...");
			if (Plugin.Instance.IsLCAPIPresent)
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Registering signature...");
				Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(OnBroadcastString));
			}
			else
			{
				Plugin.Instance.PluginLogger.LogError("LC_API is not present! Why did you try to register the DeathBroadcaster?");
			}
		}

		private static void OnBroadcastString(string data, string signature)
		{
			if (signature == "com.elitemastereric.coroner.death")
			{
				Plugin.Instance.PluginLogger.LogDebug("Broadcast has been received from LC_API!");
				string[] array = data.Split('|');
				int playerIndex = int.Parse(array[0]);
				int num = int.Parse(array[1]);
				AdvancedCauseOfDeath advancedCauseOfDeath = (AdvancedCauseOfDeath)num;
				Plugin.Instance.PluginLogger.LogDebug("Player " + playerIndex + " died of " + AdvancedDeathTracker.StringifyCauseOfDeath((AdvancedCauseOfDeath?)advancedCauseOfDeath));
				AdvancedDeathTracker.SetCauseOfDeath(playerIndex, advancedCauseOfDeath, broadcast: false);
			}
		}

		public static void AttemptBroadcast(string data, string signature)
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Broadcasting...");
				Networking.Broadcast(data, signature);
			}
			else
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is not present! Skipping broadcast...");
			}
		}
	}
}

plugins/Quality of life/red_eye-LethalAutocomplete-0.4.1/LethalAutocomplete.dll

Decompiled 10 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.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using Newtonsoft.Json;
using TerminalApi;
using TerminalApi.Events;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LethalAutocomplete")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalAutocomplete")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("B5A3A159-6BFF-43BE-840B-173ABE0E1D7F")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LethalAutocomplete;

public class WordNode
{
	public string Word { get; set; }

	public List<WordNode> Children { get; set; }

	public int Weight { get; set; }

	public WordNode(string word, int weight)
	{
		Word = word;
		Weight = weight;
		Children = new List<WordNode>();
	}

	public List<WordNode> FindMatchingWords(string[] inputs)
	{
		List<WordNode> list = new List<WordNode>();
		if (inputs.Length == 0 || Word.ToLower().StartsWith(inputs[0].ToLower()))
		{
			if (inputs.Length == 1)
			{
				list.Add(this);
			}
			else
			{
				foreach (WordNode child in Children)
				{
					list.AddRange(child.FindMatchingWords(inputs.Skip(1).ToArray()));
				}
			}
		}
		return list;
	}
}
public class Autocomplete
{
	private List<WordNode> _words;

	public static ManualLogSource Logger;

	private readonly int _defaultWeight = 10;

	public Autocomplete()
	{
		_words = new List<WordNode>();
	}

	public void Insert(TerminalKeyword terminalKeyword)
	{
		string name = ((Object)terminalKeyword).name;
		if (ContainsWord(name))
		{
			return;
		}
		WordNode wordNode = new WordNode(name, _defaultWeight);
		for (int i = 0; i < terminalKeyword.compatibleNouns.Length; i++)
		{
			string text = "";
			text = ((!new string[2] { "route", "info" }.Any(name.ToLower().Contains)) ? ((object)terminalKeyword.compatibleNouns[i].noun).ToString().Split(new char[1] { ' ' })[0] : terminalKeyword.compatibleNouns[i].noun.word);
			WordNode wordNode2 = new WordNode(text, _defaultWeight);
			if (name.ToLower() == "buy")
			{
				for (int j = 1; j < 10; j++)
				{
					wordNode2.Children.Add(new WordNode(j.ToString(), 10 - j));
				}
			}
			wordNode.Children.Add(wordNode2);
		}
		_words.Add(wordNode);
	}

	private bool ContainsWord(string word)
	{
		return _words.Any((WordNode node) => node.Word == word);
	}

	public List<string> GetAutocomplete(string input)
	{
		try
		{
			string[] array = input.Split(new char[1] { ' ' });
			List<WordNode> list = new List<WordNode>();
			string matching_start = "";
			for (int i = 0; i < array.Length - 1; i++)
			{
				matching_start = matching_start + array[i] + " ";
			}
			foreach (WordNode word in _words)
			{
				list.AddRange(word.FindMatchingWords(array));
			}
			list = (from n in list.Distinct()
				where n.Weight > 0
				orderby n.Weight descending
				select n).ToList();
			return list.Select((WordNode n) => matching_start + n.Word).ToList();
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on autocomplete search. Error: {arg}");
			return null;
		}
	}

	public List<WordNode> GetWords()
	{
		return _words;
	}

	public void SetWords(List<WordNode> words)
	{
		_words = new List<WordNode>(words);
	}
}
internal class AutocompleteManager
{
	private class SaveData
	{
		public List<WordNode> Words { get; set; }

		public Dictionary<string, List<string>> History { get; set; }
	}

	public static Keybinds keybinds;

	public static string saveFilePath = "";

	public static string autocompleteKey = "<Keyboard>/tab";

	public static string historyNextKey = "<Keyboard>/upArrow";

	public static string historyPrevKey = "<Keyboard>/downArrow";

	public static bool saveHistory = true;

	public static int historyMaxCount = 20;

	public bool exited;

	private Terminal _terminal;

	private string _input;

	private List<string> _terminalCommands;

	private List<string> _commandsHistory;

	private int _historyIndex;

	private string _lastAutocomplete = "";

	private bool _startedAutocomplete;

	private List<string> _autocompleteOptions;

	private int _autocompleteOptionIndex;

	public static ManualLogSource Logger;

	private Autocomplete _autocomplete;

	public void Awake()
	{
		if (Plugin.IsDebug)
		{
			Logger.LogInfo((object)("Lethal Autocomplete Plugin is loaded! Autocomplete Key: " + autocompleteKey));
		}
		_terminalCommands = new List<string>();
		_commandsHistory = new List<string>();
		_autocomplete = new Autocomplete();
		Autocomplete.Logger = Logger;
		LoadFromJson();
		SetupTerminalCallbacks();
	}

	private void OnTerminalTextChanged(object sender, TerminalTextChangedEventArgs e)
	{
		try
		{
			_input = TerminalApi.GetTerminalInput();
			_input = _input.Replace("\n", "");
			if (Plugin.IsDebug)
			{
				Logger.LogMessage((object)("OnTerminalTextChanged: " + _input));
			}
			if (_input != _lastAutocomplete)
			{
				ResetAutocomplete();
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"On terminal text changed event. Error: {arg}");
		}
	}

	private void OnTerminalExit(object sender, TerminalEventArgs e)
	{
		if (Plugin.IsDebug)
		{
			Logger.LogMessage((object)"Terminal Exited");
		}
		if (!saveHistory)
		{
			_commandsHistory = new List<string>();
		}
		try
		{
			RemoveKeybindCallbacks();
			SaveToJson();
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"On terminal exit. Error: {arg}");
		}
	}

	private void TerminalIsStarting(object sender, TerminalEventArgs e)
	{
		try
		{
			if (Plugin.IsDebug)
			{
				Logger.LogMessage((object)"Terminal is starting");
			}
			_terminal = TerminalApi.Terminal;
			if (autocompleteKey.Contains("tab"))
			{
				RemoveTerminalExitBinding();
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"On terminal starting. Error: {arg}");
		}
	}

	private void RemoveTerminalExitBinding()
	{
		//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_004b: 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)
		try
		{
			MovementActions movement = _terminal.playerActions.Movement;
			InputAction openMenu = ((MovementActions)(ref movement)).OpenMenu;
			if (Plugin.IsDebug)
			{
				Logger.LogMessage((object)(openMenu.name + " " + InputActionRebindingExtensions.GetBindingDisplayString(openMenu, (DisplayStringOptions)0, (string)null)));
			}
			openMenu.Disable();
			InputBinding val = default(InputBinding);
			((InputBinding)(ref val)).path = "<Keyboard>/tab";
			((InputBinding)(ref val)).overridePath = "";
			InputActionRebindingExtensions.ApplyBindingOverride(openMenu, val);
			openMenu.Enable();
			if (Plugin.IsDebug)
			{
				Logger.LogMessage((object)(openMenu.name + " " + InputActionRebindingExtensions.GetBindingDisplayString(openMenu, (DisplayStringOptions)0, (string)null)));
			}
		}
		catch (Exception ex)
		{
			Logger.LogWarning((object)"Remove terminal tab exit binded key");
			Logger.LogError((object)ex);
			throw;
		}
	}

	private void TerminalIsStarted(object sender, TerminalEventArgs e)
	{
		try
		{
			if (Plugin.IsDebug)
			{
				Logger.LogMessage((object)"Terminal is started");
			}
			_terminalCommands.Clear();
			for (int i = 0; i < _terminal.terminalNodes.allKeywords.Length; i++)
			{
				_autocomplete.Insert(_terminal.terminalNodes.allKeywords[i]);
			}
		}
		catch (Exception ex)
		{
			Logger.LogWarning((object)"Terminal is started");
			Logger.LogError((object)ex);
			throw;
		}
	}

	private void TextSubmitted(object sender, TerminalParseSentenceEventArgs e)
	{
		if (Plugin.IsDebug)
		{
			Logger.LogMessage((object)("TextSubmitted: " + _input));
		}
		try
		{
			if (e.SubmittedText != "")
			{
				if (_commandsHistory.Count + 1 > historyMaxCount)
				{
					_commandsHistory.RemoveAt(0);
				}
				_commandsHistory.Add(e.SubmittedText);
				_historyIndex = _commandsHistory.Count;
			}
			_input = "";
			ResetAutocomplete();
		}
		catch (Exception ex)
		{
			Logger.LogWarning((object)$"Text submitted: {e.SubmittedText} Node Returned: {e.ReturnedNode}");
			Logger.LogError((object)ex);
		}
	}

	private void OnBeginUsing(object sender, TerminalEventArgs e)
	{
		Logger.LogMessage((object)"Player has just started using the terminal");
		SetupKeybindCallbacks();
	}

	private void OnBeganUsing(object sender, TerminalEventArgs e)
	{
		if (autocompleteKey.Contains("tab"))
		{
			HUDManager.Instance.ChangeControlTip(0, "Quit terminal : [Esc]", true);
		}
	}

	private void SetupTerminalCallbacks()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Expected O, but got Unknown
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		Events.TerminalStarting += new TerminalEventHandler(TerminalIsStarting);
		Events.TerminalStarted += new TerminalEventHandler(TerminalIsStarted);
		Events.TerminalParsedSentence += new TerminalParseSentenceEventHandler(TextSubmitted);
		Events.TerminalBeginUsing += new TerminalEventHandler(OnBeginUsing);
		Events.TerminalBeganUsing += new TerminalEventHandler(OnBeganUsing);
		Events.TerminalExited += new TerminalEventHandler(OnTerminalExit);
		Events.TerminalTextChanged += new TerminalTextChangedEventHandler(OnTerminalTextChanged);
	}

	private void SetupKeybindCallbacks()
	{
		Logger.LogMessage((object)"Setup Keybind Callbacks");
		keybinds.AutocompleteAction.performed += OnAutocompleteKey;
		keybinds.HistoryNextAction.performed += OnHistoryNextKey;
		keybinds.HistoryPrevAction.performed += OnHistoryPrevKey;
	}

	private void RemoveKeybindCallbacks()
	{
		Logger.LogMessage((object)"Remove Keybind Callbacks");
		keybinds.AutocompleteAction.performed -= OnAutocompleteKey;
		keybinds.HistoryNextAction.performed -= OnHistoryNextKey;
		keybinds.HistoryPrevAction.performed -= OnHistoryPrevKey;
	}

	private void OnHistoryNextKey(CallbackContext ctx)
	{
		TerminalApi.SetTerminalInput("");
		try
		{
			if (_commandsHistory.Count >= 1 && _historyIndex >= 1)
			{
				_historyIndex--;
				TerminalApi.SetTerminalInput(_commandsHistory[_historyIndex]);
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on history next key performed. Error: {arg}");
			Logger.LogInfo((object)$"_commandsHistory.Count={_commandsHistory.Count}");
			Logger.LogInfo((object)$"historyIndex={_historyIndex}");
		}
	}

	private void OnHistoryPrevKey(CallbackContext ctx)
	{
		TerminalApi.SetTerminalInput("");
		try
		{
			if (_commandsHistory.Count >= 1)
			{
				if (_historyIndex + 1 >= _commandsHistory.Count)
				{
					_historyIndex = _commandsHistory.Count;
					TerminalApi.SetTerminalInput("");
					Logger.LogInfo((object)("INPUT: " + TerminalApi.GetTerminalInput()));
				}
				else
				{
					_historyIndex++;
					TerminalApi.SetTerminalInput(_commandsHistory[_historyIndex]);
				}
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on history prev key performed. Error: {arg}");
			Logger.LogInfo((object)$"_commandsHistory.Count={_commandsHistory.Count}");
			Logger.LogInfo((object)$"historyIndex={_historyIndex}");
		}
	}

	private void OnAutocompleteKey(CallbackContext ctx)
	{
		try
		{
			if (_startedAutocomplete)
			{
				NextAutocomplete();
			}
			else
			{
				StartAutocomplete();
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on autocomplete key performed. Error: {arg}");
			Logger.LogInfo((object)$"_startedAutocomplete={_startedAutocomplete}");
		}
	}

	private void StartAutocomplete()
	{
		try
		{
			List<string> autocomplete = _autocomplete.GetAutocomplete(_input);
			if (Plugin.IsDebug)
			{
				Logger.LogInfo((object)"Autocomplete options:");
				foreach (string item in autocomplete)
				{
					Logger.LogInfo((object)(item ?? ""));
				}
			}
			if (autocomplete != null && autocomplete.Count > 0)
			{
				_autocompleteOptions = new List<string>(autocomplete);
				_startedAutocomplete = true;
				_lastAutocomplete = _autocompleteOptions.First();
				Logger.LogMessage((object)("Set Autocomplete " + _lastAutocomplete));
				TerminalApi.SetTerminalInput(_lastAutocomplete);
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on autocomplete new options search. Error: {arg}");
		}
	}

	private void NextAutocomplete()
	{
		try
		{
			if (Plugin.IsDebug)
			{
				Logger.LogInfo((object)"Autocomplete Options:");
				for (int i = 0; i < _autocompleteOptions.Count; i++)
				{
					Logger.LogInfo((object)_autocompleteOptions[i]);
				}
				Logger.LogInfo((object)$"Autocomplete Index: {_autocompleteOptionIndex + 1}");
			}
			_autocompleteOptionIndex++;
			if (_autocompleteOptionIndex >= _autocompleteOptions.Count)
			{
				_autocompleteOptionIndex = 0;
			}
			_lastAutocomplete = _autocompleteOptions[_autocompleteOptionIndex];
			TerminalApi.SetTerminalInput(_lastAutocomplete);
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on autocomplete next options search. Error: {arg}");
		}
	}

	private void ResetAutocomplete()
	{
		try
		{
			if (Plugin.IsDebug)
			{
				Logger.LogInfo((object)"Reset autocomplete state");
			}
			_startedAutocomplete = false;
			_autocompleteOptionIndex = 0;
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on autocomplete reset. Error: {arg}");
		}
	}

	public void SaveToJson()
	{
		string contents = JsonConvert.SerializeObject((object)new
		{
			Words = _autocomplete.GetWords(),
			History = new Dictionary<string, List<string>> { ["value"] = _commandsHistory }
		}, (Formatting)1);
		File.WriteAllText(saveFilePath, contents);
	}

	private void LoadFromJson()
	{
		try
		{
			if (!File.Exists(saveFilePath))
			{
				return;
			}
			string text = File.ReadAllText(saveFilePath);
			if (!string.IsNullOrEmpty(text))
			{
				SaveData saveData = JsonConvert.DeserializeObject<SaveData>(text);
				_commandsHistory = new List<string>(saveData.History["value"]);
				_historyIndex = _commandsHistory.Count;
				for (int i = 0; i < _commandsHistory.Count; i++)
				{
					Logger.LogInfo((object)_commandsHistory[i]);
				}
				Logger.LogInfo((object)$"_historyIndex={_historyIndex}");
				_autocomplete.SetWords(saveData.Words);
				Logger.LogMessage((object)"Loaded save from JSON!");
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"Failed on loading json save file. Error: {arg}");
		}
	}
}
internal class Keybinds : LcInputActions
{
	public InputAction AutocompleteAction => ((LcInputActions)this).Asset["Autocomplete"];

	public InputAction HistoryNextAction => ((LcInputActions)this).Asset["HistoryNext"];

	public InputAction HistoryPrevAction => ((LcInputActions)this).Asset["HistoryPrev"];

	public override void CreateInputActions(in InputActionMapBuilder builder)
	{
		((LcInputActions)this).CreateInputActions(ref builder);
		builder.NewActionBinding().WithActionId("Autocomplete").WithActionType((InputActionType)1)
			.WithKbmPath(AutocompleteManager.autocompleteKey)
			.WithBindingName("Autocomplete Key")
			.Finish();
		builder.NewActionBinding().WithActionId("HistoryNext").WithActionType((InputActionType)1)
			.WithKbmPath(AutocompleteManager.historyNextKey)
			.WithBindingName("HistoryNext Key")
			.Finish();
		builder.NewActionBinding().WithActionId("HistoryPrev").WithActionType((InputActionType)1)
			.WithKbmPath(AutocompleteManager.historyPrevKey)
			.WithBindingName("HistoryPrev Key")
			.Finish();
	}
}
[BepInPlugin("redeye.lethalautocomplete", "Lethal Autocomplete", "0.4.1")]
[BepInDependency("atomic.terminalapi", "1.3.0")]
[BepInDependency("com.rune580.LethalCompanyInputUtils", "0.4.2")]
public class Plugin : BaseUnityPlugin
{
	private const string _GUID = "redeye.lethalautocomplete";

	private const string _Name = "Lethal Autocomplete";

	private const string _Version = "0.4.1";

	public static bool IsDebug;

	private AutocompleteManager _autocomplete;

	public string PluginPath = "";

	private void Awake()
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Lethal Autocomplete Plugin is loaded!");
		Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		try
		{
			PluginPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)ex);
		}
		try
		{
			_autocomplete = new AutocompleteManager();
			AutocompleteManager.Logger = ((BaseUnityPlugin)this).Logger;
			ConfigFile();
			AutocompleteManager.keybinds = new Keybinds();
			_autocomplete.Awake();
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)ex2);
		}
	}

	private void OnApplicationQuit()
	{
		_autocomplete.SaveToJson();
	}

	private void ConfigFile()
	{
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Expected O, but got Unknown
		string path = "save.json";
		string text = Path.Combine(PluginPath, path);
		string text2 = ((BaseUnityPlugin)this).Config.Bind<string>("Basic", "Save Data Path", "", "Absolute path to the json file with autocomplete words and commands history. By default save.json generated in plugins/red_eye-LethalAutocomplete folder.").Value;
		if (!File.Exists(text2) && text2 != "")
		{
			text2 = text;
			((BaseUnityPlugin)this).Config.Remove(new ConfigDefinition("Basic", "Save Data Path"));
			((BaseUnityPlugin)this).Config.Bind<string>("Basic", "Save Data Path", text, "Absolute path to the json file with autocomplete words and commands history. By default save.json generated in plugins/red_eye-LethalAutocomplete folder.");
			((BaseUnityPlugin)this).Logger.LogWarning((object)"The save file wasn't found in the directory specified by the configuration file! Using default path.");
		}
		AutocompleteManager.saveFilePath = ((text2 == "") ? text : text2);
		ConfigEntry<string> val = ((BaseUnityPlugin)this).Config.Bind<string>("Keyboard Bindings", "Autocomplete", "<Keyboard>/tab", "Get autocomplete for current input");
		AutocompleteManager.autocompleteKey = (val.Value.ToLower().StartsWith("<keyboard>") ? val.Value : ("<Keyboard>/" + val.Value));
		ConfigEntry<string> val2 = ((BaseUnityPlugin)this).Config.Bind<string>("Keyboard Bindings", "History Next", "<Keyboard>/upArrow", "Get current terminal session next command");
		AutocompleteManager.historyNextKey = (val2.Value.ToLower().StartsWith("<keyboard>") ? val2.Value : ("<Keyboard>/" + val2.Value));
		ConfigEntry<string> val3 = ((BaseUnityPlugin)this).Config.Bind<string>("Keyboard Bindings", "History Prev", "<Keyboard>/downArrow", "Get current terminal session prev command");
		AutocompleteManager.historyPrevKey = (val3.Value.ToLower().StartsWith("<keyboard>") ? val3.Value : ("<Keyboard>/" + val3.Value));
		AutocompleteManager.saveHistory = ((BaseUnityPlugin)this).Config.Bind<bool>("History", "Save History", true, "Regulates if the history be saved after the re-entry").Value;
		AutocompleteManager.historyMaxCount = ((BaseUnityPlugin)this).Config.Bind<int>("History", "Buffer Length", 20, "Max amount of commands to remember during terminal session").Value;
		IsDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Debug", false, "").Value;
	}
}

plugins/Quality of life/NutNutty-AlwaysPickup-1.2.0/AlwaysPickup.dll

Decompiled 10 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;

[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.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("AlwaysPickup")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AlwaysPickup")]
[assembly: AssemblyTitle("AlwaysPickup")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AlwaysPickup;

[BepInPlugin("NutNutty.AlwaysPickup", "Always Pickup", "1.0.0")]
public class AlwaysPickup : BaseUnityPlugin
{
	public void Awake()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		new Harmony("AlwaysPickup").PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Always Pickup plugin loaded!");
	}
}
[HarmonyPatch(typeof(GrabbableObject))]
public class GrabbableObjectPatch
{
	[HarmonyTranspiler]
	[HarmonyPatch("Start")]
	private static IEnumerable<CodeInstruction> TranspileGrabbableObject(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0003: 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_0027: Expected O, but got Unknown
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Expected O, but got Unknown
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, Array.Empty<CodeMatch>()).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[4]
		{
			new CodeInstruction(OpCodes.Ldarg_0, (object)null),
			new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.Field(typeof(GrabbableObject), "itemProperties")),
			new CodeInstruction(OpCodes.Ldc_I4_1, (object)null),
			new CodeInstruction(OpCodes.Stfld, (object)AccessTools.Field(typeof(Item), "canBeGrabbedBeforeGameStart"))
		}).InstructionEnumeration();
	}
}

plugins/Quality of life/PopleZoo-BetterItemScan-3.0.0/BetterItemScan.dll

Decompiled 10 months ago
using System;
using System.Collections;
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 System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
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("BetterItemScan")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BetterItemScan")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("04cd6816-7aba-4c14-a9a7-bf328df25692")]
[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 BetterItemScan
{
	[BepInPlugin("PopleZoo.BetterItemScan", "Better Item Scan", "2.1.0.0")]
	public class BetterItemScanModBase : BaseUnityPlugin
	{
		private const string modGUID = "PopleZoo.BetterItemScan";

		private const string modName = "Better Item Scan";

		private const string modVersion = "2.1.0.0";

		private readonly Harmony harmony = new Harmony("PopleZoo.BetterItemScan");

		public static BetterItemScanModBase Instance;

		public ManualLogSource mls;

		public static ConfigEntry<float> ItemScanRadius;

		public static ConfigEntry<float> AdjustScreenPositionXaxis;

		public static ConfigEntry<float> AdjustScreenPositionYaxis;

		public static ConfigEntry<float> ItemScaningUICooldown;

		public static ConfigEntry<float> FontSize;

		public static ConfigEntry<bool> ShowDebugMode;

		public static ConfigEntry<bool> ShowShipTotalOnShipOnly;

		public static ConfigEntry<bool> ShowTotalOnShipOnly;

		public static ConfigEntry<bool> CalculateForQuota;

		public static ConfigEntry<string> ItemTextColorHex;

		public static ConfigEntry<string> ItemTextCalculatorColorHex;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("PopleZoo.BetterItemScan");
			mls.LogInfo((object)"Plugin BetterItemScan is loaded!");
			LoadConfigs();
			harmony.PatchAll();
		}

		private void LoadConfigs()
		{
			ShowDebugMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "ShowDebugMode", false, "Shows the change in width of the area to scan");
			ShowShipTotalOnShipOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "ShowShipTotalOnShipOnly", false, "Whether or not to show the ship's total only in the ship");
			ShowTotalOnShipOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "ShowTotalOnShipOnly", false, "Whether or not to show the total scanned in the ship only");
			CalculateForQuota = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "CalculateForQuota", true, "Whether or not to calculate scanned items to see which meet the quota and if any do");
			ItemScanRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "ItemScanRadius", 20f, "The default width is 20");
			FontSize = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "FontSize", 20f, "The default font size is 20, to make/see this change you may have to do this manually in the config file itself in the bepinex folder");
			ItemTextColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "ItemTextColorHex", "#78FFAE", "The default text color for items that have been scanned, value must be a hexadecimal");
			ItemTextCalculatorColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "ItemTextCalculatorColorHex", "#FF3333", "The default text color for items that meet the criteria, value must be a hexadecimal");
			ItemScaningUICooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "ItemScaningUICooldown", 3f, "The default value is 5f, how long the ui stays on screen");
			AdjustScreenPositionXaxis = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "AdjustScreenPositionXaxis", 0f, "The default value is 0, you will add or take away from its original position");
			AdjustScreenPositionYaxis = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "AdjustScreenPositionYaxis", 0f, "The default value is 0, you will add or take away from its original position");
		}
	}
}
namespace BetterItemScan.Patches
{
	[HarmonyPatch]
	internal class HudManagerPatch_UI
	{
		private static GameObject _totalCounter;

		private static TextMeshProUGUI _textMesh;

		private static float _displayTimeLeft = BetterItemScanModBase.ItemScaningUICooldown.Value;

		private static float Totalsum = 0f;

		private static float Totalship = 0f;

		public static List<ScanNodeProperties> scannedNodeObjects = new List<ScanNodeProperties>();

		public static Dictionary<string, (float, int)> meetQuotaItemNames = new Dictionary<string, (float, int)>();

		public static Dictionary<string, (float, int)> NotmeetQuotaItemNames = new Dictionary<string, (float, int)>();

		public static Dictionary<ScanNodeProperties, int> ItemsDictionary = new Dictionary<ScanNodeProperties, int>();

		private static List<ScanNodeProperties> items;

		public static int MeetQuota(List<int> items, int quota)
		{
			items = items.Where((int item) => item >= quota).ToList();
			if (!items.Any())
			{
				return -1;
			}
			return items.Aggregate((int a, int b) => (Math.Abs(quota - a) < Math.Abs(quota - b)) ? a : b);
		}

		public static List<List<int>> FindCombinations(List<int> items, int quota)
		{
			List<List<int>> list = new List<List<int>>();
			int count = items.Count;
			int num = int.MaxValue;
			for (int i = 0; i < 1 << count; i++)
			{
				List<int> list2 = new List<int>();
				for (int j = 0; j < count; j++)
				{
					if ((i & (1 << j)) > 0)
					{
						list2.Add(items[j]);
					}
				}
				int num2 = list2.Sum();
				int num3 = Math.Abs(quota - num2);
				if (num3 < num)
				{
					num = num3;
					list.Clear();
					list.Add(list2);
				}
				else if (num3 == num)
				{
					list.Add(list2);
				}
			}
			list.Sort((List<int> a, List<int> b) => a.Count.CompareTo(b.Count));
			return list;
		}

		private static bool IsHexColor(string value)
		{
			string pattern = "^#(?:[0-9a-fA-F]{3}){1,2}$";
			return Regex.IsMatch(value, pattern);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		private static void OnScan(HUDManager __instance, CallbackContext context)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			Debug.Log((object)"Scan initiated!");
			FieldInfo field = typeof(HUDManager).GetField("playerPingingScan", BindingFlags.Instance | BindingFlags.NonPublic);
			float num = (float)field.GetValue(__instance);
			MethodInfo method = typeof(HUDManager).GetMethod("CanPlayerScan", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || !((CallbackContext)(ref context)).performed || !(bool)method.Invoke(__instance, null) || (double)num > -1.0)
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)_totalCounter))
			{
				CopyValueCounter();
			}
			if (!Object.op_Implicit((Object)(object)_textMesh))
			{
				_textMesh = new TextMeshProUGUI();
			}
			meetQuotaItemNames.Clear();
			NotmeetQuotaItemNames.Clear();
			items = CalculateLootItems();
			foreach (ScanNodeProperties item in items)
			{
				ItemsDictionary.Add(item, item.scrapValue);
			}
			int num2 = TimeOfDay.Instance.profitQuota - TimeOfDay.Instance.quotaFulfilled;
			List<int> list = ItemsDictionary.Values.ToList();
			list.Sort();
			list.Reverse();
			int bestIndividualItem = MeetQuota(list, num2);
			List<List<int>> source = FindCombinations(list, num2);
			if (source.Any())
			{
				int num3 = source.First().Sum();
				if (Math.Abs(num2 - bestIndividualItem) <= Math.Abs(num2 - num3))
				{
					if (bestIndividualItem != -1)
					{
						ScanNodeProperties key = ItemsDictionary.FirstOrDefault((KeyValuePair<ScanNodeProperties, int> x) => x.Value == bestIndividualItem).Key;
						if ((Object)(object)key != (Object)null)
						{
							if (!meetQuotaItemNames.ContainsKey(key.headerText))
							{
								meetQuotaItemNames.Add(key.headerText, (key.scrapValue, 1));
							}
							else
							{
								(float, int) tuple = meetQuotaItemNames[key.headerText];
								meetQuotaItemNames[key.headerText] = (tuple.Item1 + (float)key.scrapValue, tuple.Item2 + 1);
								items.Remove(key);
							}
						}
					}
				}
				else
				{
					foreach (int combination in source.First())
					{
						ScanNodeProperties key2 = ItemsDictionary.FirstOrDefault((KeyValuePair<ScanNodeProperties, int> x) => x.Value == combination).Key;
						if ((Object)(object)key2 != (Object)null)
						{
							if (!meetQuotaItemNames.ContainsKey(key2.headerText))
							{
								meetQuotaItemNames.Add(key2.headerText, (key2.scrapValue, 1));
								continue;
							}
							(float, int) tuple2 = meetQuotaItemNames[key2.headerText];
							meetQuotaItemNames[key2.headerText] = (tuple2.Item1 + (float)key2.scrapValue, tuple2.Item2 + 1);
							items.Remove(key2);
						}
					}
				}
			}
			foreach (KeyValuePair<ScanNodeProperties, int> item2 in ItemsDictionary)
			{
				if (!NotmeetQuotaItemNames.ContainsKey(item2.Key.headerText))
				{
					NotmeetQuotaItemNames.Add(item2.Key.headerText, (item2.Key.scrapValue, 1));
					continue;
				}
				(float, int) tuple3 = NotmeetQuotaItemNames[item2.Key.headerText];
				NotmeetQuotaItemNames[item2.Key.headerText] = (tuple3.Item1 + (float)item2.Key.scrapValue, tuple3.Item2 + 1);
				items.Remove(item2.Key);
			}
			ItemsDictionary.Clear();
			string text = "";
			string text2 = "";
			foreach (ScanNodeProperties item3 in items)
			{
				if (meetQuotaItemNames.ContainsKey(item3.headerText))
				{
					if (meetQuotaItemNames.TryGetValue(item3.headerText, out var value))
					{
						text2 = $"{value.Item2}-{item3.headerText}: ${value.Item1}";
					}
					if (BetterItemScanModBase.CalculateForQuota.Value)
					{
						if (IsHexColor(BetterItemScanModBase.ItemTextCalculatorColorHex.Value))
						{
							text2 = "<color=" + BetterItemScanModBase.ItemTextCalculatorColorHex.Value + ">* " + text2 + "</color>";
						}
						else
						{
							Debug.LogError((object)(BetterItemScanModBase.ItemTextCalculatorColorHex.Value + " is an invalid colour. Please remember the '#'"));
							text2 = "<color=#FF3333>* " + text2 + "</color>";
						}
					}
					else if (IsHexColor(BetterItemScanModBase.ItemTextColorHex.Value))
					{
						text2 = "<color=" + BetterItemScanModBase.ItemTextColorHex.Value + ">" + text2 + "</color>";
					}
					else
					{
						Debug.LogError((object)(BetterItemScanModBase.ItemTextColorHex.Value + " is an invalid colour. Please remember the '#'"));
						text2 = "<color=#FF3333>* " + text2 + "</color>";
					}
				}
				else if (NotmeetQuotaItemNames.ContainsKey(item3.headerText))
				{
					if (NotmeetQuotaItemNames.TryGetValue(item3.headerText, out var value2))
					{
						text2 = $"{value2.Item2}-{item3.headerText}: ${value2.Item1}";
					}
					if (IsHexColor(BetterItemScanModBase.ItemTextColorHex.Value))
					{
						text2 = "<color=" + BetterItemScanModBase.ItemTextColorHex.Value + ">" + text2 + "</color>";
					}
					else
					{
						Debug.LogError((object)(BetterItemScanModBase.ItemTextColorHex.Value + " is an invalid colour. Please remember the '#'"));
						text2 = "<color=#FF3333>* " + text2 + "</color>";
					}
				}
				text = text + text2 + "\n";
			}
			((TMP_Text)_textMesh).text = text;
			if (BetterItemScanModBase.ShowShipTotalOnShipOnly.Value)
			{
				if (!GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom)
				{
					TextMeshProUGUI textMesh = _textMesh;
					((TMP_Text)textMesh).text = ((TMP_Text)textMesh).text + "\nTotal Scanned: " + Totalsum;
				}
				else
				{
					TextMeshProUGUI textMesh2 = _textMesh;
					((TMP_Text)textMesh2).text = ((TMP_Text)textMesh2).text + "\nTotal Scanned: " + Totalsum + "\nShip Total: " + Totalship;
				}
			}
			else
			{
				TextMeshProUGUI textMesh2 = _textMesh;
				((TMP_Text)textMesh2).text = ((TMP_Text)textMesh2).text + "\nTotal Scanned: " + Totalsum + "\nShip Total: " + Totalship;
			}
			if (BetterItemScanModBase.ShowTotalOnShipOnly.Value)
			{
				if (!GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom)
				{
					((Component)_textMesh).gameObject.SetActive(false);
					((Component)((TMP_Text)__instance.totalValueText).transform.parent).gameObject.SetActive(true);
				}
				else
				{
					((Component)_textMesh).gameObject.SetActive(true);
					((Component)((TMP_Text)__instance.totalValueText).transform.parent).gameObject.SetActive(false);
				}
			}
			_displayTimeLeft = BetterItemScanModBase.ItemScaningUICooldown.Value;
			if (!_totalCounter.activeSelf)
			{
				((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(ValueCoroutine());
			}
		}

		private static List<ScanNodeProperties> CalculateLootItems()
		{
			List<GrabbableObject> source = (from obj in GameObject.Find("/Environment/HangarShip").GetComponentsInChildren<GrabbableObject>()
				where ((Object)obj).name != "ClipboardManual" && ((Object)obj).name != "StickyNoteItem"
				select obj).ToList();
			List<ScanNodeProperties> list = scannedNodeObjects.Where((ScanNodeProperties obj) => obj.headerText != "ClipboardManual" && obj.headerText != "StickyNoteItem" && obj.scrapValue != 0).ToList();
			Totalsum = list.Sum((ScanNodeProperties scrap) => scrap.scrapValue);
			Totalship = source.Sum((GrabbableObject scrap) => scrap.scrapValue);
			return list;
		}

		private static IEnumerator ValueCoroutine()
		{
			_totalCounter.SetActive(true);
			while ((double)_displayTimeLeft > 0.0)
			{
				float displayTimeLeft = _displayTimeLeft;
				_displayTimeLeft = 0f;
				Debug.Log((object)$"Waiting for {displayTimeLeft} seconds...");
				yield return (object)new WaitForSeconds(displayTimeLeft);
			}
			_totalCounter.SetActive(false);
			Debug.Log((object)"Cooldown complete. Hiding UI.");
		}

		private static void CopyValueCounter()
		{
			//IL_0056: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: 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_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: 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_0191: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter");
			if (!Object.op_Implicit((Object)(object)val))
			{
				BetterItemScanModBase.Instance.mls.LogError((object)"Failed to find ValueCounter object to copy!");
			}
			_totalCounter = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent, false);
			Vector3 localPosition = _totalCounter.transform.localPosition;
			float num = Mathf.Clamp(localPosition.x + BetterItemScanModBase.AdjustScreenPositionXaxis.Value + 50f, -6000f, (float)Screen.width);
			float num2 = Mathf.Clamp(localPosition.y + BetterItemScanModBase.AdjustScreenPositionYaxis.Value - 80f, -6000f, (float)Screen.height);
			_totalCounter.transform.localPosition = new Vector3(num, num2, localPosition.z);
			_textMesh = _totalCounter.GetComponentInChildren<TextMeshProUGUI>();
			((TMP_Text)_textMesh).fontSizeMin = 5f;
			((TMP_Text)_textMesh).fontSize = BetterItemScanModBase.FontSize.Value;
			((TMP_Text)_textMesh).ForceMeshUpdate(false, false);
			((TMP_Text)_textMesh).alignment = (TextAlignmentOptions)1025;
			RectTransform rectTransform = ((TMP_Text)_textMesh).rectTransform;
			rectTransform.anchorMin = new Vector2(0.5f, 2f);
			rectTransform.anchorMax = new Vector2(0.5f, 2f);
			rectTransform.pivot = new Vector2(0.5f, 0f);
			Vector3 localPosition2 = ((Transform)rectTransform).localPosition;
			((Transform)rectTransform).localPosition = new Vector3(localPosition2.x, localPosition2.y - 140f, localPosition2.z);
		}
	}
	[HarmonyPatch]
	public class PlayerControllerBPatch_A
	{
		private static LineRenderer lineRenderer;

		private static GameObject lineObject;

		private static float maxDistance = 80f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "AssignNewNodes")]
		private static bool AssignNewNodes_patch(HUDManager __instance, PlayerControllerB playerScript)
		{
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: 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_0101: 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_0116: 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_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: 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_002d: Expected O, but got Unknown
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			HudManagerPatch_UI.scannedNodeObjects.Clear();
			if ((Object)(object)lineRenderer == (Object)null)
			{
				lineObject = new GameObject("LineObject");
				lineRenderer = lineObject.AddComponent<LineRenderer>();
				lineRenderer.positionCount = 2;
				lineObject.SetActive(false);
			}
			FieldInfo field = typeof(HUDManager).GetField("nodesOnScreen", BindingFlags.Instance | BindingFlags.NonPublic);
			List<ScanNodeProperties> list = field.GetValue(__instance) as List<ScanNodeProperties>;
			FieldInfo field2 = typeof(HUDManager).GetField("scannedScrapNum", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field2.GetValue(__instance);
			FieldInfo field3 = typeof(HUDManager).GetField("scanNodesHit", BindingFlags.Instance | BindingFlags.NonPublic);
			RaycastHit[] array = field3.GetValue(__instance) as RaycastHit[];
			MethodInfo method = typeof(HUDManager).GetMethod("AttemptScanNode", BindingFlags.Instance | BindingFlags.NonPublic);
			int num = Physics.SphereCastNonAlloc(new Ray(((Component)playerScript.gameplayCamera).transform.position + ((Component)playerScript.gameplayCamera).transform.forward * 20f, ((Component)playerScript.gameplayCamera).transform.forward), BetterItemScanModBase.ItemScanRadius.Value, array, maxDistance, 4194304);
			Vector3 val = new Vector3(((Component)playerScript.gameplayCamera).transform.position.x, ((Component)playerScript.gameplayCamera).transform.position.y - 2f, ((Component)playerScript.gameplayCamera).transform.position.z) + ((Component)playerScript.gameplayCamera).transform.forward;
			Vector3 forward = ((Component)playerScript.gameplayCamera).transform.forward;
			if (BetterItemScanModBase.ShowDebugMode.Value)
			{
				lineObject.SetActive(true);
				lineRenderer.SetPosition(0, val);
				lineRenderer.SetPosition(1, val + forward * maxDistance);
				LineRenderer obj = lineRenderer;
				float startWidth = (lineRenderer.endWidth = BetterItemScanModBase.ItemScanRadius.Value);
				obj.startWidth = startWidth;
			}
			if (num > __instance.scanElements.Length)
			{
				num = __instance.scanElements.Length;
			}
			list.Clear();
			value = 0;
			if (num > __instance.scanElements.Length)
			{
				for (int i = 0; i < num; i++)
				{
					ScanNodeProperties component = ((Component)((RaycastHit)(ref array[i])).transform).gameObject.GetComponent<ScanNodeProperties>();
					GrabbableObject component2 = ((Component)((RaycastHit)(ref array[i])).transform.parent).gameObject.GetComponent<GrabbableObject>();
					if (component2.itemProperties.isScrap)
					{
						HudManagerPatch_UI.scannedNodeObjects.Add(component);
					}
					if (component.nodeType == 1 || component.nodeType == 2)
					{
						object[] parameters = new object[3] { component, i, playerScript };
						method.Invoke(__instance, parameters);
					}
				}
			}
			if (list.Count < __instance.scanElements.Length)
			{
				for (int j = 0; j < num; j++)
				{
					ScanNodeProperties component3 = ((Component)((RaycastHit)(ref array[j])).transform).gameObject.GetComponent<ScanNodeProperties>();
					object[] parameters2 = new object[3] { component3, j, playerScript };
					method.Invoke(__instance, parameters2);
				}
			}
			return false;
		}
	}
	[HarmonyPatch]
	public class PlayerControllerBPatch_B
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "AttemptScanNode")]
		private static bool AttemptScanNode_patch(HUDManager __instance, ScanNodeProperties node, int i, PlayerControllerB playerScript)
		{
			MethodInfo method = typeof(HUDManager).GetMethod("MeetsScanNodeRequirements", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo method2 = typeof(HUDManager).GetMethod("AssignNodeToUIElement", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field = typeof(HUDManager).GetField("nodesOnScreen", BindingFlags.Instance | BindingFlags.NonPublic);
			List<ScanNodeProperties> list = field.GetValue(__instance) as List<ScanNodeProperties>;
			FieldInfo field2 = typeof(HUDManager).GetField("scannedScrapNum", BindingFlags.Instance | BindingFlags.NonPublic);
			int num = (int)field2.GetValue(__instance);
			FieldInfo field3 = typeof(HUDManager).GetField("playerPingingScan", BindingFlags.Instance | BindingFlags.NonPublic);
			float num2 = (float)field3.GetValue(__instance);
			object[] parameters = new object[2] { node, playerScript };
			object[] parameters2 = new object[1] { node };
			if (!(bool)method.Invoke(__instance, parameters))
			{
				return false;
			}
			if (node.nodeType == 2)
			{
				num++;
			}
			if (!list.Contains(node))
			{
				list.Add(node);
			}
			if (node.creatureScanID == -1)
			{
				HudManagerPatch_UI.scannedNodeObjects.Add(node);
			}
			if ((double)num2 < 0.0)
			{
				return false;
			}
			method2.Invoke(__instance, parameters2);
			return false;
		}
	}
	[HarmonyPatch]
	public class PlayerControllerBPatch_C
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDManager), "Update")]
		private static void Update_patch(HUDManager __instance)
		{
			FieldInfo field = typeof(HUDManager).GetField("addingToDisplayTotal", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(__instance);
			((Component)((TMP_Text)__instance.totalValueText).transform.parent).gameObject.SetActive(false);
			value = false;
		}
	}
}

plugins/Quality of life/FlipMods-ReservedWalkieSlot-1.5.4/ReservedWalkieSlot.dll

Decompiled 10 months ago
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 LethalCompanyInputUtils.Api;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using ReservedWalkieSlot.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("ReservedWalkieSlot")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedWalkieSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("c15c320f-d8fc-4f1c-be3c-f2d2ffc41edd")]
[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 ReservedWalkieSlot
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> activateWalkieKey;

		public static ConfigEntry<bool> hideWalkieMeshShoulder;

		public static string activateWalkieDisplayName;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			activateWalkieKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedWalkieSlot", "ActivateWalkieKey", "<Keyboard>/x", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)");
			hideWalkieMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedWalkieSlot", "HideWalkieOnShoulder", false, "Hides the walkie mesh while on your shoulder. Only applies in scenarios where you can view your player in third person.");
			activateWalkieDisplayName = GetDisplayName(activateWalkieKey.Value);
			currentConfigEntries.Add(((ConfigEntryBase)activateWalkieKey).Definition.Key, (ConfigEntryBase)(object)activateWalkieKey);
			currentConfigEntries.Add(((ConfigEntryBase)hideWalkieMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideWalkieMeshShoulder);
			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.ReservedWalkieSlot", "ReservedWalkieSlot", "1.5.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

		public static ReservedItemInfo walkieInfo = new ReservedItemInfo("Walkie-talkie", 100, true, true, true, true);

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			instance = this;
			ConfigSettings.BindConfigSettings();
			_harmony = new Harmony("ReservedWalkieSlot");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedWalkieSlot loaded");
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}

		public static void Log(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)message);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedWalkieSlot";

		public const string PLUGIN_NAME = "ReservedWalkieSlot";

		public const string PLUGIN_VERSION = "1.5.4";
	}
}
namespace ReservedWalkieSlot.Patches
{
	[HarmonyPatch]
	internal static class ReservedWalkieSlotPatcher
	{
		private static Vector3 localPlayerShoulderPositionOffset = new Vector3(0.125f, 0.4f, 0.125f);

		private static Vector3 playerShoulderPositionOffset = new Vector3(0.15f, -0.05f, 0.25f);

		private static Vector3 playerShoulderRotationOffset = new Vector3(0f, 270f, 100f);

		private static string originalControlTooltip = "";

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static WalkieTalkie GetMainWalkie(PlayerControllerB playerController)
		{
			return GetCurrentlySelectedWalkie(playerController) ?? GetReservedWalkie(playerController);
		}

		public static WalkieTalkie GetReservedWalkie(PlayerControllerB playerController)
		{
			return (WalkieTalkie)(SyncManager.syncReservedItemsList.Contains(Plugin.walkieInfo) ? /*isinst with value type is only supported in some contexts*/: null);
		}

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

		[HarmonyPatch(typeof(WalkieTalkie), "PocketItem")]
		[HarmonyPostfix]
		public static void OnPocketWalkie(WalkieTalkie __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				if ((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController)
				{
					((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 23;
				}
				else
				{
					((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6;
				}
				((GrabbableObject)__instance).parentObject = ((Component)((GrabbableObject)__instance).playerHeldBy.playerBadgeMesh).transform.parent;
			}
		}

		[HarmonyPatch(typeof(WalkieTalkie), "EquipItem")]
		[HarmonyPostfix]
		public static void OnEquipWalkie(WalkieTalkie __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6;
				((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder);
			}
		}

		[HarmonyPatch(typeof(WalkieTalkie), "DiscardItem")]
		[HarmonyPostfix]
		public static void OnDiscardWalkie(WalkieTalkie __instance)
		{
			((Component)((Component)__instance).GetComponentInChildren<Renderer>()).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 WalkieTalkie && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance.parentObject != (Object)null && __instance.isPocketed && (Object)(object)__instance == (Object)(object)GetReservedWalkie(__instance.playerHeldBy) && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedWalkie(__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 WalkieTalkie && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance == (Object)(object)GetReservedWalkie(__instance.playerHeldBy) && !ConfigSettings.hideWalkieMeshShoulder.Value)
			{
				enable = true;
			}
		}
	}
}
namespace ReservedWalkieSlot.Input
{
	internal class IngameKeybinds : LcInputActions
	{
		internal static IngameKeybinds Instance = new IngameKeybinds();

		[InputAction("<Keyboard>/x", Name = "[ReservedItemSlots]\nActivate walkie")]
		public InputAction ActivateWalkieHotkey { get; set; }

		internal static InputActionAsset GetAsset()
		{
			return ((LcInputActions)Instance).Asset;
		}
	}
	internal class InputUtilsCompat
	{
		internal static InputActionAsset Asset => IngameKeybinds.GetAsset();

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

		public static InputAction ActivateWalkieHotkey => IngameKeybinds.Instance.ActivateWalkieHotkey;
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static InputActionAsset Asset;

		public static InputActionMap ActionMap;

		private static InputAction ActivateWalkieAction;

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

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		public static void AddToKeybindMenu()
		{
			InitKeybinds();
		}

		public static void InitKeybinds()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//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];
				ActivateWalkieAction = InputUtilsCompat.ActivateWalkieHotkey;
			}
			else
			{
				Asset = new InputActionAsset();
				ActionMap = new InputActionMap("ReservedItemSlots");
				InputActionSetupExtensions.AddActionMap(Asset, ActionMap);
				ActivateWalkieAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ActivateWalkie", (InputActionType)0, ConfigSettings.activateWalkieKey.Value, (string)null, (string)null, (string)null, (string)null);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable()
		{
			Asset.Enable();
			ActivateWalkieAction.performed += OnPressWalkieButtonPerformed;
			ActivateWalkieAction.canceled += OnReleaseWalkieButtonPerformed;
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable()
		{
			Asset.Disable();
			ActivateWalkieAction.performed -= OnPressWalkieButtonPerformed;
			ActivateWalkieAction.canceled -= OnReleaseWalkieButtonPerformed;
		}

		private static void OnPressWalkieButtonPerformed(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject))
			{
				return;
			}
			WalkieTalkie mainWalkie = ReservedWalkieSlotPatcher.GetMainWalkie(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainWalkie == (Object)null) && ((GrabbableObject)mainWalkie).isBeingUsed)
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					Plugin.Log("Talking into walkie");
					ShipBuildModeManager.Instance.CancelBuildMode(true);
					((GrabbableObject)mainWalkie).UseItemOnClient(true);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}

		private static void OnReleaseWalkieButtonPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				WalkieTalkie mainWalkie = ReservedWalkieSlotPatcher.GetMainWalkie(localPlayerController);
				if (((CallbackContext)(ref context)).canceled && !((Object)(object)mainWalkie == (Object)null))
				{
					Plugin.Log("Not talking into walkie");
					ShipBuildModeManager.Instance.CancelBuildMode(true);
					((GrabbableObject)mainWalkie).UseItemOnClient(false);
				}
			}
		}
	}
}

plugins/Quality of life/Dev1A3-ScannableCodes-1.0.2/ScannableCodes.dll

Decompiled 10 months ago
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.Logging;
using HarmonyLib;
using UnityEngine;

[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("ScanCodes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e32c44b70105c03236526ea33f4ec139e7aa61f2")]
[assembly: AssemblyProduct("ScanCodes")]
[assembly: AssemblyTitle("ScanCodes")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ScanCodes;

[BepInPlugin("Dev1A3.ScanCodes", "ScanCodes", "1.0.0")]
internal class PluginLoader : BaseUnityPlugin
{
	internal const string modGUID = "Dev1A3.ScanCodes";

	private readonly Harmony harmony = new Harmony("Dev1A3.ScanCodes");

	private const string modVersion = "1.0.0";

	private static bool initialized;

	internal static ManualLogSource logSource;

	public static PluginLoader Instance { get; private set; }

	private void Awake()
	{
		if (!initialized)
		{
			initialized = true;
			Instance = this;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			harmony.PatchAll(executingAssembly);
			logSource = Logger.CreateLogSource("Dev1A3.ScanCodes");
			logSource.LogInfo((object)"Loaded ScanCodes");
		}
	}
}
[HarmonyPatch]
internal static class ScanPatch
{
	[HarmonyPatch(typeof(TerminalAccessibleObject), "SetCodeTo")]
	[HarmonyPostfix]
	private static void SetCodeTo(ref TerminalAccessibleObject __instance, int codeIndex)
	{
		if (__instance.objectCode == null)
		{
			return;
		}
		Transform val = (Object.op_Implicit((Object)(object)((Component)__instance).transform.parent) ? ((Component)__instance).transform.parent : ((Component)__instance).transform);
		ScanNodeProperties componentInChildren = ((Component)val).GetComponentInChildren<ScanNodeProperties>();
		if ((Object)(object)componentInChildren != (Object)null)
		{
			componentInChildren.subText = " " + __instance.objectCode;
			if (__instance.isBigDoor)
			{
				componentInChildren.maxRange = 8;
			}
			else if ((Object)(object)((Component)__instance).GetComponent<Turret>() != (Object)null)
			{
				componentInChildren.maxRange = 10;
			}
			PluginLoader.logSource.LogDebug((object)$"Set code of {((Object)val).name}: {__instance.objectCode} (Range: {componentInChildren.maxRange})");
		}
	}
}
public static class MyPluginInfo
{
	public const string PLUGIN_GUID = "ScanCodes";

	public const string PLUGIN_NAME = "ScanCodes";

	public const string PLUGIN_VERSION = "1.0.0";
}

plugins/Game Balance/TheFluff-FairAI-1.2.8/FairAI.dll

Decompiled 10 months ago
using System;
using System.Collections;
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 System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FairAI.Component;
using FairAI.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using LethalThings;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FairAI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FairAI")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("42deea12-f73e-4d63-81e9-5359e98c8d53")]
[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]
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace FairAI
{
	internal class FAIR_AI : NetworkBehaviour
	{
		public EnemyAI targetWithRotation;

		[ClientRpc]
		public void SwitchedTargetedEnemyClientRpc(Turret turret, EnemyAI enemy, bool setModeToCharging = false)
		{
			targetWithRotation = enemy;
			if (setModeToCharging)
			{
				Type typeFromHandle = typeof(Turret);
				MethodInfo method = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(turret, new object[1] { 1 });
			}
		}

		[ClientRpc]
		public void RemoveTargetedEnemyClientRpc()
		{
			targetWithRotation = null;
		}
	}
	[BepInPlugin("GoldenKitten.FairAI", "Fair AI", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "GoldenKitten.FairAI";

		private const string modName = "Fair AI";

		private const string modVersion = "1.0.0";

		private Harmony harmony = new Harmony("GoldenKitten.FairAI");

		public static Plugin Instance;

		public static ManualLogSource logger;

		public static List<EnemyType> enemies;

		public static List<Item> items;

		public static int wallsAndEnemyLayerMask = 524288;

		public static int enemyMask = 524288;

		public static int allHittablesMask;

		private static float onMeshThreshold = 3f;

		private void Awake()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony = new Harmony("GoldenKitten.FairAI");
			logger = Logger.CreateLogSource("GoldenKitten.FairAI");
			harmony.PatchAll(typeof(Plugin));
			logger.LogInfo((object)"Fair AI initiated!");
			CreateHarmonyPatch(harmony, typeof(RoundManager), "Start", null, typeof(RoundManagerPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(StartOfRound), "Start", null, typeof(StartOfRoundPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Turret), "Start", null, typeof(TurretAIPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Turret), "Update", null, typeof(TurretAIPatch), "PatchUpdate", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "SetTargetToPlayerBody", null, typeof(TurretAIPatch), "PatchSetTargetToPlayerBody", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "TurnTowardsTargetIfHasLOS", null, typeof(TurretAIPatch), "PatchTurnTowardsTargetIfHasLOS", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Landmine), "SpawnExplosion", new Type[4]
			{
				typeof(Vector3),
				typeof(bool),
				typeof(float),
				typeof(float)
			}, typeof(MineAIPatch), "PatchSpawnExplosion", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerEnter", null, typeof(MineAIPatch), "PatchOnTriggerEnter", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerExit", null, typeof(MineAIPatch), "PatchOnTriggerExit", isPrefix: false);
			if (FindType("LethalThings.RoombaAI") != null)
			{
				CreateHarmonyPatch(harmony, FindType("LethalThings.RoombaAI"), "Start", null, typeof(BoombaPatch), "PatchStart", isPrefix: false);
				CreateHarmonyPatch(harmony, FindType("LethalThings.RoombaAI"), "DoAIInterval", null, typeof(BoombaPatch), "PatchDoAIInterval", isPrefix: false);
			}
		}

		public static bool CanMob(string parentIdentifier, string identifier, string mobName)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			string text = RemoveInvalidCharacters(mobName).ToUpper();
			if (((BaseUnityPlugin)Instance).Config[new ConfigDefinition("Mobs", parentIdentifier)].BoxedValue.ToString().ToUpper().Equals("TRUE"))
			{
				foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
				{
					if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(text + identifier.ToUpper())))
					{
						return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
					}
				}
				return false;
			}
			return false;
		}

		public static string RemoveWhitespaces(string source)
		{
			return string.Join("", source.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		public static string RemoveSpecialCharacters(string source)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in source)
			{
				if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		public static string RemoveInvalidCharacters(string source)
		{
			return RemoveWhitespaces(RemoveSpecialCharacters(source));
		}

		public static Type FindType(string fullName)
		{
			try
			{
				if ((from a in AppDomain.CurrentDomain.GetAssemblies()
					where !a.IsDynamic
					select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName)) != null)
				{
					return (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.IsDynamic
						select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName));
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

		public static void CreateHarmonyPatch(Harmony harmony, Type typeToPatch, string methodToPatch, Type[] parameters, Type patchType, string patchMethod, bool isPrefix)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			if (typeToPatch == null || patchType == null)
			{
				logger.LogInfo((object)"Type is either incorrect or does not exist!");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeToPatch, methodToPatch, parameters, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(patchType, patchMethod, (Type[])null, (Type[])null);
			if (isPrefix)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		public static bool IsAgentOnNavMesh(GameObject agentObject)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_0039: 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_0058: 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)
			Vector3 position = agentObject.transform.position;
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(position, ref val, onMeshThreshold, -1) && Mathf.Approximately(position.x, ((NavMeshHit)(ref val)).position.x) && Mathf.Approximately(position.z, ((NavMeshHit)(ref val)).position.z))
			{
				return position.y >= ((NavMeshHit)(ref val)).position.y;
			}
			return false;
		}

		public static bool AttackTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return HitTargets(GetTargets(aimPoint, forward, range), forward);
		}

		public static List<GameObject> GetTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(aimPoint, forward);
			RaycastHit[] array = Physics.RaycastAll(val, range, allHittablesMask, (QueryTriggerInteraction)2);
			Array.Sort(array, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
			Vector3 val2 = aimPoint + forward * range;
			IHittable val3 = default(IHittable);
			EnemyAI val6 = default(EnemyAI);
			for (int i = 0; i < array.Length; i++)
			{
				GameObject gameObject = ((Component)((RaycastHit)(ref array[i])).transform).gameObject;
				if (gameObject.TryGetComponent<IHittable>(ref val3))
				{
					EnemyAI val4 = null;
					EnemyAICollisionDetect val5 = (EnemyAICollisionDetect)(object)((val3 is EnemyAICollisionDetect) ? val3 : null);
					if (val5 != null)
					{
						val4 = val5.mainScript;
					}
					if ((Object)(object)val4 != (Object)null && (val4.isEnemyDead || val4.enemyHP <= 0 || !val4.enemyType.canDie))
					{
						continue;
					}
					if (val3 is PlayerControllerB)
					{
						list.Add(gameObject);
					}
					else
					{
						if (!((Object)(object)val4 != (Object)null))
						{
							continue;
						}
						list.Add(gameObject);
					}
					val2 = ((RaycastHit)(ref array[i])).point;
					break;
				}
				if (((Component)((RaycastHit)(ref array[i])).collider).TryGetComponent<EnemyAI>(ref val6))
				{
					if (val6.isEnemyDead || val6.enemyHP <= 0 || !val6.enemyType.canDie)
					{
						continue;
					}
					list.Add(((Component)val6).gameObject);
					val2 = ((RaycastHit)(ref array[i])).point;
					break;
				}
				val2 = ((RaycastHit)(ref array[i])).point;
				break;
			}
			return list;
		}

		public static bool HitTargets(List<GameObject> targets, Vector3 forward)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			bool hits = false;
			if (!targets.Any())
			{
				return hits;
			}
			targets.ForEach(delegate(GameObject t)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_03b0: Expected O, but got Unknown
				//IL_058a: Unknown result type (might be due to invalid IL or missing references)
				//IL_055b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0562: Expected O, but got Unknown
				//IL_0577: Unknown result type (might be due to invalid IL or missing references)
				//IL_0282: 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_0413: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)t != (Object)null)
				{
					if ((Object)(object)t.GetComponent<PlayerControllerB>() != (Object)null)
					{
						PlayerControllerB component = t.GetComponent<PlayerControllerB>();
						int num = 20;
						hits = true;
						component.DamagePlayer(num, true, true, (CauseOfDeath)7, 0, false, forward);
					}
					else if ((Object)(object)t.GetComponent<EnemyAICollisionDetect>() != (Object)null)
					{
						EnemyAICollisionDetect component2 = t.GetComponent<EnemyAICollisionDetect>();
						int num2 = 1;
						if (!component2.mainScript.isEnemyDead && ((NetworkBehaviour)component2.mainScript).IsOwner && CanMob("TurretDamageAllMobs", ".Turret Damage", component2.mainScript.enemyType.enemyName))
						{
							if (component2.mainScript is NutcrackerEnemyAI)
							{
								if (((EnemyAI)(NutcrackerEnemyAI)component2.mainScript).currentBehaviourStateIndex > 0)
								{
									if ((Object)(object)component2.mainScript.creatureAnimator != (Object)null)
									{
										component2.mainScript.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
									}
									EnemyAI mainScript = component2.mainScript;
									mainScript.enemyHP -= num2;
									if (component2.mainScript.enemyHP <= 0 || ((NetworkBehaviour)component2.mainScript).IsOwner)
									{
										component2.mainScript.KillEnemyOnOwnerClient(true);
									}
									hits = true;
								}
							}
							else
							{
								if ((Object)(object)component2.mainScript.creatureAnimator != (Object)null)
								{
									component2.mainScript.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
								}
								EnemyAI mainScript2 = component2.mainScript;
								mainScript2.enemyHP -= num2;
								if (component2.mainScript.enemyHP <= 0 || ((NetworkBehaviour)component2.mainScript).IsOwner)
								{
									component2.mainScript.KillEnemyOnOwnerClient(true);
								}
								hits = true;
							}
						}
					}
					else if ((Object)(object)t.GetComponent<EnemyAI>() != (Object)null)
					{
						EnemyAI component3 = t.GetComponent<EnemyAI>();
						if (((NetworkBehaviour)component3).IsOwner)
						{
							int num3 = 1;
							if (CanMob("TurretDamageAllMobs", ".Turret Damage", component3.enemyType.enemyName))
							{
								if (component3 is NutcrackerEnemyAI)
								{
									if (((EnemyAI)(NutcrackerEnemyAI)component3).currentBehaviourStateIndex > 0)
									{
										if ((Object)(object)component3.creatureAnimator != (Object)null)
										{
											component3.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
										}
										component3.enemyHP -= num3;
										if (component3.enemyHP <= 0 || ((NetworkBehaviour)component3).IsOwner)
										{
											component3.KillEnemyOnOwnerClient(true);
										}
										hits = true;
									}
								}
								else
								{
									if ((Object)(object)component3.creatureAnimator != (Object)null)
									{
										component3.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
									}
									component3.enemyHP -= num3;
									if (component3.enemyHP <= 0 || ((NetworkBehaviour)component3).IsOwner)
									{
										component3.KillEnemyOnOwnerClient(true);
									}
									hits = true;
								}
							}
						}
					}
					else if (t.GetComponent<IHittable>() != null)
					{
						IHittable component4 = t.GetComponent<IHittable>();
						if (component4 is EnemyAICollisionDetect)
						{
							EnemyAICollisionDetect val = (EnemyAICollisionDetect)component4;
							int num4 = 1;
							if (((NetworkBehaviour)val.mainScript).IsOwner && CanMob("TurretDamageAllMobs", ".Turret Damage", val.mainScript.enemyType.enemyName))
							{
								if (val.mainScript is NutcrackerEnemyAI)
								{
									if (((EnemyAI)(NutcrackerEnemyAI)val.mainScript).currentBehaviourStateIndex > 0)
									{
										if ((Object)(object)val.mainScript.creatureAnimator != (Object)null)
										{
											val.mainScript.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
										}
										EnemyAI mainScript3 = val.mainScript;
										mainScript3.enemyHP -= num4;
										if (val.mainScript.enemyHP <= 0 || ((NetworkBehaviour)val.mainScript).IsOwner)
										{
											val.mainScript.KillEnemyOnOwnerClient(true);
										}
										hits = true;
									}
								}
								else
								{
									if ((Object)(object)val.mainScript.creatureAnimator != (Object)null)
									{
										val.mainScript.creatureAnimator.SetTrigger(Animator.StringToHash("damage"));
									}
									EnemyAI mainScript4 = val.mainScript;
									mainScript4.enemyHP -= num4;
									if (val.mainScript.enemyHP <= 0 || ((NetworkBehaviour)val.mainScript).IsOwner)
									{
										val.mainScript.KillEnemyOnOwnerClient(true);
									}
									hits = true;
								}
							}
						}
						else if (component4 is PlayerControllerB)
						{
							PlayerControllerB val2 = (PlayerControllerB)component4;
							int num5 = 33;
							hits = true;
							val2.DamagePlayer(num5, true, true, (CauseOfDeath)7, 0, false, forward);
						}
						else
						{
							component4.Hit(1, forward, (PlayerControllerB)null, true);
							hits = true;
						}
					}
				}
			});
			return hits;
		}
	}
}
namespace FairAI.Patches
{
	internal class BoombaPatch
	{
		public static void PatchStart(ref RoombaAI __instance)
		{
			((Component)__instance).gameObject.AddComponent<BoombaTimer>();
		}

		public static void PatchDoAIInterval(ref RoombaAI __instance)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: 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_006b: 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_008e: 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_00ac: 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_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_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.IsAgentOnNavMesh(((Component)__instance).gameObject) || (((EnemyAI)__instance).currentSearch == null && !((EnemyAI)__instance).movingTowardsTargetPlayer) || (!__instance.mineAudio.isPlaying && !__instance.mineFarAudio.isPlaying) || !((Component)__instance).GetComponent<BoombaTimer>().IsActiveBomb())
			{
				return;
			}
			Vector3 val = ((Component)__instance).transform.position + Vector3.up;
			Collider[] array = Physics.OverlapSphere(val, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(val, ((Component)array[i]).transform.position);
				if ((num > 4f && Physics.Linecast(val, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1)) || !((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if (!((Object)(object)((Component)component.mainScript).gameObject != (Object)(object)((Component)__instance).gameObject) || !Plugin.CanMob("BoombaAllMobs", ".Boomba", component.mainScript.enemyType.enemyName))
				{
					continue;
				}
				if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component.mainScript).IsOwner && !component.mainScript.isEnemyDead)
				{
					Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, val, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
					if (num < 3f)
					{
						component.mainScript.KillEnemyOnOwnerClient(true);
					}
					else if (num < 6f)
					{
						component.mainScript.HitEnemyOnLocalClient(2, default(Vector3), (PlayerControllerB)null, false);
					}
				}
				if (((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).KillEnemy(true);
				}
				else
				{
					((EnemyAI)__instance).KillEnemyServerRpc(true);
				}
			}
		}
	}
	internal class MineAIPatch
	{
		public static void PatchOnTriggerEnter(ref Landmine __instance, Collider other, ref float ___pressMineDebounceTimer)
		{
			EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
			if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()))
			{
				___pressMineDebounceTimer = 0.5f;
				__instance.PressMineServerRpc();
			}
		}

		public static void PatchOnTriggerExit(ref Landmine __instance, Collider other, ref bool ___sendingExplosionRPC)
		{
			EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
			if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()) && !__instance.hasExploded)
			{
				__instance.SetOffMineAnimation();
				___sendingExplosionRPC = true;
				__instance.ExplodeMineServerRpc();
			}
		}

		public static void PatchSpawnExplosion(Vector3 explosionPosition, bool spawnExplosionEffect = false, float killRange = 1f, float damageRange = 1f)
		{
			//IL_0001: 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)
			//IL_0024: 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_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_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_00ff: 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)
			Collider[] array = Physics.OverlapSphere(explosionPosition, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(explosionPosition, ((Component)array[i]).transform.position);
				if ((num > 4f && Physics.Linecast(explosionPosition, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1)) || !((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component.mainScript).IsOwner && !component.mainScript.isEnemyDead)
				{
					if (num < killRange)
					{
						component.mainScript.KillEnemyOnOwnerClient(true);
					}
					else if (num < damageRange)
					{
						component.mainScript.HitEnemyOnLocalClient(2, default(Vector3), (PlayerControllerB)null, false);
					}
				}
			}
		}
	}
	internal class RoundManagerPatch
	{
		public static void PatchStart()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Expected O, but got Unknown
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}
	}
	internal class StartOfRoundPatch
	{
		public static void PatchStart()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Expected O, but got Unknown
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}
	}
	internal class TurretAIPatch
	{
		public static float viewRadius = 10f;

		public static float viewAngle = 90f;

		public static void PatchStart(ref Turret __instance)
		{
			FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
			if ((Object)(object)component == (Object)null)
			{
				component = ((Component)__instance).gameObject.AddComponent<FAIR_AI>();
			}
		}

		public static bool PatchUpdate(ref Turret __instance)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected I4, but got Unknown
			//IL_0134: 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_00cb: Invalid comparison between Unknown and I4
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Invalid comparison between Unknown and I4
			//IL_05b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bd: Invalid comparison between Unknown and I4
			//IL_0773: Unknown result type (might be due to invalid IL or missing references)
			//IL_0779: Invalid comparison between Unknown and I4
			//IL_09b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09bf: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Invalid comparison between Unknown and O
			//IL_080f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0815: Invalid comparison between Unknown and O
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Expected O, but got Unknown
			//IL_08b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0903: Unknown result type (might be due to invalid IL or missing references)
			//IL_0822: Unknown result type (might be due to invalid IL or missing references)
			//IL_082c: Expected O, but got Unknown
			//IL_0dc0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ddb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0df4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e00: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e12: Unknown result type (might be due to invalid IL or missing references)
			//IL_092a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0939: Unknown result type (might be due to invalid IL or missing references)
			//IL_093e: Unknown result type (might be due to invalid IL or missing references)
			//IL_095b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0960: Unknown result type (might be due to invalid IL or missing references)
			//IL_096f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c03: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c0f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c2a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c36: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c58: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b8b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b91: Invalid comparison between Unknown and O
			//IL_0e89: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e95: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ea7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e6f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c8a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cbb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cc0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ccf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b9e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba8: Expected O, but got Unknown
			FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
			Type typeFromHandle = typeof(Turret);
			if (!__instance.turretActive)
			{
				FieldInfo field = typeFromHandle.GetField("wasTargetingPlayerLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
				field.SetValue(__instance, false);
				__instance.turretMode = (TurretMode)0;
				__instance.targetPlayerWithRotation = null;
				component.targetWithRotation = null;
				return false;
			}
			FieldInfo field2 = typeFromHandle.GetField("wasTargetingPlayerLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field2.GetValue(__instance);
			if ((Object)(object)__instance.targetPlayerWithRotation != (Object)null || (Object)(object)component.targetWithRotation != (Object)null)
			{
				if (!(bool)value)
				{
					field2.SetValue(__instance, true);
					if ((int)__instance.turretMode == 0)
					{
						__instance.turretMode = (TurretMode)1;
					}
				}
				MethodInfo method = typeFromHandle.GetMethod("SetTargetToPlayerBody", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(__instance, null);
				MethodInfo method2 = typeFromHandle.GetMethod("TurnTowardsTargetIfHasLOS", BindingFlags.Instance | BindingFlags.NonPublic);
				method2.Invoke(__instance, null);
			}
			else if ((bool)value)
			{
				field2.SetValue(__instance, false);
				__instance.turretMode = (TurretMode)0;
			}
			FieldInfo field3 = typeFromHandle.GetField("turretModeLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
			object value2 = field3.GetValue(__instance);
			FieldInfo field4 = typeFromHandle.GetField("rotatingClockwise", BindingFlags.Instance | BindingFlags.NonPublic);
			object value3 = field4.GetValue(__instance);
			FieldInfo field5 = typeFromHandle.GetField("fadeBulletAudioCoroutine", BindingFlags.Instance | BindingFlags.NonPublic);
			object value4 = field5.GetValue(__instance);
			FieldInfo field6 = typeFromHandle.GetField("turretInterval", BindingFlags.Instance | BindingFlags.NonPublic);
			object value5 = field6.GetValue(__instance);
			FieldInfo field7 = typeFromHandle.GetField("rotatingSmoothly", BindingFlags.Instance | BindingFlags.NonPublic);
			object value6 = field7.GetValue(__instance);
			FieldInfo field8 = typeFromHandle.GetField("switchRotationTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value7 = field8.GetValue(__instance);
			FieldInfo field9 = typeFromHandle.GetField("rotatingRight", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field10 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			object value8 = field10.GetValue(__instance);
			FieldInfo field11 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field12 = typeFromHandle.GetField("shootRay", BindingFlags.Instance | BindingFlags.NonPublic);
			object value9 = field12.GetValue(__instance);
			FieldInfo field13 = typeFromHandle.GetField("hit", BindingFlags.Instance | BindingFlags.NonPublic);
			object value10 = field13.GetValue(__instance);
			FieldInfo field14 = typeFromHandle.GetField("berserkTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value11 = field14.GetValue(__instance);
			FieldInfo field15 = typeFromHandle.GetField("enteringBerserkMode", BindingFlags.Instance | BindingFlags.NonPublic);
			object value12 = field15.GetValue(__instance);
			TurretMode turretMode = __instance.turretMode;
			TurretMode val = turretMode;
			RaycastHit val4;
			switch ((int)val)
			{
			case 0:
				value2 = field3.GetValue(__instance);
				if ((int)(TurretMode)value2 > 0)
				{
					field3.SetValue(__instance, (object)(TurretMode)0);
					field4.SetValue(__instance, false);
					__instance.mainAudio.Stop();
					__instance.farAudio.Stop();
					__instance.berserkAudio.Stop();
					value4 = field5.GetValue(__instance);
					if ((object)(Coroutine)value4 != null)
					{
						((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
					}
					MethodInfo method4 = typeFromHandle.GetMethod("FadeBulletAudio", BindingFlags.Instance | BindingFlags.NonPublic);
					IEnumerator enumerator = (IEnumerator)method4.Invoke(__instance, null);
					field5.SetValue(__instance, ((MonoBehaviour)__instance).StartCoroutine(enumerator));
					__instance.bulletParticles.Stop(true, (ParticleSystemStopBehavior)1);
					__instance.rotationSpeed = 28f;
					field7.SetValue(__instance, true);
					__instance.turretAnimator.SetInteger("TurretMode", 0);
					field6.SetValue(__instance, Random.Range(0f, 0.15f));
				}
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					break;
				}
				if ((float)value7 >= 7f)
				{
					field8.SetValue(__instance, 0f);
					value7 = field8.GetValue(__instance);
					bool flag = !(bool)field9.GetValue(__instance);
					__instance.SwitchRotationClientRpc(flag);
					__instance.SwitchRotationOnInterval(flag);
				}
				else
				{
					field8.SetValue(__instance, (float)value7 + Time.deltaTime);
				}
				value5 = field6.GetValue(__instance);
				if ((float)value5 >= 0.25f)
				{
					field6.SetValue(__instance, 0f);
					PlayerControllerB val5 = __instance.CheckForPlayersInLineOfSight(1.35f, true);
					List<EnemyAI> actualTargets = GetActualTargets(__instance, GetTargets(__instance));
					if ((Object)(object)val5 != (Object)null && !val5.isPlayerDead)
					{
						__instance.targetPlayerWithRotation = val5;
						MethodInfo method5 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
						method5.Invoke(__instance, new object[1] { 1 });
						__instance.SwitchTargetedPlayerClientRpc((int)val5.playerClientId, true);
					}
					else if (actualTargets.Any())
					{
						__instance.targetPlayerWithRotation = null;
						component.targetWithRotation = actualTargets[0];
						MethodInfo method6 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
						method6.Invoke(__instance, new object[1] { 1 });
						component.SwitchedTargetedEnemyClientRpc(__instance, actualTargets[0], setModeToCharging: true);
					}
				}
				else
				{
					value5 = field6.GetValue(__instance);
					field6.SetValue(__instance, (float)value5 + Time.deltaTime);
				}
				break;
			case 1:
				value2 = field3.GetValue(__instance);
				if ((int)(TurretMode)value2 != 1)
				{
					field3.SetValue(__instance, (object)(TurretMode)1);
					field4.SetValue(__instance, false);
					__instance.mainAudio.PlayOneShot(__instance.detectPlayerSFX);
					__instance.berserkAudio.Stop();
					WalkieTalkie.TransmitOneShotAudio(__instance.mainAudio, __instance.detectPlayerSFX, 1f);
					__instance.rotationSpeed = 95f;
					field7.SetValue(__instance, false);
					field11.SetValue(__instance, 0f);
					__instance.turretAnimator.SetInteger("TurretMode", 1);
				}
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					break;
				}
				value5 = field6.GetValue(__instance);
				if ((float)value5 >= 1.5f)
				{
					field6.SetValue(__instance, 0f);
					Debug.Log((object)"Charging timer is up, setting to firing mode");
					if (!(bool)value8)
					{
						Debug.Log((object)"hasLineOfSight is false");
						__instance.targetPlayerWithRotation = null;
						component.targetWithRotation = null;
						__instance.RemoveTargetedPlayerClientRpc();
						component.RemoveTargetedEnemyClientRpc();
					}
					else
					{
						MethodInfo method7 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
						method7.Invoke(__instance, new object[1] { 2 });
						__instance.SetToModeClientRpc(2);
					}
				}
				else
				{
					value5 = field6.GetValue(__instance);
					field6.SetValue(__instance, (float)value5 + Time.deltaTime);
				}
				break;
			case 2:
				value2 = field3.GetValue(__instance);
				if ((int)(TurretMode)value2 != 2)
				{
					field3.SetValue(__instance, (object)(TurretMode)2);
					__instance.berserkAudio.Stop();
					__instance.mainAudio.clip = __instance.firingSFX;
					__instance.mainAudio.Play();
					__instance.farAudio.clip = __instance.firingFarSFX;
					__instance.farAudio.Play();
					__instance.bulletParticles.Play(true);
					__instance.bulletCollisionAudio.Play();
					value4 = field5.GetValue(__instance);
					if ((object)(Coroutine)value4 != null)
					{
						((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
					}
					__instance.bulletCollisionAudio.volume = 1f;
					field7.SetValue(__instance, false);
					field11.SetValue(__instance, 0f);
					__instance.turretAnimator.SetInteger("TurretMode", 2);
				}
				value5 = field6.GetValue(__instance);
				if ((float)value5 >= 0.21f)
				{
					field6.SetValue(__instance, 0f);
					Plugin.AttackTargets(__instance.aimPoint.position, __instance.aimPoint.forward, 30f);
					field12.SetValue(__instance, (object)new Ray(__instance.aimPoint.position, __instance.aimPoint.forward));
					RaycastHit val6 = default(RaycastHit);
					if (Physics.Raycast((Ray)value9, ref val6, 30f, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
					{
						field13.SetValue(__instance, val6);
						Ray val7 = (Ray)value9;
						value10 = field13.GetValue(__instance);
						Transform transform2 = ((Component)__instance.bulletCollisionAudio).transform;
						val4 = (RaycastHit)value10;
						transform2.position = ((Ray)(ref val7)).GetPoint(((RaycastHit)(ref val4)).distance - 0.5f);
					}
				}
				else
				{
					value5 = field6.GetValue(__instance);
					field6.SetValue(__instance, (float)value5 + Time.deltaTime);
				}
				break;
			case 3:
				value2 = field3.GetValue(__instance);
				if ((int)(TurretMode)value2 != 3)
				{
					field3.SetValue(__instance, (object)(TurretMode)3);
					__instance.turretAnimator.SetInteger("TurretMode", 1);
					field14.SetValue(__instance, 1.3f);
					__instance.berserkAudio.Play();
					__instance.rotationSpeed = 77f;
					field15.SetValue(__instance, true);
					field7.SetValue(__instance, true);
					field11.SetValue(__instance, 0f);
					field2.SetValue(__instance, false);
					__instance.targetPlayerWithRotation = null;
					component.targetWithRotation = null;
				}
				value12 = field15.GetValue(__instance);
				if ((bool)value12)
				{
					value11 = field14.GetValue(__instance);
					field14.SetValue(__instance, (float)value11 - Time.deltaTime);
					value11 = field14.GetValue(__instance);
					if ((float)value11 <= 0f)
					{
						field15.SetValue(__instance, false);
						field4.SetValue(__instance, true);
						field14.SetValue(__instance, 9f);
						__instance.turretAnimator.SetInteger("TurretMode", 2);
						__instance.mainAudio.clip = __instance.firingSFX;
						__instance.mainAudio.Play();
						__instance.farAudio.clip = __instance.firingFarSFX;
						__instance.farAudio.Play();
						__instance.bulletParticles.Play(true);
						__instance.bulletCollisionAudio.Play();
						value4 = field5.GetValue(__instance);
						if ((object)(Coroutine)value4 != null)
						{
							((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
						}
						__instance.bulletCollisionAudio.volume = 1f;
					}
					break;
				}
				value5 = field6.GetValue(__instance);
				if ((float)value5 >= 0.21f)
				{
					field6.SetValue(__instance, 0f);
					Plugin.AttackTargets(__instance.aimPoint.position, __instance.aimPoint.forward, 30f);
					field12.SetValue(__instance, (object)new Ray(__instance.aimPoint.position, __instance.aimPoint.forward));
					value9 = field12.GetValue(__instance);
					RaycastHit val2 = default(RaycastHit);
					if (Physics.Raycast((Ray)value9, ref val2, 30f, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
					{
						value9 = field12.GetValue(__instance);
						field13.SetValue(__instance, val2);
						value10 = field12.GetValue(__instance);
						Transform transform = ((Component)__instance.bulletCollisionAudio).transform;
						Ray val3 = (Ray)value9;
						val4 = (RaycastHit)value10;
						transform.position = ((Ray)(ref val3)).GetPoint(((RaycastHit)(ref val4)).distance - 0.5f);
					}
				}
				else
				{
					value5 = field6.GetValue(__instance);
					field6.SetValue(__instance, (float)value5 - Time.deltaTime);
				}
				if (((NetworkBehaviour)__instance).IsServer)
				{
					value11 = field14.GetValue(__instance);
					field14.SetValue(__instance, (float)value11 - Time.deltaTime);
					value11 = field14.GetValue(__instance);
					if ((float)value11 <= 0f)
					{
						MethodInfo method3 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
						method3.Invoke(__instance, new object[1] { 0 });
						__instance.SetToModeClientRpc(0);
					}
				}
				break;
			}
			value3 = field4.GetValue(__instance);
			if ((bool)value3)
			{
				__instance.turnTowardsObjectCompass.localEulerAngles = new Vector3(-180f, __instance.turretRod.localEulerAngles.y - Time.deltaTime * 20f, 180f);
				__instance.turretRod.rotation = Quaternion.RotateTowards(__instance.turretRod.rotation, __instance.turnTowardsObjectCompass.rotation, __instance.rotationSpeed * Time.deltaTime);
				return false;
			}
			value6 = field7.GetValue(__instance);
			if ((bool)value6)
			{
				__instance.turnTowardsObjectCompass.localEulerAngles = new Vector3(-180f, Mathf.Clamp(__instance.targetRotation, 0f - __instance.rotationRange, __instance.rotationRange), 180f);
			}
			__instance.turretRod.rotation = Quaternion.RotateTowards(__instance.turretRod.rotation, __instance.turnTowardsObjectCompass.rotation, __instance.rotationSpeed * Time.deltaTime);
			return false;
		}

		public static bool PatchSetTargetToPlayerBody(ref Turret __instance)
		{
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(__instance);
			if ((Object)(object)__instance.targetPlayerWithRotation != (Object)null)
			{
				if (__instance.targetPlayerWithRotation.isPlayerDead)
				{
					value = field.GetValue(__instance);
					if (!(bool)value)
					{
						field.SetValue(__instance, true);
					}
					if ((Object)(object)__instance.targetPlayerWithRotation.deadBody != (Object)null)
					{
						__instance.targetTransform = ((Component)__instance.targetPlayerWithRotation.deadBody.bodyParts[5]).transform;
					}
					FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
					if ((Object)(object)component.targetWithRotation != (Object)null)
					{
						value = field.GetValue(__instance);
						if (!(bool)value)
						{
							field.SetValue(__instance, true);
						}
						value = field.GetValue(__instance);
						if (!((Component)component.targetWithRotation).GetComponent<EnemyAI>().isEnemyDead)
						{
							field.SetValue(__instance, false);
							__instance.targetTransform = ((Component)component.targetWithRotation).transform;
						}
					}
				}
				else
				{
					field.SetValue(__instance, false);
					__instance.targetTransform = ((Component)__instance.targetPlayerWithRotation.gameplayCamera).transform;
				}
			}
			else
			{
				FAIR_AI component2 = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
				if ((Object)(object)component2.targetWithRotation != (Object)null)
				{
					value = field.GetValue(__instance);
					if (!(bool)value)
					{
						field.SetValue(__instance, true);
					}
					value = field.GetValue(__instance);
					if (!((Component)component2.targetWithRotation).GetComponent<EnemyAI>().isEnemyDead)
					{
						field.SetValue(__instance, false);
						__instance.targetTransform = ((Component)component2.targetWithRotation).transform;
					}
				}
			}
			return false;
		}

		public static bool PatchTurnTowardsTargetIfHasLOS(ref Turret __instance)
		{
			//IL_0066: 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)
			//IL_0077: 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_00aa: 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_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(__instance);
			FieldInfo field2 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			object value2 = field.GetValue(__instance);
			FieldInfo field3 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value3 = field.GetValue(__instance);
			if ((bool)value || Vector3.Angle(__instance.targetTransform.position - __instance.centerPoint.position, __instance.forwardFacingPos.forward) > __instance.rotationRange)
			{
				flag = false;
			}
			if (Physics.Linecast(__instance.aimPoint.position, __instance.targetTransform.position, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
			{
				flag = false;
			}
			if (flag)
			{
				field2.SetValue(__instance, true);
				field3.SetValue(__instance, 0f);
				__instance.tempTransform.position = __instance.targetTransform.position;
				Transform tempTransform = __instance.tempTransform;
				tempTransform.position -= Vector3.up * 0.15f;
				__instance.turnTowardsObjectCompass.LookAt(__instance.tempTransform);
				return false;
			}
			value2 = field2.GetValue(__instance);
			if ((bool)value2)
			{
				field2.SetValue(__instance, false);
				field3.SetValue(__instance, 0f);
			}
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				return false;
			}
			value3 = field3.GetValue(__instance);
			field3.SetValue(__instance, (float)value3 + Time.deltaTime);
			value3 = field3.GetValue(__instance);
			if ((float)value3 >= 2f)
			{
				field3.SetValue(__instance, 0f);
				Debug.Log((object)"Turret: LOS timer ended on server. checking for new player target");
				PlayerControllerB val = __instance.CheckForPlayersInLineOfSight(2f, false);
				List<EnemyAI> actualTargets = GetActualTargets(__instance, GetTargets(__instance));
				if ((Object)(object)val != (Object)null)
				{
					__instance.targetPlayerWithRotation = val;
					__instance.SwitchTargetedPlayerClientRpc((int)val.playerClientId, false);
					Debug.Log((object)"Turret: Got new player target");
				}
				else
				{
					Debug.Log((object)"Turret: No new player to target; returning to detection mode.");
					__instance.targetPlayerWithRotation = null;
					__instance.RemoveTargetedPlayerClientRpc();
					FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
					if (actualTargets.Any())
					{
						component.targetWithRotation = actualTargets[0];
						component.SwitchedTargetedEnemyClientRpc(__instance, actualTargets[0]);
					}
					else
					{
						component.targetWithRotation = null;
						component.RemoveTargetedEnemyClientRpc();
					}
				}
			}
			return false;
		}

		public static List<EnemyAI> GetActualTargets(Turret turret, List<EnemyAI> targets)
		{
			List<EnemyAI> enemies = new List<EnemyAI>();
			List<EnemyAI> list = new List<EnemyAI>();
			list.RemoveAll((EnemyAI t) => (Object)(object)t == (Object)null);
			if (list.Any())
			{
				list.ForEach(delegate(EnemyAI target)
				{
					EnemyAI val = ((Component)target).GetComponent<EnemyAICollisionDetect>().mainScript;
					if ((Object)(object)val == (Object)null)
					{
						val = ((Component)target).GetComponent<EnemyAI>();
					}
					if ((Object)(object)val != (Object)null && !val.isEnemyDead && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", val.enemyType.enemyName))
					{
						enemies.Add(val);
					}
				});
			}
			return enemies;
		}

		private static List<EnemyAI> GetTargets(Turret turret, float radius = 2f, bool angleRangeCheck = false)
		{
			List<Transform> list = FindVisibleTargets(turret);
			List<EnemyAI> en = new List<EnemyAI>();
			if (list.Any())
			{
				list.ForEach(delegate(Transform e)
				{
					EnemyAI val = ((Component)e).GetComponent<EnemyAICollisionDetect>().mainScript;
					if ((Object)(object)val == (Object)null)
					{
						val = ((Component)e).GetComponent<EnemyAI>();
					}
					if ((Object)(object)val != (Object)null && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", val.enemyType.enemyName))
					{
						en.Add(val);
					}
				});
			}
			return en;
		}

		public static Vector3 DirectionFromAngle(Turret turret, float angleInDegrees, bool angleIsGlobal)
		{
			//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_0011: 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)
			if (!angleIsGlobal)
			{
				angleInDegrees += ((Component)turret).transform.eulerAngles.y;
			}
			return new Vector3(Mathf.Sin(angleInDegrees * ((float)Math.PI / 180f)), 0f, Mathf.Cos(angleInDegrees * ((float)Math.PI / 180f)));
		}

		public static List<Transform> FindVisibleTargets(Turret turret)
		{
			//IL_0007: 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_003f: 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_0049: 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_0052: 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_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)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(turret.aimPoint.position, viewRadius, Plugin.enemyMask);
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < array.Length; i++)
			{
				Transform transform = ((Component)array[i]).transform;
				Vector3 val = transform.position - turret.aimPoint.position;
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				if (Vector3.Angle(turret.aimPoint.forward, normalized) < viewAngle / 2f)
				{
					float num = Vector3.Distance(turret.aimPoint.position, transform.position);
					if (!Physics.Raycast(turret.aimPoint.position, normalized, num, ~Plugin.enemyMask) && ((Object)(object)((Component)transform).GetComponent<EnemyAICollisionDetect>() != (Object)null || (Object)(object)((Component)transform).GetComponent<EnemyAI>() != (Object)null) && (Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", ((Component)transform).GetComponent<EnemyAICollisionDetect>().mainScript.enemyType.enemyName) || Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", ((Component)transform).GetComponent<EnemyAI>().enemyType.enemyName)))
					{
						list.Add(transform);
					}
				}
			}
			return list;
		}
	}
}
namespace FairAI.Component
{
	internal class BoombaTimer : MonoBehaviour
	{
		private bool isActiveBomb = false;

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine(StartBombTimer());
			Plugin.logger.LogInfo((object)"Boomba has been set active.");
		}

		public IEnumerator StartBombTimer()
		{
			SetActiveBomb(isActive: false);
			yield return (object)new WaitForSeconds(3f);
			SetActiveBomb(isActive: true);
		}

		public void SetActiveBomb(bool isActive)
		{
			isActiveBomb = isActive;
		}

		public bool IsActiveBomb()
		{
			return isActiveBomb;
		}
	}
}

plugins/Core/notnotnotswipez-MoreCompany-1.7.4/MoreCompany.dll

Decompiled 10 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.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using MoreCompany.Cosmetics;
using MoreCompany.Utils;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
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: AssemblyTitle("MoreCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("511a1e5e-0611-49f1-b60f-cec69c668fd8")]
[assembly: AssemblyFileVersion("1.7.4")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.7.4.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];
				AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
				if ((Object)(object)val != (Object)null && 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(new char[1] { ' ' }));
				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(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(chatMessage);
				}
				else if (chatMessage.StartsWith("[morecompanycosmetics]"))
				{
					return false;
				}
			}
			else if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				HandleDataMessage(chatMessage);
			}
			return true;
		}

		private static void HandleDataMessage(string chatMessage)
		{
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			if (ignoreSample)
			{
				return;
			}
			chatMessage = chatMessage.Replace("[morecompanycosmetics]", "");
			string[] array = chatMessage.Split(new char[1] { ';' });
			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(ForestGiantAI __instance)
		{
			if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount)
			{
				__instance.playerStealthMeters = new float[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					__instance.playerStealthMeters[i] = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "Update")]
	public static class SpringManAIUpdatePatch
	{
		public static bool Prefix(SpringManAI __instance, ref float ___timeSinceHittingPlayer, ref float ___stopAndGoMinimumInterval, ref bool ___wasOwnerLastFrame, ref bool ___stoppingMovement, ref float ___currentChaseSpeed, ref bool ___hasStopped, ref float ___currentAnimSpeed, ref float ___updateDestinationInterval, ref Vector3 ___tempVelocity, ref float ___targetYRotation, ref float ___setDestinationToPlayerInterval, ref float ___previousYRotation)
		{
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			UpdateBase((EnemyAI)(object)__instance, ref ___updateDestinationInterval, ref ___tempVelocity, ref ___targetYRotation, ref ___setDestinationToPlayerInterval, ref ___previousYRotation);
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			int currentBehaviourStateIndex = ((EnemyAI)__instance).currentBehaviourStateIndex;
			if (currentBehaviourStateIndex != 0 && currentBehaviourStateIndex == 1)
			{
				if (___timeSinceHittingPlayer >= 0f)
				{
					___timeSinceHittingPlayer -= Time.deltaTime;
				}
				if (((NetworkBehaviour)__instance).IsOwner)
				{
					if (___stopAndGoMinimumInterval > 0f)
					{
						___stopAndGoMinimumInterval -= Time.deltaTime;
					}
					if (!___wasOwnerLastFrame)
					{
						___wasOwnerLastFrame = true;
						if (!___stoppingMovement && ___timeSinceHittingPlayer < 0.12f)
						{
							((EnemyAI)__instance).agent.speed = ___currentChaseSpeed;
						}
						else
						{
							((EnemyAI)__instance).agent.speed = 0f;
						}
					}
					bool flag = false;
					for (int i = 0; i < MainClass.newPlayerCount; i++)
					{
						if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && StartOfRound.Instance.allPlayerScripts[i].HasLineOfSightToPosition(((Component)__instance).transform.position + Vector3.up * 1.6f, 68f, 60, -1f) && Vector3.Distance(((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, ((EnemyAI)__instance).eye.position) > 0.3f)
						{
							flag = true;
						}
					}
					if (((EnemyAI)__instance).stunNormalizedTimer > 0f)
					{
						flag = true;
					}
					if (flag != ___stoppingMovement && ___stopAndGoMinimumInterval <= 0f)
					{
						___stopAndGoMinimumInterval = 0.15f;
						if (flag)
						{
							__instance.SetAnimationStopServerRpc();
						}
						else
						{
							__instance.SetAnimationGoServerRpc();
						}
						___stoppingMovement = flag;
					}
				}
				if (___stoppingMovement)
				{
					if (__instance.animStopPoints.canAnimationStop)
					{
						if (!___hasStopped)
						{
							___hasStopped = true;
							__instance.mainCollider.isTrigger = false;
							if (GameNetworkManager.Instance.localPlayerController.HasLineOfSightToPosition(((Component)__instance).transform.position, 70f, 25, -1f))
							{
								float num = Vector3.Distance(((Component)__instance).transform.position, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position);
								if (num < 4f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.9f, true);
								}
								else if (num < 9f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.4f, true);
								}
							}
							if (___currentAnimSpeed > 2f)
							{
								RoundManager.PlayRandomClip(((EnemyAI)__instance).creatureVoice, __instance.springNoises, false, 1f, 0);
								if (__instance.animStopPoints.animationPosition == 1)
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoing");
								}
								else
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoingPosition2");
								}
							}
						}
						((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", 0f);
						___currentAnimSpeed = 0f;
						if (((NetworkBehaviour)__instance).IsOwner)
						{
							((EnemyAI)__instance).agent.speed = 0f;
							return false;
						}
					}
				}
				else
				{
					if (___hasStopped)
					{
						___hasStopped = false;
						__instance.mainCollider.isTrigger = true;
					}
					___currentAnimSpeed = Mathf.Lerp(___currentAnimSpeed, 6f, 5f * Time.deltaTime);
					((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", ___currentAnimSpeed);
					if (((NetworkBehaviour)__instance).IsOwner)
					{
						((EnemyAI)__instance).agent.speed = Mathf.Lerp(((EnemyAI)__instance).agent.speed, ___currentChaseSpeed, 4.5f * Time.deltaTime);
					}
				}
			}
			return false;
		}

		private static void UpdateBase(EnemyAI __instance, ref float updateDestinationInterval, ref Vector3 tempVelocity, ref float targetYRotation, ref float setDestinationToPlayerInterval, ref float previousYRotation)
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: 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_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: 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_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: 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_0454: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.enemyType.isDaytimeEnemy && !__instance.daytimeEnemyLeaving)
			{
				ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "CheckTimeOfDayToLeave", null);
			}
			if (__instance.stunnedIndefinitely <= 0)
			{
				if ((double)__instance.stunNormalizedTimer >= 0.0)
				{
					__instance.stunNormalizedTimer -= Time.deltaTime / __instance.enemyType.stunTimeMultiplier;
				}
				else
				{
					__instance.stunnedByPlayer = null;
					if ((double)__instance.postStunInvincibilityTimer >= 0.0)
					{
						__instance.postStunInvincibilityTimer -= Time.deltaTime * 5f;
					}
				}
			}
			if (!__instance.ventAnimationFinished && (double)__instance.timeSinceSpawn < (double)__instance.exitVentAnimationTime + 0.004999999888241291 * (double)RoundManager.Instance.numberOfEnemiesInScene)
			{
				__instance.timeSinceSpawn += Time.deltaTime;
				if (!((NetworkBehaviour)__instance).IsOwner)
				{
					Vector3 serverPosition = __instance.serverPosition;
					if (__instance.serverPosition != Vector3.zero)
					{
						((Component)__instance).transform.position = __instance.serverPosition;
						((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, targetYRotation, ((Component)__instance).transform.eulerAngles.z);
					}
				}
				else if ((double)updateDestinationInterval >= 0.0)
				{
					updateDestinationInterval -= Time.deltaTime;
				}
				else
				{
					__instance.SyncPositionToClients();
					updateDestinationInterval = 0.1f;
				}
				return;
			}
			if (!__instance.ventAnimationFinished)
			{
				__instance.ventAnimationFinished = true;
				if ((Object)(object)__instance.creatureAnimator != (Object)null)
				{
					__instance.creatureAnimator.SetBool("inSpawningAnimation", false);
				}
			}
			if (!((NetworkBehaviour)__instance).IsOwner)
			{
				if (__instance.currentSearch.inProgress)
				{
					__instance.StopSearch(__instance.currentSearch, true);
				}
				__instance.SetClientCalculatingAI(false);
				if (!__instance.inSpecialAnimation)
				{
					((Component)__instance).transform.position = Vector3.SmoothDamp(((Component)__instance).transform.position, __instance.serverPosition, ref tempVelocity, __instance.syncMovementSpeed);
					((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, Mathf.LerpAngle(((Component)__instance).transform.eulerAngles.y, targetYRotation, 15f * Time.deltaTime), ((Component)__instance).transform.eulerAngles.z);
				}
				__instance.timeSinceSpawn += Time.deltaTime;
				return;
			}
			if (__instance.isEnemyDead)
			{
				__instance.SetClientCalculatingAI(false);
				return;
			}
			if (!__instance.inSpecialAnimation)
			{
				__instance.SetClientCalculatingAI(true);
			}
			if (__instance.movingTowardsTargetPlayer && (Object)(object)__instance.targetPlayer != (Object)null)
			{
				if ((double)setDestinationToPlayerInterval <= 0.0)
				{
					setDestinationToPlayerInterval = 0.25f;
					__instance.destination = RoundManager.Instance.GetNavMeshPosition(((Component)__instance.targetPlayer).transform.position, RoundManager.Instance.navHit, 2.7f, -1);
				}
				else
				{
					__instance.destination = new Vector3(((Component)__instance.targetPlayer).transform.position.x, __instance.destination.y, ((Component)__instance.targetPlayer).transform.position.z);
					setDestinationToPlayerInterval -= Time.deltaTime;
				}
			}
			if (__instance.inSpecialAnimation)
			{
				return;
			}
			if ((double)updateDestinationInterval >= 0.0)
			{
				updateDestinationInterval -= Time.deltaTime;
			}
			else
			{
				__instance.DoAIInterval();
				updateDestinationInterval = __instance.AIIntervalTime;
			}
			if (!((double)Mathf.Abs(previousYRotation - ((Component)__instance).transform.eulerAngles.y) <= 6.0))
			{
				previousYRotation = ((Component)__instance).transform.eulerAngles.y;
				targetYRotation = previousYRotation;
				if (((NetworkBehaviour)__instance).IsServer)
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationClientRpc", new object[1] { (short)previousYRotation });
				}
				else
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationServerRpc", new object[1] { (short)previousYRotation });
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
	public static class SpringManAIIntervalPatch
	{
		public static bool Prefix(SpringManAI __instance)
		{
			//IL_0013: 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_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).moveTowardsDestination)
			{
				((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination);
			}
			((EnemyAI)__instance).SyncPositionToClients();
			if (StartOfRound.Instance.allPlayersDead)
			{
				return false;
			}
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			switch (((EnemyAI)__instance).currentBehaviourStateIndex)
			{
			default:
				return false;
			case 1:
				if (__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).StopSearch(__instance.searchForPlayers, true);
				}
				if (((EnemyAI)__instance).TargetClosestPlayer(1.5f, false, 70f))
				{
					PlayerControllerB fieldValue = ReflectionUtils.GetFieldValue<PlayerControllerB>(__instance, "previousTarget");
					if ((Object)(object)fieldValue != (Object)(object)((EnemyAI)__instance).targetPlayer)
					{
						ReflectionUtils.SetFieldValue(__instance, "previousTarget", ((EnemyAI)__instance).targetPlayer);
						((EnemyAI)__instance).ChangeOwnershipOfEnemy(((EnemyAI)__instance).targetPlayer.actualClientId);
					}
					((EnemyAI)__instance).movingTowardsTargetPlayer = true;
					return false;
				}
				((EnemyAI)__instance).SwitchToBehaviourState(0);
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
				break;
			case 0:
			{
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
					return false;
				}
				for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
				{
					if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && !Physics.Linecast(((Component)__instance).transform.position + Vector3.up * 0.5f, ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault) && Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 30f)
					{
						((EnemyAI)__instance).SwitchToBehaviourState(1);
						return false;
					}
				}
				if (!__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).movingTowardsTargetPlayer = false;
					((EnemyAI)__instance).StartSearch(((Component)__instance).transform.position, __instance.searchForPlayers);
					return false;
				}
				break;
			}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
	public static class GetClosestPlayerPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB __result, bool requireLineOfSight = false, bool cannotBeInShip = false, bool cannotBeNearShip = false)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: 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)
			PlayerControllerB val = null;
			__instance.mostOptimalDistance = 2000f;
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], cannotBeInShip, false))
				{
					continue;
				}
				if (cannotBeNearShip)
				{
					if (StartOfRound.Instance.allPlayerScripts[i].isInElevator)
					{
						continue;
					}
					bool flag = false;
					for (int j = 0; j < RoundManager.Instance.spawnDenialPoints.Length; j++)
					{
						if (Vector3.Distance(RoundManager.Instance.spawnDenialPoints[j].transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 10f)
						{
							flag = true;
							break;
						}
					}
					if (flag)
					{
						continue;
					}
				}
				if (!requireLineOfSight || !Physics.Linecast(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position, 256))
				{
					__instance.tempDist = Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position);
					if (__instance.tempDist < __instance.mostOptimalDistance)
					{
						__instance.mostOptimalDistance = __instance.tempDist;
						val = StartOfRound.Instance.allPlayerScripts[i];
					}
				}
			}
			__result = val;
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")]
	public static class GetAllPlayersInLineOfSightPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB[] __result, float width = 45f, int range = 60, Transform eyeObject = null, float proximityCheck = -1f, int layerMask = -1)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//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_00c0: 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_00d2: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: 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_0104: 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_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			if (layerMask == -1)
			{
				layerMask = StartOfRound.Instance.collidersAndRoomMaskAndDefault;
			}
			if ((Object)(object)eyeObject == (Object)null)
			{
				eyeObject = __instance.eye;
			}
			if (__instance.enemyType.isOutsideEnemy && !__instance.enemyType.canSeeThroughFog && (int)TimeOfDay.Instance.currentLevelWeather == 3)
			{
				range = Mathf.Clamp(range, 0, 30);
			}
			List<PlayerControllerB> list = new List<PlayerControllerB>(MainClass.newPlayerCount);
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false))
				{
					continue;
				}
				Vector3 position = ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position;
				if (Vector3.Distance(__instance.eye.position, position) < (float)range && !Physics.Linecast(eyeObject.position, position, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
				{
					Vector3 val = position - eyeObject.position;
					if (Vector3.Angle(eyeObject.forward, val) < width || Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < proximityCheck)
					{
						list.Add(StartOfRound.Instance.allPlayerScripts[i]);
					}
				}
			}
			if (list.Count == MainClass.newPlayerCount)
			{
				__result = StartOfRound.Instance.allPlayerScripts;
				return false;
			}
			if (list.Count > 0)
			{
				__result = list.ToArray();
				return false;
			}
			__result = null;
			return false;
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static bool Prefix(DressGirlAI __instance)
		{
			ReflectionUtils.SetFieldValue(__instance, "timesChoosingAPlayer", ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") + 1);
			if (ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") > 1)
			{
				__instance.timer = __instance.hauntInterval - 1f;
			}
			__instance.SFXVolumeLerpTo = 0f;
			((EnemyAI)__instance).creatureVoice.Stop();
			__instance.heartbeatMusic.volume = 0f;
			if (!ReflectionUtils.GetFieldValue<bool>(__instance, "initializedRandomSeed"))
			{
				ReflectionUtils.SetFieldValue(__instance, "ghostGirlRandom", new Random(StartOfRound.Instance.randomMapSeed + 158));
			}
			float num = 0f;
			float num2 = 0f;
			int num3 = 0;
			int num4 = 0;
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount > num3)
				{
					num3 = StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount;
					num4 = i;
				}
				if (StartOfRound.Instance.allPlayerScripts[i].insanityLevel > num)
				{
					num = StartOfRound.Instance.allPlayerScripts[i].insanityLevel;
					num2 = i;
				}
			}
			int[] array = new int[MainClass.newPlayerCount];
			for (int j = 0; j < MainClass.newPlayerCount; j++)
			{
				if (!StartOfRound.Instance.allPlayerScripts[j].isPlayerControlled)
				{
					array[j] = 0;
					continue;
				}
				array[j] += 80;
				if (num2 == (float)j && num > 1f)
				{
					array[j] += 50;
				}
				if (num4 == j)
				{
					array[j] += 30;
				}
				if (!StartOfRound.Instance.allPlayerScripts[j].hasBeenCriticallyInjured)
				{
					array[j] += 10;
				}
				if ((Object)(object)StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer != (Object)null && StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer.scrapValue > 150)
				{
					array[j] += 30;
				}
			}
			__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[RoundManager.Instance.GetRandomWeightedIndex(array, ReflectionUtils.GetFieldValue<Random>(__instance, "ghostGirlRandom"))];
			if (__instance.hauntingPlayer.isPlayerDead)
			{
				for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
				{
					if (!StartOfRound.Instance.allPlayerScripts[k].isPlayerDead)
					{
						__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[k];
						break;
					}
				}
			}
			Debug.Log((object)$"Little girl: Haunting player with playerClientId: {__instance.hauntingPlayer.playerClientId}; actualClientId: {__instance.hauntingPlayer.actualClientId}");
			((EnemyAI)__instance).ChangeOwnershipOfEnemy(__instance.hauntingPlayer.actualClientId);
			__instance.hauntingLocalPlayer = (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance.hauntingPlayer;
			if (ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine") != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine"));
			}
			ReflectionUtils.SetFieldValue(__instance, "switchHauntedPlayerCoroutine", ((MonoBehaviour)__instance).StartCoroutine(ReflectionUtils.InvokeMethod<IEnumerator>(__instance, "setSwitchingHauntingPlayer", null)));
			return false;
		}
	}
	[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 void Postfix(MenuManager __instance)
		{
			//IL_0076: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
				GameObject gameObject2 = ((Component)gameObject.transform.Find("MenuContainer").Find("MainButtons").Find("HeaderImage")).gameObject;
				Image component = gameObject2.GetComponent<Image>();
				MainClass.ReadSettingsFromFile();
				component.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));
				CosmeticRegistry.SpawnCosmeticGUI();
				Transform val = gameObject.transform.Find("MenuContainer").Find("LobbyHostSettings").Find("HostSettingsContainer")
					.Find("LobbyHostOptions")
					.Find("OptionsNormal");
				GameObject val2 = Object.Instantiate<GameObject>(MainClass.crewCountUI, val);
				RectTransform component2 = val2.GetComponent<RectTransform>();
				((Transform)component2).localPosition = new Vector3(96.9f, -70f, -6.7f);
				TMP_InputField inputField = ((Component)val2.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>();
				inputField.characterLimit = 3;
				inputField.text = MainClass.newPlayerCount.ToString();
				((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s)
				{
					if (int.TryParse(s, out var result))
					{
						MainClass.newPlayerCount = result;
						MainClass.newPlayerCount = Mathf.Clamp(MainClass.newPlayerCount, 1, MainClass.maxPlayerCount);
						inputField.text = MainClass.newPlayerCount.ToString();
						MainClass.SaveSettingsToFile();
					}
					else if (s.Length != 0)
					{
						inputField.text = MainClass.newPlayerCount.ToString();
						inputField.caretPosition = 1;
					}
				});
			}
			catch (Exception)
			{
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
	public static class AddUserPlayerListPatch
	{
		public 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(QuickMenuManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")]
	public static class QuickMenuDisplayPatch
	{
		public static bool Prefix(QuickMenuManager __instance, ref bool __result)
		{
			__result = true;
			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_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Expected O, but got Unknown
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: 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 (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
				{
					Debug.Log((object)$"[Event]: {finalIndex}");
					__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 TestPatch
	{
		[HarmonyPrefix]
		public static bool Prefix(QuickMenuManager __instance, int ___playerObjToKick)
		{
			Debug.Log((object)__instance.ConfirmKickUserPanel);
			Debug.Log((object)___playerObjToKick);
			if (___playerObjToKick > 0)
			{
				StartOfRound.Instance.KickPlayer(___playerObjToKick);
				__instance.ConfirmKickUserPanel.SetActive(false);
			}
			else
			{
				Debug.Log((object)$"[FATAL]: ID: {___playerObjToKick} is the HOST!");
				__instance.ConfirmKickUserPanel.SetActive(false);
			}
			return false;
		}
	}
	[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), "FillEndGameStats")]
	public static class HudFillEndGameFix
	{
		public static bool Prefix(HUDManager __instance, EndOfGameStats stats)
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Invalid comparison between Unknown and I4
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < __instance.statsUIElements.playerNamesText.Length; i++)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[i];
				((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = "";
				((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = false;
				((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "Notes: \n";
				if (val.disconnectedMidGame || val.isPlayerDead || val.isPlayerControlled)
				{
					if (val.isPlayerDead)
					{
						num++;
					}
					else if (val.isPlayerControlled)
					{
						num2++;
					}
					((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = __instance.playersManager.allPlayerScripts[i].playerUsername;
					((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = true;
					if (__instance.playersManager.allPlayerScripts[i].isPlayerDead)
					{
						if ((int)__instance.playersManager.allPlayerScripts[i].causeOfDeath == 10)
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.missingIcon;
						}
						else
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.deceasedIcon;
						}
					}
					else
					{
						__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.aliveIcon;
					}
					for (int j = 0; j < 3 && j < stats.allPlayerStats[i].playerNotes.Count; j++)
					{
						TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i];
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + stats.allPlayerStats[i].playerNotes[j] + "\n";
					}
				}
				else
				{
					((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "";
				}
			}
			((TMP_Text)__instance.statsUIElements.quotaNumerator).text = RoundManager.Instance.scrapCollectedInLevel.ToString();
			((TMP_Text)__instance.statsUIElements.quotaDenominator).text = RoundManager.Instance.totalScrapValueInLevel.ToString();
			if (StartOfRound.Instance.allPlayersDead)
			{
				((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = true;
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "F";
				return false;
			}
			((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = false;
			int num3 = 0;
			float num4 = (float)RoundManager.Instance.scrapCollectedInLevel / RoundManager.Instance.totalScrapValueInLevel;
			if (num2 == StartOfRound.Instance.connectedPlayersAmount + 1)
			{
				num3++;
			}
			else if (num > 1)
			{
				num3--;
			}
			if (num4 >= 0.99f)
			{
				num3 += 2;
			}
			else if (num4 >= 0.6f)
			{
				num3++;
			}
			else if (num4 <= 0.25f)
			{
				num3--;
			}
			switch (num3)
			{
			case -1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "D";
				return false;
			case 0:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "C";
				return false;
			case 1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "B";
				return false;
			case 2:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "A";
				return false;
			case 3:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "S";
				return false;
			default:
				return false;
			}
		}
	}
	[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 static class PluginInformation
	{
		public const string PLUGIN_NAME = "MoreCompany";

		public const string PLUGIN_VERSION = "1.7.4";

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

		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));
			}
			ManualHarmonyPatches.ManualPatch(val);
			StaticLogger.LogInfo((object)"Loading MoreCompany...");
			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);
			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)"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);
				}
			}
		}

		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 = int.Parse(array[0]);
					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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length == newPlayerCount)
			{
				return;
			}
			playerIdsAndCosmetics.Clear();
			uint num = 10000u;
			int num2 = newPlayerCount - instance.allPlayerObjects.Length;
			int num3 = instance.allPlayerObjects.Length;
			GameObject val = instance.allPlayerObjects[3];
			for (int i = 0; i < num2; i++)
			{
				uint num4 = num + (uint)i;
				GameObject val2 = Object.Instantiate<GameObject>(val);
				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})";
				val2.transform.parent = null;
				PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>();
				notSupposedToExistPlayers.Add(componentInChildren);
				componentInChildren.playerClientId = (ulong)(4 + i);
				componentInChildren.isPlayerControlled = false;
				componentInChildren.isPlayerDead = false;
				componentInChildren.DropAllHeldItems(false, false);
				componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true);
				UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false);
				Array.Resize(ref instance.allPlayerObjects, instance.allPlayerObjects.Length + 1);
				Array.Resize(ref instance.allPlayerScripts, instance.allPlayerScripts.Length + 1);
				Array.Resize(ref instance.gameStats.allPlayerStats, instance.gameStats.allPlayerStats.Length + 1);
				Array.Resize(ref instance.playerSpawnPositions, instance.playerSpawnPositions.Length + 1);
				instance.allPlayerObjects[num3 + i] = val2;
				instance.gameStats.allPlayerStats[num3 + i] = new PlayerStats();
				instance.allPlayerScripts[num3 + i] = componentInChildren;
				instance.playerSpawnPositions[num3 + i] = instance.playerSpawnPositions[3];
			}
		}

		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);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")]
	public static class SendNewPlayerValuesServerRpcPatch
	{
		public static ulong lastId;

		public static void Prefix(PlayerControllerB __instance, ulong newPlayerSteamId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				lastId = newPlayerSteamId;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")]
	public static class SendNewPlayerValuesClientRpcPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return;
			}
			if (StartOfRound.Instance.mapScreen.radarTargets.Count != MainClass.newPlayerCount)
			{
				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));
			}
			if (!networkManager.IsServer)
			{
				return;
			}
			List<ulong> list = new List<ulong>();
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (i == (int)__instance.playerClientId)
				{
					list.Add(SendNewPlayerValuesServerRpcPatch.lastId);
				}
				else
				{
					list.Add(__instance.playersManager.allPlayerScripts[i].playerSteamId);
				}
			}
			playerSteamIds = list.ToArray();
		}
	}
	public static class HUDManagerBullshitPatch
	{
		public static bool ManualPrefix(HUDManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
	public static class SyncShipUnlockablePatch
	{
		public static void Prefix(StartOfRound __instance, ref int[] playerSuitIDs, bool shipLightsOn, Vector3[] placeableObjectPositions, Vector3[] placeableObjectRotations, int[] placeableObjects, int[] storedItems, int[] scrapValues, int[] itemSaveData)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				int[] array = new int[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					array[i] = __instance.allPlayerScripts[i].currentSuitID;
				}
				playerSuitIDs = array;
			}
		}
	}
	[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 bool Prefix(ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(NetworkConnectionManager), "HandleConnectionApproval")]
	public static class ConnectionApprovalTest
	{
		public static void Prefix(ulong ownerClientId, ConnectionApprovalResponse response)
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				if (StartOfRound.Instance.connectedPlayersAmount >= MainClass.newPlayerCount)
				{
					response.Approved = false;
					response.Reason = "Server is full";
				}
				else
				{
					response.Approved = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
	public static class LobbyThingPatch
	{
		public static void Prefix(ref int maxMembers)
		{
			MainClass.ReadSettingsFromFile();
			maxMembers = MainClass.newPlayerCount;
		}
	}
	public class ManualHarmonyPatches
	{
		public static void ManualPatch(Harmony HarmonyInstance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[0], (Type[])null), new HarmonyMethod(typeof(HUDManagerBullshitPatch).GetMethod("ManualPrefix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_00d2: 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 (!((Object)(object)__instance.mimickingPlayer != (Object)null))
				{
					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(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
	{
		public static bool Prefix(PlayerControllerB __instance)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			if ((Object)(object)__instance.spectatedPlayerScript != (Object)null)
			{
				num = (int)__instance.spectatedPlayerScript.playerClientId;
			}
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				num = (num + 1) % MainClass.newPlayerCount;
				if (!__instance.playersManager.allPlayerScripts[num].isPlayerDead && __instance.playersManager.allPlayerScripts[num].isPlayerControlled && (Object)(object)__instance.playersManager.allPlayerScripts[num] != (Object)(object)__instance)
				{
					__instance.spectatedPlayerScript = __instance.playersManager.allPlayerScripts[num];
					__instance.SetSpectatedPlayerEffects(false);
					return false;
				}
			}
			if ((Object)(object)__instance.deadBody != (Object)null && ((Component)__instance.deadBody).gameObject.activeSelf)
			{
				__instance.spectateCameraPivot.position = __instance.deadBody.bodyParts[0].position;
				ReflectionUtils.InvokeMethod(__instance, "RaycastSpectateCameraAroundPivot", null);
			}
			StartOfRound.Instance.SetPlayerSafeInShip();
			return false;
		}
	}
	[HarmonyPatch(typeof(SoundManager), "Start")]
	public static class SoundManagerStartPatch
	{
		public static void Postfix()
		{
			int num = MainClass.newPlayerCount - 4;
			int num2 = 4;
			for (int i = 0; i < num; i++)
			{
				Array.Resize(ref SoundManager.Instance.playerVoicePitches, SoundManager.Instance.playerVoicePitches.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchTargets, SoundManager.Instance.playerVoicePitchTargets.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceVolumes, SoundManager.Instance.playerVoiceVolumes.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchLerpSpeed, SoundManager.Instance.playerVoicePitchLerpSpeed.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceMixers, SoundManager.Instance.playerVoiceMixers.Length + 1);
				AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice")));
				SoundManager.Instance.playerVoicePitches[num2 + i] = 1f;
				SoundManager.Instance.playerVoicePitchTargets[num2 + i] = 1f;
				SoundManager.Instance.playerVoiceVolumes[num2 + i] = 0.5f;
				SoundManager.Instance.playerVoicePitchLerpSpeed[num2 + i] = 3f;
				SoundManager.Instance.playerVoiceMixers[num2 + i] = val;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
	public static class SpawnPositionClampPatch
	{
		public static void Prefix(ref int playerNum, bool simpleTeleport = false)
		{
			if (playerNum > 3)
			{
				playerNum = 3;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
	public static class OnClientConnectedPatch
	{
		public static bool Prefix(StartOfRound __instance, ulong clientId)
		{
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				return false;
			}
			Debug.Log((object)"player connected");
			Debug.Log((object)$"connected players #: {__instance.connectedPlayersAmount}");
			try
			{
				List<int> list = __instance.ClientPlayerList.Values.ToList();
				Debug.Log((object)$"Connecting new player on host; clientId: {clientId}");
				int num = 0;
				for (int i = 1; i < MainClass.newPlayerCount; i++)
				{
					if (!list.Contains(i))
					{
						num = i;
						break;
					}
				}
				__instance.allPlayerScripts[num].actualClientId = clientId;
				__instance.allPlayerObjects[num].GetComponent<NetworkObject>().ChangeOwnership(clientId);
				Debug.Log((object)$"New player assigned object id: {__instance.allPlayerObjects[num]}");
				List<ulong> list2 = new List<ulong>();
				for (int j = 0; j < __instance.allPlayerObjects.Length; j++)
				{
					NetworkObject component = __instance.allPlayerObjects[j].GetComponent<NetworkObject>();
					if (!component.IsOwnedByServer)
					{
						list2.Add(component.OwnerClientId);
					}
					else if (j == 0)
					{
						list2.Add(NetworkManager.Singleton.LocalClientId);
					}
					else
					{
						list2.Add(999uL);
					}
				}
				int groupCredits = Object.FindObjectOfType<Terminal>().groupCredits;
				int profitQuota = TimeOfDay.Instance.profitQuota;
				int quotaFulfilled = TimeOfDay.Instance.quotaFulfilled;
				int num2 = (int)TimeOfDay.Instance.timeUntilDeadline;
				ReflectionUtils.InvokeMethod(__instance, "OnPlayerConnectedClientRpc", new object[11]
				{
					clientId,
					__instance.connectedPlayersAmount,
					list2.ToArray(),
					num,
					groupCredits,
					__instance.currentLevelID,
					profitQuota,
					num2,
					quotaFulfilled,
					__instance.randomMapSeed,
					__instance.isChallengeFile
				});
				__instance.ClientPlayerList.Add(clientId, num);
				Debug.Log((object)$"client id connecting: {clientId} ; their corresponding player object id: {num}");
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"Error occured in OnClientConnected! Shutting server down. clientId: {clientId}. Error: {arg}");
				GameNetworkManager.Instance.disconnectionReasonMessage = "Error occured when a player attempted to join the server! Restart the application and please report the glitch!";
				GameNetworkManager.Instance.Disconnect();
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(SteamLobbyManager), "LoadServerList")]
	public static class LoadServerListPatch
	{
		public static bool Prefix(SteamLobbyManager __instance)
		{
			OverrideMethod(__instance);
			return false;
		}

		private static async void OverrideMethod(SteamLobbyManager __instance)
		{
			if (GameNetworkManager.Instance.waitingForLobbyDataRefresh)
			{
				return;
			}
			ReflectionUtils.SetFieldValue(__instance, "refreshServerListTimer", 0f);
			((TMP_Text)__instance.serverListBlankText).text = "Loading server list...";
			ReflectionUtils.GetFieldValue<Lobby[]>(__instance, "currentLobbyList");
			LobbySlot[] array = Object.FindObjectsOfType<LobbySlot>();
			for (int i = 0; i < array.Length; i++)
			{
				Object.Destroy((Object)(object)((Component)array[i]).gameObject);
			}
			LobbyQuery val;
			switch (__instance.sortByDistanceSetting)
			{
			case 0:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceClose();
				break;
			case 1:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceFar();
				break;
			case 2:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceWorldwide();
				break;
			}
			Debug.Log((object)"Requested server list");
			GameNetworkManager.Instance.waitingForLobbyDataRefresh = true;
			Lobby[] currentLobbyList;
			switch (__instance.sortByDistanceSetting)
			{
			case 0:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceClose();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			case 1:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceFar();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			default:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceWorldwide();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			}
			GameNetworkManager.Instance.waitingForLobbyDataRefresh = false;
			if (currentLobbyList != null)
			{
				Debug.Log((object)"Got lobby list!");
				ReflectionUtils.InvokeMethod(__instance, "DebugLogServerList", null);
				if (currentLobbyList.Length == 0)
				{
					((TMP_Text)__instance.serverListBlankText).text = "No available servers to join.";
				}
				else
				{
					((TMP_Text)__instance.serverListBlankText).text = "";
				}
				ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", 0f);
				for (int j = 0; j < currentLobbyList.Length; j++)
				{
					Friend[] array2 = SteamFriends.GetBlocked().ToArray();
					if (array2 != null)
					{
						for (int k = 0; k < array2.Length; k++)
						{
							Debug.Log((object)$"blocked user: {((Friend)(ref array2[k])).Name}; id: {array2[k].Id}");
							if (((Lobby)(ref currentLobbyList[j])).IsOwnedBy(array2[k].Id))
							{
								Debug.Log((object)("Hiding lobby by blocked user: " + ((Friend)(ref array2[k])).Name));
							}
						}
					}
					else
					{
						Debug.Log((object)"Blocked users list is null");
					}
					GameObject gameObject = Object.Instantiate<GameObject>(__instance.LobbySlotPrefab, __instance.levelListContainer);
					gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, 0f + ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset"));
					ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset") - 42f);
					LobbySlot componentInChildren = gameObject.GetComponentInChildren<LobbySlot>();
					((TMP_Text)componentInChildren.LobbyName).text = ((Lobby)(ref currentLobbyList[j])).GetData("name");
					((TMP_Text)componentInChildren.playerCount).text = $"{((Lobby)(ref currentLobbyList[j])).MemberCount} / {((Lobby)(ref currentLobbyList[j])).MaxMembers}";
					componentInChildren.lobbyId = ((Lobby)(ref currentLobbyList[j])).Id;
					componentInChildren.thisLobby = currentLobbyList[j];
					ReflectionUtils.SetFieldValue(__instance, "currentLobbyList", currentLobbyList);
				}
			}
			else
			{
				Debug.Log((object)"Lobby list is null after request.");
				((TMP_Text)__instance.serverListBlankText).text = "No available servers to join.";
			}
		}
	}
	[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;
		}
	}
}

plugins/Core/Sv_Matt-HideModList-1.0.1/HideModList.dll

Decompiled 10 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[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("HideModList")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Hides the LC api modlist info")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("HideModList")]
[assembly: AssemblyTitle("HideModList")]
[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 HideModList
{
	[HarmonyPatch(typeof(HUDManager), "DisplayTip")]
	public static class DisplayTipPatch
	{
		public static bool Prefix(HUDManager __instance, string headerText, string bodyText, bool isWarning = false, bool useSave = false, string prefsKey = "LC_Tip1")
		{
			if (headerText.StartsWith("Mod List"))
			{
				return false;
			}
			return true;
		}
	}
	[BepInPlugin("HideModList", "HideModList", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Harmony val = new Harmony("plugin.HideModList");
			val.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin HideModList is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "HideModList";

		public const string PLUGIN_NAME = "HideModList";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/Core/Sligili-HDLethalCompany-1.5.6 (1)/HDLethalCompany.dll

Decompiled 10 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.Configuration;
using GameNetcodeStuff;
using HDLethalCompany.Patch;
using HDLethalCompany.Tools;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HDLethalCompanyRemake")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HDLethalCompanyRemake")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("7f379bc1-1fd4-4c72-9247-a181862eec6b")]
[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 HDLethalCompany
{
	[BepInPlugin("HDLethalCompany", "HDLethalCompany-Sligili", "1.5.6")]
	public class HDLethalCompanyInitialization : BaseUnityPlugin
	{
		private static ConfigEntry<float> config_ResMult;

		private static ConfigEntry<bool> config_EnablePostProcessing;

		private static ConfigEntry<bool> config_EnableFog;

		private static ConfigEntry<bool> config_EnableAntialiasing;

		private static ConfigEntry<bool> config_EnableResolution;

		private static ConfigEntry<bool> config_EnableFoliage;

		private static ConfigEntry<int> config_FogQuality;

		private static ConfigEntry<int> config_TextureQuality;

		private static ConfigEntry<int> config_LOD;

		private static ConfigEntry<int> config_ShadowmapQuality;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"HDLethalCompany loaded");
			ConfigFile();
			GraphicsPatch.assetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HDLethalCompany/hdlethalcompany"));
			_harmony = new Harmony("HDLethalCompany");
			_harmony.PatchAll(typeof(GraphicsPatch));
		}

		private void ConfigFile()
		{
			config_ResMult = ((BaseUnityPlugin)this).Config.Bind<float>("RESOLUTION", "Value", 2.233f, "Resolution Scale Multiplier - <EXAMPLES -> | 1.000 = 860x520p | 2.233 =~ 1920x1080p | 2.977 = 2560x1440p | 4.465 = 3840x2060p > - The UI scanned elements have slightly incorrect offsets after 3.000");
			config_EnableResolution = ((BaseUnityPlugin)this).Config.Bind<bool>("RESOLUTION", "EnableRes", true, "Resolution Fix - In case you wanna use another resolution mod or apply any widescreen mod while keeping the graphics settings");
			config_EnableAntialiasing = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableAA", false, "Anti-Aliasing (Unity's SMAA)");
			config_EnablePostProcessing = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnablePP", true, "Post-Processing (Color grading)");
			config_TextureQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "TextureQuality", 3, "Texture Resolution Quality - <PRESETS -> | 0 = VERY LOW (1/8) | 1 = LOW (1/4) | 2 = MEDIUM (1/2) | 3 = HIGH (1/1 VANILLA) >");
			config_FogQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "FogQuality", 1, "Volumetric Fog Quality - <PRESETS -> | 0 = VERY LOW | 1 = VANILLA FOG | 2 = MEDIUM | 3 = HIGH >");
			config_EnableFog = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableFOG", true, "Volumetric Fog Toggle - Use this as a last resource in case lowering the fog quality is not enough to get decent performance");
			config_LOD = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "LOD", 1, "Level Of Detail - <PRESETS -> | 0 = LOW (HALF DISTANCE) | 1 = VANILLA | 2 = HIGH (TWICE THE DISTANCE) >");
			config_ShadowmapQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "ShadowQuality", 3, "Shadows Resolution - <PRESETS -> 0 = VERY LOW (SHADOWS DISABLED)| 1 = LOW (256) | 2 = MEDIUM (1024) | 3 = VANILLA (2048) > - Shadowmap max resolution");
			config_EnableFoliage = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableF", true, "Foliage Toggle - If the game camera should or not render bushes/grass (trees won't be affected)");
			GraphicsPatch.m_enableFoliage = config_EnableFoliage.Value;
			GraphicsPatch.m_enableResolutionFix = config_EnableResolution.Value;
			GraphicsPatch.m_setShadowQuality = config_ShadowmapQuality.Value;
			GraphicsPatch.m_setLOD = config_LOD.Value;
			GraphicsPatch.m_setTextureResolution = config_TextureQuality.Value;
			GraphicsPatch.m_setFogQuality = config_FogQuality.Value;
			GraphicsPatch.multiplier = config_ResMult.Value;
			GraphicsPatch.anchorOffsetZ = 0.123f * config_ResMult.Value + 0.877f;
			GraphicsPatch.m_widthResolution = 860f * config_ResMult.Value;
			GraphicsPatch.m_heightResolution = 520f * config_ResMult.Value;
			GraphicsPatch.m_enableAntiAliasing = config_EnableAntialiasing.Value;
			GraphicsPatch.m_enableFog = config_EnableFog.Value;
			GraphicsPatch.m_enablePostProcessing = config_EnablePostProcessing.Value;
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "HDLethalCompany";

		public const string Name = "HDLethalCompany-Sligili";

		public const string Ver = "1.5.6";
	}
}
namespace HDLethalCompany.Tools
{
	public class Reflection
	{
		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 CallMethod(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;
		}
	}
}
namespace HDLethalCompany.Patch
{
	internal class GraphicsPatch
	{
		public static bool m_enablePostProcessing;

		public static bool m_enableFog;

		public static bool m_enableAntiAliasing;

		public static bool m_enableResolutionFix;

		public static bool m_enableFoliage = true;

		public static int m_setFogQuality;

		public static int m_setTextureResolution;

		public static int m_setLOD;

		public static int m_setShadowQuality;

		private static HDRenderPipelineAsset myAsset;

		public static AssetBundle assetBundle;

		public static float anchorOffsetX = 439.48f;

		public static float anchorOffsetY = 244.8f;

		public static float anchorOffsetZ;

		public static float multiplier;

		public static float m_widthResolution;

		public static float m_heightResolution;

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPrefix]
		private static void StartPrefix(PlayerControllerB __instance)
		{
			//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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			Object[] array = Resources.FindObjectsOfTypeAll(typeof(HDAdditionalCameraData));
			foreach (Object obj in array)
			{
				HDAdditionalCameraData val = (HDAdditionalCameraData)(object)((obj is HDAdditionalCameraData) ? obj : null);
				if (!(((Object)((Component)val).gameObject).name == "MapCamera"))
				{
					val.customRenderingSettings = true;
					ToggleCustomPass(val, m_enablePostProcessing);
					SetLevelOfDetail(val);
					ToggleVolumetricFog(val, m_enableFog);
					if (!m_enableFoliage)
					{
						LayerMask val2 = LayerMask.op_Implicit(((Component)val).GetComponent<Camera>().cullingMask);
						val2 = LayerMask.op_Implicit(LayerMask.op_Implicit(val2) & -1025);
						((Component)val).GetComponent<Camera>().cullingMask = LayerMask.op_Implicit(val2);
					}
					SetShadowQuality(assetBundle, val);
					if (!(((Object)((Component)val).gameObject).name == "SecurityCamera") && !(((Object)((Component)val).gameObject).name == "ShipCamera"))
					{
						SetAntiAliasing(val);
					}
				}
			}
			array = null;
			SetTextureQuality();
			SetFogQuality();
			if (m_enableResolutionFix && multiplier != 1f)
			{
				int width = (int)Math.Round(m_widthResolution, 0);
				int height = (int)Math.Round(m_heightResolution, 0);
				((Texture)__instance.gameplayCamera.targetTexture).width = width;
				((Texture)__instance.gameplayCamera.targetTexture).height = height;
			}
		}

		[HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")]
		[HarmonyPrefix]
		private static void RoundPostFix()
		{
			SetFogQuality();
			if (m_setLOD == 0)
			{
				RemoveLodFromGameObject("CatwalkStairs");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "UpdateScanNodes")]
		[HarmonyPostfix]
		private static void UpdateScanNodesPostfix(PlayerControllerB playerScript, HUDManager __instance)
		{
			//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_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			if (anchorOffsetZ > 1.238f)
			{
				anchorOffsetZ = 1.238f;
			}
			if (!m_enableResolutionFix || multiplier == 1f)
			{
				return;
			}
			Vector3 zero = Vector3.zero;
			bool flag = false;
			for (int i = 0; i < __instance.scanElements.Length; i++)
			{
				if ((Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).Count > 0 && (Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).TryGetValue(__instance.scanElements[i], out var value) && (Object)(object)value != (Object)null)
				{
					try
					{
						if ((bool)Reflection.CallMethod(__instance, "NodeIsNotVisible", value, i))
						{
							continue;
						}
						if (!((Component)__instance.scanElements[i]).gameObject.activeSelf)
						{
							((Component)__instance.scanElements[i]).gameObject.SetActive(true);
							((Component)__instance.scanElements[i]).GetComponent<Animator>().SetInteger("colorNumber", value.nodeType);
							if (value.creatureScanID != -1)
							{
								Traverse.Create((object)__instance).Method("AttemptScanNewCreature", new object[1] { value.creatureScanID });
							}
						}
						goto IL_0186;
					}
					catch (Exception arg)
					{
						Debug.LogError((object)$"Error in updatescanNodes A: {arg}");
						goto IL_0186;
					}
				}
				(Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).Remove(__instance.scanElements[i]);
				((Component)__instance.scanElements[i]).gameObject.SetActive(false);
				continue;
				IL_0186:
				try
				{
					Traverse.Create((object)__instance).Field("scanElementText").SetValue((object)((Component)__instance.scanElements[i]).gameObject.GetComponentsInChildren<TextMeshProUGUI>());
					if ((Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[]).Length > 1)
					{
						((TMP_Text)(Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[])[0]).text = value.headerText;
						((TMP_Text)(Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[])[1]).text = value.subText;
					}
					if (value.nodeType == 2)
					{
						flag = true;
					}
					zero = playerScript.gameplayCamera.WorldToScreenPoint(((Component)value).transform.position);
					((Transform)__instance.scanElements[i]).position = new Vector3(((Transform)__instance.scanElements[i]).position.x, ((Transform)__instance.scanElements[i]).position.y, 12.17f * anchorOffsetZ);
					__instance.scanElements[i].anchoredPosition = Vector2.op_Implicit(new Vector3(zero.x - anchorOffsetX * multiplier, zero.y - anchorOffsetY * multiplier));
					if (!(multiplier > 3f))
					{
						((Transform)__instance.scanElements[i]).localScale = new Vector3(multiplier, multiplier, multiplier);
					}
					else
					{
						((Transform)__instance.scanElements[i]).localScale = new Vector3(3f, 3f, 3f);
					}
				}
				catch (Exception arg2)
				{
					Debug.LogError((object)$"Error in updatescannodes B: {arg2}");
				}
			}
			try
			{
				if (!flag)
				{
					__instance.totalScrapScanned = 0;
					Traverse.Create((object)__instance).Field("totalScrapScannedDisplayNum").SetValue((object)0);
					Traverse.Create((object)__instance).Field("addToDisplayTotalInterval").SetValue((object)0.35f);
				}
				__instance.scanInfoAnimator.SetBool("display", (int)Reflection.GetInstanceField(typeof(HUDManager), __instance, "scannedScrapNum") >= 2 && flag);
			}
			catch (Exception arg3)
			{
				Debug.LogError((object)$"Error in updatescannodes C: {arg3}");
			}
		}

		public static void SetShadowQuality(AssetBundle assetBundle, HDAdditionalCameraData cameraData)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)assetBundle == (Object)null)
			{
				Debug.LogError((object)"HDLETHALCOMPANY: Something is wrong with the Asset Bundle - Null");
				return;
			}
			((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[20u] = true;
			((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)20, (m_setShadowQuality != 0) ? true : false);
			myAsset = (HDRenderPipelineAsset)((m_setShadowQuality != 1) ? ((m_setShadowQuality != 2) ? ((object)(HDRenderPipelineAsset)QualitySettings.renderPipeline) : ((object)(myAsset = assetBundle.LoadAsset<HDRenderPipelineAsset>("Assets/HDLethalCompany/MediumShadowsAsset.asset")))) : (myAsset = assetBundle.LoadAsset<HDRenderPipelineAsset>("Assets/HDLethalCompany/VeryLowShadowsAsset.asset")));
			QualitySettings.renderPipeline = (RenderPipelineAsset)(object)myAsset;
		}

		public static void SetLevelOfDetail(HDAdditionalCameraData cameraData)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (m_setLOD != 1)
			{
				((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[60u] = true;
				((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[61u] = true;
				((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)60, true);
				((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)61, true);
				cameraData.renderingPathCustomFrameSettings.lodBiasMode = (LODBiasMode)2;
				cameraData.renderingPathCustomFrameSettings.lodBias = ((m_setLOD == 0) ? 0.6f : 2.3f);
				if (m_setLOD == 0 && ((Component)cameraData).GetComponent<Camera>().farClipPlane > 180f)
				{
					((Component)cameraData).GetComponent<Camera>().farClipPlane = 170f;
				}
			}
		}

		public static void SetTextureQuality()
		{
			if (m_setTextureResolution < 3)
			{
				int globalTextureMipmapLimit = 3 - m_setTextureResolution;
				QualitySettings.globalTextureMipmapLimit = globalTextureMipmapLimit;
			}
		}

		public static void SetAntiAliasing(HDAdditionalCameraData cameraData)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (m_enableAntiAliasing)
			{
				cameraData.antialiasing = (AntialiasingMode)3;
			}
		}

		public static void ToggleCustomPass(HDAdditionalCameraData cameraData, bool enable)
		{
			((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[6u] = true;
			((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)6, enable);
		}

		public static void ToggleVolumetricFog(HDAdditionalCameraData cameraData, bool enable)
		{
			((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[28u] = true;
			((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)28, enable);
		}

		public static void SetFogQuality()
		{
			Object[] array = Resources.FindObjectsOfTypeAll(typeof(Volume));
			if (array.Length == 0)
			{
				Debug.LogError((object)"No volumes found");
				return;
			}
			Fog val2 = default(Fog);
			foreach (Object obj in array)
			{
				Volume val = (Volume)(object)((obj is Volume) ? obj : null);
				if (val.sharedProfile.TryGet<Fog>(ref val2))
				{
					((VolumeParameter<int>)(object)((VolumeComponentWithQuality)val2).quality).Override(3);
					switch (m_setFogQuality)
					{
					case -1:
						val2.volumetricFogBudget = 0.05f;
						val2.resolutionDepthRatio = 0.5f;
						break;
					case 0:
						val2.volumetricFogBudget = 0.05f;
						val2.resolutionDepthRatio = 0.5f;
						break;
					case 2:
						val2.volumetricFogBudget = 0.333f;
						val2.resolutionDepthRatio = 0.666f;
						break;
					case 3:
						val2.volumetricFogBudget = 0.666f;
						val2.resolutionDepthRatio = 0.5f;
						break;
					}
				}
			}
		}

		public static void RemoveLodFromGameObject(string name)
		{
			Object[] array = Resources.FindObjectsOfTypeAll(typeof(LODGroup));
			foreach (Object obj in array)
			{
				LODGroup val = (LODGroup)(object)((obj is LODGroup) ? obj : null);
				if (((Object)((Component)val).gameObject).name == name)
				{
					val.enabled = false;
				}
			}
		}
	}
}

plugins/Core/RugbugRedfern-Skinwalkers-2.0.6/SkinwalkerMod.dll

Decompiled 10 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[5]
		{
			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" }
			}
		};

		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.6")]
	internal class PluginLoader : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod");

		private const string modGUID = "RugbugRedfern.SkinwalkerMod";

		private const string modVersion = "2.0.6";

		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.6");
			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;
			DebugSettings.Instance.RecordMicrophoneRawAudio = 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)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).gameObject == (Object)null))
				{
					SkinwalkerLogger.Log("IsEnemyEnabled check: " + ((Object)val).name);
					SkinwalkerLogger.Log(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()
		{
		}
	}
}

plugins/Core/egeadam-MoreScreams-1.0.3/MoreScreams.dll

Decompiled 10 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance.Audio.Playback;
using GameNetcodeStuff;
using HarmonyLib;
using MoreScreams.Configuration;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MoreScreams")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreScreams")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("ba7e5619-9c03-4b8d-9888-381fda81ea0f")]
[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 MoreScreams
{
	[BepInPlugin("egeadam.MoreScreams", "MoreScreams", "1.0.3")]
	public class MoreScreams : BaseUnityPlugin
	{
		private const string modGUID = "egeadam.MoreScreams";

		private const string modName = "MoreScreams";

		private const string modVersion = "1.0.3";

		private readonly Harmony harmony = new Harmony("egeadam.MoreScreams");

		private static MoreScreams Instance;

		internal static ManualLogSource mls;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("egeadam.MoreScreams");
			Config.Init();
			harmony.PatchAll();
		}
	}
}
namespace MoreScreams.Patches
{
	public class AudioConfig
	{
		private PlayerControllerB playerControllerB;

		private float shutUpAt;

		private bool lowPassFilter;

		private bool highPassFilter;

		private float panStereo;

		private float playerVoicePitchTargets;

		private float playerPitch;

		private float spatialBlend;

		private bool set2D;

		private float volume;

		public bool IsAliveOrShuttedUp
		{
			get
			{
				if (!(shutUpAt < Time.time))
				{
					return !playerControllerB.isPlayerDead;
				}
				return true;
			}
		}

		public float ShutUpAt => shutUpAt;

		public bool LowPassFilter => lowPassFilter;

		public bool HighPassFilter => highPassFilter;

		public float PanStereo => panStereo;

		public float PlayerVoicePitchTargets => playerVoicePitchTargets;

		public float PlayerPitch => playerPitch;

		public float SpatialBlend => spatialBlend;

		public bool Set2D => set2D;

		public float Volume => volume;

		public Transform DeadBodyT => ((Component)playerControllerB.deadBody).transform;

		public Transform AudioSourceT => ((Component)playerControllerB.currentVoiceChatAudioSource).transform;

		public AudioConfig(PlayerControllerB playerControllerB, float shutUpAt, bool lowPassFilter, bool highPassFilter, float panStereo, float playerVoicePitchTargets, float playerPitch, float spatialBlend, bool set2D, float volume)
		{
			this.playerControllerB = playerControllerB;
			this.shutUpAt = shutUpAt;
			this.lowPassFilter = lowPassFilter;
			this.highPassFilter = highPassFilter;
			this.panStereo = panStereo;
			this.playerVoicePitchTargets = playerVoicePitchTargets;
			this.playerPitch = playerPitch;
			this.spatialBlend = spatialBlend;
			this.set2D = set2D;
			this.volume = volume;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "UpdatePlayerVoiceEffects")]
	internal class UpdatePlayerVoiceEffectsPatch
	{
		private static bool updateStarted = false;

		private static Dictionary<PlayerControllerB, AudioConfig> configs = new Dictionary<PlayerControllerB, AudioConfig>();

		public static Dictionary<PlayerControllerB, AudioConfig> Configs => configs;

		[HarmonyBefore(new string[] { "BiggerLobby" })]
		private static void Prefix()
		{
			if (configs == null)
			{
				configs = new Dictionary<PlayerControllerB, AudioConfig>();
			}
			if (!updateStarted)
			{
				((MonoBehaviour)HUDManager.Instance).StartCoroutine(UpdateNumerator());
				updateStarted = true;
			}
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null || StartOfRound.Instance.allPlayerScripts == null)
			{
				return;
			}
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i];
				if (!((Object)(object)val == (Object)null) && (val.isPlayerControlled || val.isPlayerDead) && (Object)(object)val != (Object)(object)GameNetworkManager.Instance.localPlayerController)
				{
					AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
					if (!((Object)(object)currentVoiceChatAudioSource == (Object)null) && val.isPlayerDead && !configs.ContainsKey(val))
					{
						Dictionary<PlayerControllerB, AudioConfig> dictionary = configs;
						float shutUpAt = Time.time + Config.ShutUpAfter;
						bool enabled = ((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>()).enabled;
						bool enabled2 = ((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>()).enabled;
						float panStereo = (currentVoiceChatAudioSource.panStereo = 0f);
						dictionary.Add(val, new AudioConfig(val, shutUpAt, enabled, enabled2, panStereo, SoundManager.Instance.playerVoicePitchTargets[(int)(IntPtr)(long)val.playerClientId], GetPitch(val), currentVoiceChatAudioSource.spatialBlend, val.currentVoiceChatIngameSettings.set2D, val.voicePlayerState.Volume));
					}
				}
			}
		}

		private static void Postfix()
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if (configs == null)
			{
				configs = new Dictionary<PlayerControllerB, AudioConfig>();
			}
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			PlayerControllerB[] array = configs.Keys.ToArray();
			foreach (PlayerControllerB val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				AudioConfig audioConfig = configs[val];
				if (audioConfig == null)
				{
					continue;
				}
				if ((val.isPlayerControlled || val.isPlayerDead) && !((Object)(object)val == (Object)(object)GameNetworkManager.Instance.localPlayerController))
				{
					if ((Object)(object)val.currentVoiceChatAudioSource == (Object)null)
					{
						continue;
					}
					AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
					if (!audioConfig.IsAliveOrShuttedUp)
					{
						if ((Object)(object)val.deadBody != (Object)null)
						{
							((Component)currentVoiceChatAudioSource).transform.position = ((Component)val.deadBody).transform.position;
						}
						currentVoiceChatAudioSource.panStereo = audioConfig.PanStereo;
						currentVoiceChatAudioSource.spatialBlend = audioConfig.SpatialBlend;
						AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
						AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
						if ((Object)(object)component != (Object)null)
						{
							((Behaviour)component).enabled = audioConfig.LowPassFilter;
						}
						if ((Object)(object)component2 != (Object)null)
						{
							((Behaviour)component2).enabled = audioConfig.HighPassFilter;
						}
						if ((Object)(object)SoundManager.Instance != (Object)null)
						{
							SoundManager.Instance.playerVoicePitchTargets[(int)(IntPtr)(long)val.playerClientId] = audioConfig.PlayerVoicePitchTargets;
							SoundManager.Instance.SetPlayerPitch(audioConfig.PlayerPitch, (int)val.playerClientId);
						}
						val.currentVoiceChatIngameSettings.set2D = audioConfig.Set2D;
						val.voicePlayerState.Volume = audioConfig.Volume;
						val.currentVoiceChatAudioSource.volume = audioConfig.Volume;
					}
				}
				else if (!val.isPlayerDead)
				{
					configs.Remove(val);
				}
			}
		}

		private static IEnumerator UpdateNumerator()
		{
			yield return 0;
			while (true)
			{
				UpdatePlayersStatus();
				yield return (object)new WaitForFixedUpdate();
			}
		}

		private static void UpdatePlayersStatus()
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if (configs == null)
			{
				return;
			}
			bool flag = false;
			KeyValuePair<PlayerControllerB, AudioConfig>[] array = configs.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<PlayerControllerB, AudioConfig> keyValuePair = array[i];
				if (!((Object)(object)keyValuePair.Key == (Object)null))
				{
					if (!keyValuePair.Key.isPlayerDead)
					{
						configs.Remove(keyValuePair.Key);
						flag = true;
					}
					else if ((Object)(object)keyValuePair.Value.DeadBodyT != (Object)null && (Object)(object)keyValuePair.Value.AudioSourceT != (Object)null)
					{
						keyValuePair.Value.AudioSourceT.position = keyValuePair.Value.DeadBodyT.position;
					}
				}
			}
			if (flag)
			{
				StartOfRound.Instance.UpdatePlayerVoiceEffects();
			}
		}

		private static float GetPitch(PlayerControllerB playerControllerB)
		{
			int num = (int)playerControllerB.playerClientId;
			float result = default(float);
			SoundManager.Instance.diageticMixer.GetFloat($"PlayerPitch{num}", ref result);
			return result;
		}
	}
	[HarmonyPatch]
	internal class DissonancePatch
	{
		public static MethodBase TargetMethod()
		{
			return AccessTools.FirstMethod(typeof(VoicePlayback), (Func<MethodInfo, bool>)((MethodInfo method) => method.Name.Contains("SetTransform")));
		}

		private static bool Prefix(object __instance)
		{
			foreach (AudioConfig value in UpdatePlayerVoiceEffectsPatch.Configs.Values)
			{
				if (!value.IsAliveOrShuttedUp && ((object)((Component)((__instance is VoicePlayback) ? __instance : null)).transform).Equals((object?)value.AudioSourceT))
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace MoreScreams.Configuration
{
	internal static class Config
	{
		private const string CONFIG_FILE_NAME = "MoreScreams.cfg";

		private static ConfigFile config;

		private static ConfigEntry<float> shutUpAfter;

		public static float ShutUpAfter => shutUpAfter.Value;

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			config = new ConfigFile(Path.Combine(Paths.ConfigPath, "MoreScreams.cfg"), true);
			shutUpAfter = config.Bind<float>("Config", "Shut up after", 2f, "Mutes death player after given seconds.");
		}
	}
}

plugins/Core/anormaltwig-LateCompany-1.0.10/LateCompanyV1.0.10.dll

Decompiled 10 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+d704803bb6f51635f2d01203f1e067e3078ab7f5")]
[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.10";
	}
	[BepInPlugin("twig.latecompany", "Late Company", "1.0.10")]
	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.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);
		}
	}
}

plugins/Core/AllToasters-SpectateEnemies-2.2.1/SpectateEnemy.dll

Decompiled 10 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.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using TMPro;
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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SpectateEnemy")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("2.2.1+4548998f5eaa9b81ec66b05ceab7191e8a0a77c9")]
[assembly: AssemblyProduct("SpectateEnemy")]
[assembly: AssemblyTitle("SpectateEnemy")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SpectateEnemy
{
	internal class Inputs : LcInputActions
	{
		[InputAction("<Keyboard>/e", Name = "Swap between Players/Enemies")]
		public InputAction SwapKey { get; set; }

		[InputAction("<Keyboard>/insert", Name = "Open Config Menu")]
		public InputAction MenuKey { get; set; }

		[InputAction("<Mouse>/rightButton", Name = "Toggle Flashlight")]
		public InputAction FlashlightKey { get; set; }

		[InputAction("<Mouse>/scroll/down", Name = "Zoom Out")]
		public InputAction ZoomOutKey { get; set; }

		[InputAction("<Mouse>/scroll/up", Name = "Zoom In")]
		public InputAction ZoomInKey { get; set; }
	}
	[BepInPlugin("SpectateEnemy", "SpectateEnemy", "2.2.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public static MethodInfo raycastSpectate = null;

		public static MethodInfo displaySpectatorTip = null;

		public static Inputs Inputs = new Inputs();

		private Harmony harmony;

		private void Awake()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmony = new Harmony("SpectateEnemy");
			harmony.PatchAll();
			raycastSpectate = AccessTools.Method(typeof(PlayerControllerB), "RaycastSpectateCameraAroundPivot", (Type[])null, (Type[])null);
			displaySpectatorTip = AccessTools.Method(typeof(HUDManager), "DisplaySpectatorTip", (Type[])null, (Type[])null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"SpectateEnemy loaded!");
		}
	}
	internal class Spectatable : MonoBehaviour
	{
		public SpectatableType type = SpectatableType.Enemy;

		public string enemyName = "Enemy";

		public string maskedName = string.Empty;

		public EnemyAI enemyInstance = null;
	}
	internal enum SpectatableType
	{
		Enemy,
		Turret,
		Landmine,
		Masked
	}
	internal class SpectateEnemies : MonoBehaviour
	{
		public static SpectateEnemies Instance;

		private static readonly Dictionary<string, bool> settings = new Dictionary<string, bool>();

		private bool WindowOpen = false;

		private Rect window = new Rect(10f, 10f, 500f, 400f);

		public int SpectatedEnemyIndex = -1;

		public bool SpectatingEnemies = false;

		public Spectatable[] SpectatorList;

		public float zoomLevel = 1f;

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			SetupKeybinds();
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		private void SetupKeybinds()
		{
			Plugin.Inputs.SwapKey.performed += OnSwapKeyPressed;
			Plugin.Inputs.MenuKey.performed += OnMenuKeyPressed;
			Plugin.Inputs.FlashlightKey.performed += OnFlashlightKeyPressed;
			Plugin.Inputs.ZoomOutKey.performed += OnZoomOutPressed;
			Plugin.Inputs.ZoomInKey.performed += OnZoomInPressed;
		}

		private void OnSwapKeyPressed(CallbackContext context)
		{
			if (((CallbackContext)(ref context)).performed && (Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
				{
					ToggleSpectatingMode(localPlayerController);
				}
			}
		}

		private void OnMenuKeyPressed(CallbackContext context)
		{
			if (((CallbackContext)(ref context)).performed && (Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
				{
					Toggle();
				}
			}
		}

		private void OnFlashlightKeyPressed(CallbackContext context)
		{
			if (!((CallbackContext)(ref context)).performed || !((Object)(object)GameNetworkManager.Instance != (Object)null) || !((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null))
			{
				return;
			}
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if ((Object)(object)HUDManager.Instance != (Object)null && ((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				Light component = ((Component)HUDManager.Instance.playersManager.spectateCamera).GetComponent<Light>();
				if ((Object)(object)component != (Object)null)
				{
					((Behaviour)component).enabled = !((Behaviour)component).enabled;
				}
			}
		}

		private void OnZoomOutPressed(CallbackContext context)
		{
			if (((CallbackContext)(ref context)).performed && SpectatingEnemies)
			{
				zoomLevel += 0.1f;
				if (zoomLevel > 10f)
				{
					zoomLevel = 10f;
				}
			}
		}

		private void OnZoomInPressed(CallbackContext context)
		{
			if (((CallbackContext)(ref context)).performed && SpectatingEnemies)
			{
				zoomLevel -= 0.1f;
				if (zoomLevel < 1f)
				{
					zoomLevel = 1f;
				}
			}
		}

		private void LateUpdate()
		{
			//IL_00f8: 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)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			if (!SpectatingEnemies)
			{
				return;
			}
			if (SpectatorList.Length == 0)
			{
				SpectatingEnemies = false;
				return;
			}
			Spectatable obj = SpectatorList.ElementAtOrDefault(SpectatedEnemyIndex);
			if ((Object)(object)obj == (Object)null)
			{
				GetNextValidSpectatable();
				return;
			}
			if ((obj.type == SpectatableType.Enemy || obj.type == SpectatableType.Masked) && (Object)(object)obj.enemyInstance != (Object)null && obj.enemyInstance.isEnemyDead)
			{
				GetNextValidSpectatable();
				return;
			}
			Vector3? spectatePosition = GetSpectatePosition(obj);
			if (!spectatePosition.HasValue)
			{
				GetNextValidSpectatable();
				return;
			}
			if (obj.enemyName == "Enemy")
			{
				TryFixName(ref obj);
			}
			GameNetworkManager.Instance.localPlayerController.spectateCameraPivot.position = spectatePosition.Value + Vector3.up * zoomLevel;
			if (obj.type == SpectatableType.Masked && obj.maskedName != string.Empty)
			{
				((TMP_Text)HUDManager.Instance.spectatingPlayerText).text = $"(Spectating: {obj.maskedName}) [{zoomLevel:F1}x]";
			}
			else
			{
				((TMP_Text)HUDManager.Instance.spectatingPlayerText).text = $"(Spectating: {obj.enemyName}) [{zoomLevel:F1}x]";
			}
			Plugin.raycastSpectate.Invoke(GameNetworkManager.Instance.localPlayerController, Array.Empty<object>());
		}

		private Vector3? GetSpectatePosition(Spectatable obj)
		{
			//IL_00bd: 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_004e: 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)
			if (obj.type == SpectatableType.Enemy || obj.type == SpectatableType.Masked)
			{
				EnemyAI enemyInstance = obj.enemyInstance;
				if ((Object)(object)enemyInstance != (Object)null)
				{
					return ((Object)(object)enemyInstance.eye == (Object)null) ? ((Component)enemyInstance).transform.position : enemyInstance.eye.position;
				}
			}
			else if (obj.type == SpectatableType.Turret)
			{
				Turret component = ((Component)obj).GetComponent<Turret>();
				if ((Object)(object)component != (Object)null)
				{
					return ((Component)component.centerPoint).transform.position;
				}
			}
			else
			{
				if (obj.type == SpectatableType.Landmine)
				{
					return ((Component)obj).transform.position;
				}
				Debug.LogError((object)("[SpectateEnemy]: Error when spectating: no handler for SpectatableType " + obj.type));
			}
			return null;
		}

		private void TryFixName(ref Spectatable obj)
		{
			MaskedPlayerEnemy val = default(MaskedPlayerEnemy);
			EnemyAI val2 = default(EnemyAI);
			Turret val3 = default(Turret);
			Landmine val4 = default(Landmine);
			if (((Component)obj).gameObject.TryGetComponent<MaskedPlayerEnemy>(ref val))
			{
				if ((Object)(object)val.mimickingPlayer != (Object)null)
				{
					obj.enemyName = val.mimickingPlayer.playerUsername;
				}
				else
				{
					obj.enemyName = ((EnemyAI)val).enemyType.enemyName;
				}
			}
			else if (((Component)obj).gameObject.TryGetComponent<EnemyAI>(ref val2))
			{
				obj.enemyName = val2.enemyType.enemyName;
			}
			else if (((Component)obj).gameObject.TryGetComponent<Turret>(ref val3))
			{
				obj.enemyName = "Turret";
			}
			else if (((Component)obj).gameObject.TryGetComponent<Landmine>(ref val4))
			{
				obj.enemyName = "Landmine";
			}
		}

		public void ToggleSpectatingMode(PlayerControllerB __instance)
		{
			//IL_00ed: 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)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			SpectatingEnemies = !SpectatingEnemies;
			if (SpectatingEnemies)
			{
				SpectatorList = (from x in Object.FindObjectsByType<Spectatable>((FindObjectsSortMode)0)
					where settings[x.enemyName]
					select x).ToArray();
				if (SpectatorList.Length == 0)
				{
					SpectatingEnemies = false;
					Plugin.displaySpectatorTip.Invoke(HUDManager.Instance, new object[1] { "No enemies to spectate" });
					return;
				}
				if (SpectatedEnemyIndex == -1 || SpectatedEnemyIndex >= SpectatorList.Length)
				{
					if ((Object)(object)__instance.spectatedPlayerScript == (Object)null)
					{
						GetNextValidSpectatable();
					}
					else
					{
						float num = 999999f;
						int spectatedEnemyIndex = 0;
						for (int i = 0; i < SpectatorList.Length; i++)
						{
							Vector3 val = ((Component)SpectatorList[i]).transform.position - ((Component)__instance.spectatedPlayerScript).transform.position;
							float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
							if (sqrMagnitude < num * num)
							{
								num = sqrMagnitude;
								spectatedEnemyIndex = i;
							}
						}
						SpectatedEnemyIndex = spectatedEnemyIndex;
					}
				}
				__instance.spectatedPlayerScript = null;
			}
			else
			{
				__instance.spectatedPlayerScript = ((IEnumerable<PlayerControllerB>)__instance.playersManager.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => !x.isPlayerDead && x.isPlayerControlled));
				((TMP_Text)HUDManager.Instance.spectatingPlayerText).text = "(Spectating: " + __instance.spectatedPlayerScript.playerUsername + ")";
			}
		}

		public void PopulateSettings()
		{
			EnemyType[] array = Resources.FindObjectsOfTypeAll<EnemyType>();
			EnemyType[] array2 = array;
			foreach (EnemyType val in array2)
			{
				if (!(val.enemyName == "Red pill") && !(val.enemyName == "Lasso"))
				{
					settings.TryAdd(val.enemyName, !val.isDaytimeEnemy);
				}
			}
			settings.TryAdd("Landmine", value: false);
			settings.TryAdd("Turret", value: false);
			try
			{
				if (File.Exists(Paths.ConfigPath + "/SpectateEnemy.cfg"))
				{
					string[] array3 = File.ReadAllLines(Paths.ConfigPath + "/SpectateEnemy.cfg");
					if (array3[3] == "[Config]")
					{
						Debug.LogWarning((object)"[SpectateEnemies]: Config not found, using default values!");
						return;
					}
					string[] array4 = array3;
					foreach (string text in array4)
					{
						string[] array5 = text.Split(':');
						if (array5.Length == 2 && settings.ContainsKey(array5[0]) && bool.TryParse(array5[1], out var result))
						{
							settings[array5[0]] = result;
						}
					}
					Debug.LogWarning((object)"[SpectateEnemies]: Config loaded");
				}
				else
				{
					Debug.LogWarning((object)"[SpectateEnemies]: Config not found, using default values!");
				}
			}
			catch (Exception)
			{
				Debug.LogWarning((object)"[SpectateEnemies]: Config failed to load, using default values!");
			}
			AssertSettings();
		}

		private void OnApplicationQuit()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<string, bool> setting in settings)
			{
				stringBuilder.Append(setting.Key);
				stringBuilder.Append(':');
				stringBuilder.Append(setting.Value);
				stringBuilder.AppendLine();
			}
			File.WriteAllText(Paths.ConfigPath + "/SpectateEnemy.cfg", stringBuilder.ToString());
			Debug.LogWarning((object)"[SpectateEnemies]: Config saved");
		}

		public bool SpectateNextEnemy()
		{
			if (SpectatorList.Length == 0)
			{
				SpectatingEnemies = false;
				return true;
			}
			GetNextValidSpectatable();
			return false;
		}

		private void GetNextValidSpectatable()
		{
			SpectatorList = (from x in Object.FindObjectsByType<Spectatable>((FindObjectsSortMode)0)
				where settings[x.enemyName]
				select x).ToArray();
			int num = 0;
			int num2 = SpectatedEnemyIndex;
			while (num < SpectatorList.Length)
			{
				num2++;
				if (num2 >= SpectatorList.Length)
				{
					num2 = 0;
				}
				Spectatable spectatable = SpectatorList.ElementAtOrDefault(num2);
				if ((Object)(object)spectatable != (Object)null)
				{
					if ((spectatable.type == SpectatableType.Enemy || spectatable.type == SpectatableType.Masked) && (Object)(object)spectatable.enemyInstance != (Object)null && spectatable.enemyInstance.isEnemyDead)
					{
						num++;
						continue;
					}
					if (settings.ContainsKey(spectatable.enemyName))
					{
						SpectatedEnemyIndex = num2;
						return;
					}
				}
				num++;
			}
			SpectatingEnemies = false;
			Plugin.displaySpectatorTip.Invoke(HUDManager.Instance, new object[1] { "No enemies to spectate" });
		}

		private void AssertSettings()
		{
			foreach (KeyValuePair<string, bool> setting in settings)
			{
				Debug.LogWarning((object)$"{setting.Key} : {setting.Value}");
			}
		}

		public bool GetSetting(string name)
		{
			if (settings.ContainsKey(name))
			{
				return settings[name];
			}
			return false;
		}

		public void Toggle()
		{
			WindowOpen = !WindowOpen;
		}

		public void Hide()
		{
			WindowOpen = false;
		}

		public bool IsMenuOpen()
		{
			return WindowOpen;
		}

		private void OnGUI()
		{
			//IL_000c: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//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)
			if (WindowOpen)
			{
				GUI.color = Color.gray;
				window = GUI.Window(0, window, new WindowFunction(DrawGUI), "Spectator Settings");
			}
		}

		private void DrawGUI(int windowID)
		{
			//IL_00df: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			if (windowID == 0)
			{
				GUI.Label(new Rect(10f, 30f, 500f, 100f), "Tip: Checking the box next to an enemy name will enable spectating it.");
				int num = 0;
				int num2 = 0;
				foreach (string item in settings.Keys.ToList())
				{
					settings[item] = GUI.Toggle(new Rect((float)(10 + 150 * num), (float)(60 + 30 * num2), 150f, 20f), settings[item], item);
					num++;
					if (num == 3)
					{
						num = 0;
						num2++;
					}
				}
			}
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 10000f));
		}
	}
	public class SpectateEnemiesAPI
	{
		public static bool IsLoaded => (Object)(object)SpectateEnemies.Instance != (Object)null;

		public static bool IsSpectatingEnemies => SpectateEnemies.Instance.SpectatingEnemies;

		public static GameObject CurrentEnemySpectating()
		{
			if (IsSpectatingEnemies && SpectateEnemies.Instance.SpectatedEnemyIndex > -1)
			{
				return ((Component)SpectateEnemies.Instance.SpectatorList[SpectateEnemies.Instance.SpectatedEnemyIndex]).gameObject;
			}
			return null;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "SpectateEnemy";

		public const string PLUGIN_NAME = "SpectateEnemy";

		public const string PLUGIN_VERSION = "2.2.1";
	}
}
namespace SpectateEnemy.Patches
{
	[HarmonyPatch(typeof(EnemyAI), "Start")]
	internal class EnemyAI_Patches
	{
		private static void Postfix(EnemyAI __instance)
		{
			Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
			spectatable.enemyName = __instance.enemyType.enemyName;
			spectatable.enemyInstance = __instance;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Disconnect")]
	internal class GameNetworkManager_Patches
	{
		private static void Postfix()
		{
			SpectateEnemies.Instance.SpectatedEnemyIndex = -1;
			SpectateEnemies.Instance.SpectatingEnemies = false;
			SpectateEnemies.Instance.Hide();
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Update")]
	internal class HUDManager_Patches
	{
		private static void Postfix(HUDManager __instance)
		{
			//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)
			//IL_00c7: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: 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_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) || !((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null))
			{
				return;
			}
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (!localPlayerController.isPlayerDead)
			{
				return;
			}
			if (StartOfRound.Instance.shipIsLeaving)
			{
				SpectateEnemies.Instance.Hide();
				Light component = ((Component)__instance.playersManager.spectateCamera).GetComponent<Light>();
				if ((Object)(object)component != (Object)null)
				{
					((Behaviour)component).enabled = false;
				}
				return;
			}
			InputBinding val = Plugin.Inputs.SwapKey.bindings[0];
			string text = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			val = Plugin.Inputs.MenuKey.bindings[0];
			string text2 = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			val = Plugin.Inputs.FlashlightKey.bindings[0];
			string text3 = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			val = Plugin.Inputs.ZoomOutKey.bindings[0];
			string text4 = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			val = Plugin.Inputs.ZoomInKey.bindings[0];
			string text5 = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			if (SpectateEnemies.Instance.SpectatingEnemies)
			{
				TextMeshProUGUI holdButtonToEndGameEarlyText = __instance.holdButtonToEndGameEarlyText;
				((TMP_Text)holdButtonToEndGameEarlyText).text = ((TMP_Text)holdButtonToEndGameEarlyText).text + "\n\n\n\n\nSpectate Players: [" + text + "]\nFlashlight : [" + text3 + "]\nZoom Out [" + text4 + "]\nZoom In [" + text5 + "]\nConfig Menu : [" + text2 + "]";
			}
			else
			{
				TextMeshProUGUI holdButtonToEndGameEarlyText = __instance.holdButtonToEndGameEarlyText;
				((TMP_Text)holdButtonToEndGameEarlyText).text = ((TMP_Text)holdButtonToEndGameEarlyText).text + "\n\n\n\n\nSpectate Enemies: [" + text + "]\nFlashlight : [" + text3 + "]\nConfig Menu : [" + text2 + "]";
			}
		}
	}
	[HarmonyPatch(typeof(Landmine), "Start")]
	internal class Landmine_Patches
	{
		private static void Postfix(Landmine __instance)
		{
			Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
			spectatable.type = SpectatableType.Landmine;
			spectatable.enemyName = "Landmine";
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy), "Start")]
	internal class MaskedPlayerEnemy_Patches
	{
		private static void Postfix(MaskedPlayerEnemy __instance)
		{
			Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
			spectatable.type = SpectatableType.Masked;
			spectatable.enemyName = ((EnemyAI)__instance).enemyType.enemyName;
			if ((Object)(object)__instance.mimickingPlayer != (Object)null)
			{
				spectatable.maskedName = __instance.mimickingPlayer.playerUsername;
			}
			spectatable.enemyInstance = (EnemyAI)(object)__instance;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
	internal class PlayerControllerB_Use
	{
		private static bool Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject))
			{
				if (SpectateEnemies.Instance.IsMenuOpen())
				{
					return false;
				}
				if (SpectateEnemies.Instance.SpectatingEnemies)
				{
					SpectateEnemies.Instance.SpectateNextEnemy();
				}
				return true;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
	internal class PlayerControllerB_SpectateNext
	{
		private static bool Prefix()
		{
			return !SpectateEnemies.Instance.SpectatingEnemies;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Start")]
	internal class QuickMenuManager_Patches
	{
		private static void Postfix(QuickMenuManager __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if ((Object)(object)SpectateEnemies.Instance == (Object)null)
			{
				GameObject val = new GameObject("SpectateEnemiesObject");
				SpectateEnemies spectateEnemies = val.AddComponent<SpectateEnemies>();
				spectateEnemies.PopulateSettings();
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
	internal class StartOfRound_Patches
	{
		private static void Postfix()
		{
			SpectateEnemies.Instance.SpectatedEnemyIndex = -1;
			SpectateEnemies.Instance.SpectatingEnemies = false;
			SpectateEnemies.Instance.Hide();
		}
	}
	[HarmonyPatch(typeof(Turret), "Start")]
	internal class Turret_Patches
	{
		private static void Postfix(Turret __instance)
		{
			Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
			spectatable.type = SpectatableType.Turret;
			spectatable.enemyName = "Turret";
		}
	}
}

plugins/Dependencies/Rune580-LethalCompany_InputUtils-0.4.4 (1)/LethalCompanyInputUtils.dll

Decompiled 10 months ago
using System;
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 BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using LethalCompanyInputUtils.Data;
using LethalCompanyInputUtils.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[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("LethalCompanyInputUtils")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9e95a88c49ab86635dbebf33cfb26802052a8769")]
[assembly: AssemblyProduct("LethalCompanyInputUtils")]
[assembly: AssemblyTitle("LethalCompanyInputUtils")]
[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.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;
		}
	}
}
namespace LethalCompanyInputUtils
{
	public static class LcInputActionApi
	{
		private static readonly Dictionary<string, LcInputActions> InputActionsMap = new Dictionary<string, LcInputActions>();

		private static IReadOnlyCollection<LcInputActions> InputActions => InputActionsMap.Values;

		internal static void LoadIntoUI(KepRemapPanel panel)
		{
			//IL_0159: 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_0094: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: 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_00cc: Expected O, but got Unknown
			//IL_00d9: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			UpdateFontScaling(panel);
			AdjustSizeAndPos(panel);
			LayoutElement val = EnsureLayoutElement(panel);
			val.minHeight = 0f;
			List<RemappableKey> remappableKeys = panel.remappableKeys;
			int num = remappableKeys.Count((RemappableKey key) => !key.gamepadOnly);
			foreach (LcInputActions inputAction in InputActions)
			{
				if (inputAction.Loaded)
				{
					continue;
				}
				foreach (InputActionReference actionRef in inputAction.ActionRefs)
				{
					InputBinding val2 = ((IEnumerable<InputBinding>)(object)actionRef.action.bindings).First();
					string name = ((InputBinding)(ref val2)).name;
					RemappableKey item = new RemappableKey
					{
						ControlName = name,
						currentInput = actionRef,
						gamepadOnly = false
					};
					remappableKeys.Insert(num++, item);
					RemappableKey item2 = new RemappableKey
					{
						ControlName = name,
						currentInput = actionRef,
						rebindingIndex = 1,
						gamepadOnly = true
					};
					remappableKeys.Add(item2);
				}
				inputAction.Loaded = true;
			}
			float horizontalOffset = panel.horizontalOffset;
			Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect;
			float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset);
			panel.maxVertical = (float)num / num2;
			val.minHeight += (panel.maxVertical + 1f) * panel.verticalOffset;
		}

		private static void UpdateFontScaling(KepRemapPanel panel)
		{
			TextMeshProUGUI component = ((Component)panel.keyRemapSlotPrefab.transform.Find("Text (1)")).GetComponent<TextMeshProUGUI>();
			if (!((TMP_Text)component).enableAutoSizing)
			{
				((TMP_Text)component).fontSizeMax = ((TMP_Text)component).fontSize;
				((TMP_Text)component).fontSizeMin = ((TMP_Text)component).fontSize - 4f;
				((TMP_Text)component).enableAutoSizing = true;
			}
		}

		private static void AdjustSizeAndPos(KepRemapPanel panel)
		{
			GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject;
			if (gameObject.GetComponent<ContentSizeFitter>() == null)
			{
				panel.keyRemapContainer.SetPivotY(1f);
				panel.keyRemapContainer.SetAnchorMinY(1f);
				panel.keyRemapContainer.SetAnchorMaxY(1f);
				panel.keyRemapContainer.SetAnchoredPosY(0f);
				panel.keyRemapContainer.SetLocalPosY(0f);
				ContentSizeFitter obj = gameObject.AddComponent<ContentSizeFitter>();
				obj.horizontalFit = (FitMode)0;
				obj.verticalFit = (FitMode)1;
			}
		}

		private static LayoutElement EnsureLayoutElement(KepRemapPanel panel)
		{
			GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject;
			LayoutElement component = gameObject.GetComponent<LayoutElement>();
			if (component != null)
			{
				return component;
			}
			return gameObject.AddComponent<LayoutElement>();
		}

		internal static void CalculateVerticalMaxForGamepad(KepRemapPanel panel)
		{
			//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)
			int num = panel.remappableKeys.Count((RemappableKey key) => key.gamepadOnly);
			float horizontalOffset = panel.horizontalOffset;
			Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect;
			float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset);
			panel.maxVertical = (float)num / num2;
			LayoutElement obj = EnsureLayoutElement(panel);
			obj.minHeight += (panel.maxVertical + 3f) * panel.verticalOffset;
		}

		internal static void ResetLoadedInputActions()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				inputAction.Loaded = false;
			}
		}

		internal static void RegisterInputActions(LcInputActions lcInputActions, InputActionMapBuilder builder)
		{
			if (!InputActionsMap.TryAdd(lcInputActions.Id, lcInputActions))
			{
				Logging.Logger.LogWarning((object)("The mod [" + lcInputActions.Plugin.GUID + "] instantiated an Actions class [" + lcInputActions.GetType().Name + "] more than once!\n\t These classes should be treated as singletons!, do not instantiate more than once!"));
			}
			else
			{
				lcInputActions.CreateInputActions(in builder);
				InputActionSetupExtensions.AddActionMap(lcInputActions.GetAsset(), builder.Build());
				lcInputActions.GetAsset().Enable();
				lcInputActions.OnAssetLoaded();
				lcInputActions.Load();
				lcInputActions.BuildActionRefs();
			}
		}

		internal static void DisableForRebind()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				if (inputAction.Enabled)
				{
					inputAction.Disable();
				}
			}
		}

		internal static void ReEnableFromRebind()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				if (inputAction.WasEnabled)
				{
					inputAction.Enable();
				}
			}
		}

		internal static void SaveOverrides()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				inputAction.Save();
			}
		}
	}
	[BepInPlugin("com.rune580.LethalCompanyInputUtils", "Lethal Company Input Utils", "0.4.4")]
	public class LethalCompanyInputUtilsPlugin : BaseUnityPlugin
	{
		public const string ModId = "com.rune580.LethalCompanyInputUtils";

		public const string ModName = "Lethal Company Input Utils";

		public const string ModVersion = "0.4.4";

		private Harmony? _harmony;

		private void Awake()
		{
			Logging.SetLogSource(((BaseUnityPlugin)this).Logger);
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.rune580.LethalCompanyInputUtils");
			SceneManager.activeSceneChanged += OnSceneChanged;
			FsUtils.EnsureControlsDir();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin com.rune580.LethalCompanyInputUtils is loaded!");
		}

		private static void OnSceneChanged(Scene current, Scene next)
		{
			LcInputActionApi.ResetLoadedInputActions();
		}
	}
}
namespace LethalCompanyInputUtils.Utils
{
	internal static class AssemblyUtils
	{
		public static BepInPlugin? GetBepInPlugin(this Assembly assembly)
		{
			foreach (Type validType in assembly.GetValidTypes())
			{
				BepInPlugin customAttribute = ((MemberInfo)validType).GetCustomAttribute<BepInPlugin>();
				if (customAttribute != null)
				{
					return customAttribute;
				}
			}
			return null;
		}

		public static IEnumerable<Type> GetValidTypes(this Assembly assembly)
		{
			try
			{
				return assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.Where((Type type) => (object)type != null);
			}
		}
	}
	internal static class FsUtils
	{
		public static string SaveDir { get; } = GetSaveDir();


		public static string Pre041ControlsDir { get; } = Path.Combine(Paths.BepInExRootPath, "controls");


		public static string ControlsDir { get; } = Path.Combine(Paths.ConfigPath, "controls");


		private static string GetSaveDir()
		{
			string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
			return Path.Combine(folderPath, "AppData", "LocalLow", "ZeekerssRBLX", "Lethal Company");
		}

		public static void EnsureControlsDir()
		{
			if (!Directory.Exists(ControlsDir))
			{
				Directory.CreateDirectory(ControlsDir);
			}
		}
	}
	internal static class Logging
	{
		private static ManualLogSource? _logSource;

		internal static ManualLogSource Logger { get; } = _logSource;


		internal static void SetLogSource(ManualLogSource logSource)
		{
			_logSource = logSource;
		}
	}
	internal static class RuntimeHelper
	{
		public static void SetLocalPosY(this RectTransform rectTransform, float y)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = ((Transform)rectTransform).localPosition;
			((Transform)rectTransform).localPosition = new Vector3(localPosition.x, y, localPosition.z);
		}

		public static void SetPivotY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.pivot = new Vector2(rectTransform.pivot.x, y);
		}

		public static void SetAnchorMinY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, y);
		}

		public static void SetAnchorMaxY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, y);
		}

		public static void SetAnchoredPosY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, y);
		}
	}
}
namespace LethalCompanyInputUtils.Patches
{
	public static class InputControlPathPatches
	{
		[HarmonyPatch]
		public static class ToHumanReadableStringPatch
		{
			public static IEnumerable<MethodBase> TargetMethods()
			{
				return from method in AccessTools.GetDeclaredMethods(typeof(InputControlPath))
					where method.Name == "ToHumanReadableString" && method.ReturnType == typeof(string)
					select method;
			}

			public static void Postfix(ref string __result)
			{
				string text = __result;
				if ((text == "<InputUtils-Gamepad-Not-Bound>" || text == "<InputUtils-Kbm-Not-Bound>") ? true : false)
				{
					__result = "";
				}
			}
		}
	}
	public static class KeyRemapPanelPatches
	{
		[HarmonyPatch(typeof(KepRemapPanel), "LoadKeybindsUI")]
		public static class LoadKeybindsUIPatch
		{
			public static void Prefix(KepRemapPanel __instance)
			{
				LcInputActionApi.DisableForRebind();
				LcInputActionApi.LoadIntoUI(__instance);
			}

			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Expected O, but got Unknown
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Expected O, but got Unknown
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Expected O, but got Unknown
				//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Expected O, but got Unknown
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e5: Expected O, but got Unknown
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				//IL_010d: Expected O, but got Unknown
				//IL_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Expected O, but got Unknown
				//IL_0162: Unknown result type (might be due to invalid IL or missing references)
				//IL_0168: Expected O, but got Unknown
				CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null);
				FieldInfo maxVerticalField = AccessTools.Field(typeof(KepRemapPanel), "maxVertical");
				val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[6]
				{
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsLdarg(code, (int?)0)), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, maxVerticalField, false)), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Ldc_R4 && (float)code.operand == 2f), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Add), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Conv_I4), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsStloc(code, (LocalBuilder)null)), (string)null)
				});
				val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				}).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(LcInputActionApi), "CalculateVerticalMaxForGamepad", new Type[1] { typeof(KepRemapPanel) }, (Type[])null))
				});
				return val.InstructionEnumeration();
			}
		}

		[HarmonyPatch(typeof(KepRemapPanel), "UnloadKeybindsUI")]
		public static class UnloadKeybindsUIPatch
		{
			public static void Prefix()
			{
				LcInputActionApi.SaveOverrides();
				LcInputActionApi.ReEnableFromRebind();
			}
		}
	}
}
namespace LethalCompanyInputUtils.Data
{
	[Serializable]
	public struct BindingOverride
	{
		public string? action;

		public string? origPath;

		public string? path;
	}
	[Serializable]
	public class BindingOverrides
	{
		public List<BindingOverride> overrides;

		private BindingOverrides()
		{
			overrides = new List<BindingOverride>();
		}

		public BindingOverrides(IEnumerable<InputBinding> bindings)
		{
			//IL_001b: 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)
			overrides = new List<BindingOverride>();
			foreach (InputBinding binding in bindings)
			{
				InputBinding current = binding;
				if (((InputBinding)(ref current)).hasOverrides)
				{
					BindingOverride item = new BindingOverride
					{
						action = ((InputBinding)(ref current)).action,
						origPath = ((InputBinding)(ref current)).path,
						path = ((InputBinding)(ref current)).overridePath
					};
					overrides.Add(item);
				}
			}
		}

		public void LoadInto(InputActionAsset asset)
		{
			foreach (BindingOverride @override in overrides)
			{
				InputAction obj = asset.FindAction(@override.action, false);
				if (obj != null)
				{
					InputActionRebindingExtensions.ApplyBindingOverride(obj, @override.path, (string)null, @override.origPath);
				}
			}
		}

		public static BindingOverrides FromJson(string json)
		{
			BindingOverrides bindingOverrides = new BindingOverrides();
			JToken value = JsonConvert.DeserializeObject<JObject>(json).GetValue("overrides");
			bindingOverrides.overrides = value.ToObject<List<BindingOverride>>();
			return bindingOverrides;
		}
	}
}
namespace LethalCompanyInputUtils.Api
{
	[AttributeUsage(AttributeTargets.Property)]
	public class InputActionAttribute : Attribute
	{
		public readonly string KbmPath;

		public string? ActionId { get; set; }

		public string? GamepadPath { get; set; }

		public InputActionType ActionType { get; set; } = (InputActionType)1;


		public string? KbmInteractions { get; set; }

		public string? GamepadInteractions { get; set; }

		public string? Name { get; set; }

		[Obsolete("Prefer using the named optional params instead.")]
		public InputActionAttribute(string action, string kbmPath, string gamepadPath)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			ActionId = action;
			KbmPath = kbmPath;
			GamepadPath = gamepadPath;
		}

		public InputActionAttribute(string kbmPath)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			KbmPath = kbmPath;
		}
	}
	public class InputActionBindingBuilder
	{
		private readonly InputActionMapBuilder _mapBuilder;

		private string? _actionId;

		private string? _kbmPath;

		private string? _gamepadPath;

		private string? _kbmInteractions;

		private string? _gamepadInteractions;

		private InputActionType _actionType;

		private string? _name;

		internal InputActionBindingBuilder(InputActionMapBuilder mapBuilder)
		{
			_mapBuilder = mapBuilder;
		}

		public InputActionBindingBuilder WithActionId(string actionId)
		{
			_actionId = actionId;
			return this;
		}

		public InputActionBindingBuilder WithKbmPath(string kbmPath)
		{
			_kbmPath = kbmPath;
			return this;
		}

		public InputActionBindingBuilder WithGamepadPath(string gamepadPath)
		{
			_gamepadPath = gamepadPath;
			return this;
		}

		public InputActionBindingBuilder WithKbmInteractions(string? kbmInteractions)
		{
			_kbmInteractions = kbmInteractions;
			return this;
		}

		public InputActionBindingBuilder WithGamepadInteractions(string? gamepadInteractions)
		{
			_gamepadInteractions = gamepadInteractions;
			return this;
		}

		public InputActionBindingBuilder WithActionType(InputActionType actionType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			_actionType = actionType;
			return this;
		}

		public InputActionBindingBuilder WithBindingName(string? name)
		{
			_name = name;
			return this;
		}

		public InputAction Finish()
		{
			//IL_001b: 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_002a: Expected O, but got Unknown
			//IL_005f: 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 (_name == null)
			{
				_name = _actionId;
			}
			InputAction val = new InputAction(_actionId, _actionType, (string)null, (string)null, (string)null, (string)null);
			_mapBuilder.WithAction(val);
			if (_kbmPath != null)
			{
				_mapBuilder.WithBinding(new InputBinding(_kbmPath, _actionId, (string)null, (string)null, _kbmInteractions, _name));
			}
			if (_gamepadPath != null)
			{
				_mapBuilder.WithBinding(new InputBinding(_gamepadPath, _actionId, (string)null, (string)null, _gamepadInteractions, _name));
			}
			return val;
		}
	}
	public class InputActionMapBuilder
	{
		private readonly InputActionMap _actionMap = new InputActionMap(mapName);

		public InputActionMapBuilder(string mapName)
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown


		public InputActionMapBuilder WithAction(InputAction action)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			InputActionSetupExtensions.AddAction(_actionMap, action.name, action.type, (string)null, (string)null, (string)null, (string)null, (string)null);
			return this;
		}

		public InputActionMapBuilder WithBinding(InputBinding binding)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			InputActionSetupExtensions.AddBinding(_actionMap, binding);
			return this;
		}

		public InputActionBindingBuilder NewActionBinding()
		{
			return new InputActionBindingBuilder(this);
		}

		internal InputActionMap Build()
		{
			return _actionMap;
		}
	}
	public abstract class LcInputActions
	{
		public const string UnboundKeyboardAndMouseIdentifier = "<InputUtils-Kbm-Not-Bound>";

		public const string UnboundGamepadIdentifier = "<InputUtils-Gamepad-Not-Bound>";

		private readonly string _jsonPath;

		private readonly List<InputActionReference> _actionRefs = new List<InputActionReference>();

		internal bool Loaded;

		private readonly Dictionary<PropertyInfo, InputActionAttribute> _inputProps;

		public InputActionAsset Asset { get; }

		internal bool WasEnabled { get; private set; }

		public bool Enabled => Asset.enabled;

		internal IReadOnlyCollection<InputActionReference> ActionRefs => _actionRefs;

		internal string Id => Plugin.GUID + "." + MapName;

		public BepInPlugin Plugin { get; }

		protected virtual string MapName => GetType().Name;

		internal InputActionAsset GetAsset()
		{
			return Asset;
		}

		protected LcInputActions()
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			Asset = ScriptableObject.CreateInstance<InputActionAsset>();
			Plugin = Assembly.GetCallingAssembly().GetBepInPlugin() ?? throw new InvalidOperationException();
			_jsonPath = Path.Combine(FsUtils.ControlsDir, Id + ".json");
			InputActionMapBuilder inputActionMapBuilder = new InputActionMapBuilder(Id);
			PropertyInfo[] properties = GetType().GetProperties();
			_inputProps = new Dictionary<PropertyInfo, InputActionAttribute>();
			PropertyInfo[] array = properties;
			foreach (PropertyInfo propertyInfo in array)
			{
				InputActionAttribute customAttribute = propertyInfo.GetCustomAttribute<InputActionAttribute>();
				if (customAttribute != null && !(propertyInfo.PropertyType != typeof(InputAction)))
				{
					InputActionAttribute inputActionAttribute = customAttribute;
					if (inputActionAttribute.ActionId == null)
					{
						string text = (inputActionAttribute.ActionId = propertyInfo.Name);
					}
					inputActionAttribute = customAttribute;
					if (inputActionAttribute.GamepadPath == null)
					{
						string text = (inputActionAttribute.GamepadPath = "<InputUtils-Gamepad-Not-Bound>");
					}
					string kbmPath = (string.IsNullOrEmpty(customAttribute.KbmPath) ? "<InputUtils-Kbm-Not-Bound>" : customAttribute.KbmPath);
					inputActionMapBuilder.NewActionBinding().WithActionId(customAttribute.ActionId).WithActionType(customAttribute.ActionType)
						.WithBindingName(customAttribute.Name)
						.WithKbmPath(kbmPath)
						.WithGamepadPath(customAttribute.GamepadPath)
						.WithKbmInteractions(customAttribute.KbmInteractions)
						.WithGamepadInteractions(customAttribute.GamepadInteractions)
						.Finish();
					_inputProps[propertyInfo] = customAttribute;
				}
			}
			LcInputActionApi.RegisterInputActions(this, inputActionMapBuilder);
		}

		public virtual void CreateInputActions(in InputActionMapBuilder builder)
		{
		}

		public virtual void OnAssetLoaded()
		{
		}

		internal void BuildActionRefs()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<PropertyInfo, InputActionAttribute> inputProp in _inputProps)
			{
				inputProp.Deconstruct(out var key, out var value);
				PropertyInfo propertyInfo = key;
				InputActionAttribute inputActionAttribute = value;
				InputAction value2 = Asset.FindAction(inputActionAttribute.ActionId, false);
				propertyInfo.SetValue(this, value2);
			}
			IEnumerable<InputActionReference> collection = ((IEnumerable<InputActionMap>)(object)Asset.actionMaps).SelectMany((InputActionMap map) => (IEnumerable<InputAction>)(object)map.actions).Select((Func<InputAction, InputActionReference>)InputActionReference.Create);
			_actionRefs.AddRange(collection);
		}

		public void Enable()
		{
			WasEnabled = Asset.enabled;
			Asset.Enable();
		}

		public void Disable()
		{
			WasEnabled = Asset.enabled;
			Asset.Disable();
		}

		internal void Save()
		{
			BindingOverrides bindingOverrides = new BindingOverrides(Asset.bindings);
			File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides));
		}

		internal void Load()
		{
			try
			{
				ApplyMigrations();
			}
			catch (Exception ex)
			{
				Logging.Logger.LogError((object)"Got error when applying migrations, skipping...");
				Logging.Logger.LogError((object)ex);
			}
			if (!File.Exists(_jsonPath))
			{
				return;
			}
			try
			{
				BindingOverrides.FromJson(File.ReadAllText(_jsonPath)).LoadInto(Asset);
			}
			catch (Exception ex2)
			{
				Logging.Logger.LogError((object)ex2);
			}
		}

		private void ApplyMigrations()
		{
			string text = Path.Combine(FsUtils.Pre041ControlsDir, Id + ".json");
			if (File.Exists(text) && !File.Exists(_jsonPath))
			{
				File.Move(text, _jsonPath);
			}
			if (!File.Exists(_jsonPath) || !File.ReadAllText(_jsonPath).Replace(" ", "").Contains("\"origPath\":\"\""))
			{
				return;
			}
			BindingOverrides bindingOverrides = BindingOverrides.FromJson(File.ReadAllText(_jsonPath));
			for (int i = 0; i < bindingOverrides.overrides.Count; i++)
			{
				BindingOverride value = bindingOverrides.overrides[i];
				if (string.IsNullOrEmpty(value.origPath) && value.path != null)
				{
					if (value.path.StartsWith("<Keyboard>") || value.path.StartsWith("<Mouse>"))
					{
						value.origPath = "<InputUtils-Kbm-Not-Bound>";
					}
					else
					{
						value.origPath = "<InputUtils-Gamepad-Not-Bound>";
					}
					bindingOverrides.overrides[i] = value;
				}
			}
			File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides));
		}
	}
}

plugins/Dependencies/Ozone-Runtime_Netcode_Patcher-0.2.5/NicholaScott.BepInEx.RuntimeNetcodeRPCValidator.dll

Decompiled 10 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.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[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("Unity.Netcode.Runtime")]
[assembly: AssemblyCompany("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.5.0")]
[assembly: AssemblyInformationalVersion("0.2.5+6e2f89b3631ae55d2f51a00ccfd3f20fec9d2372")]
[assembly: AssemblyProduct("RuntimeNetcodeRPCValidator")]
[assembly: AssemblyTitle("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace RuntimeNetcodeRPCValidator
{
	public class AlreadyRegisteredException : Exception
	{
		public AlreadyRegisteredException(string PluginGUID)
			: base("Can't register plugin " + PluginGUID + " until the other instance of NetcodeValidator is Disposed of!")
		{
		}
	}
	public class InvalidPluginGuidException : Exception
	{
		public InvalidPluginGuidException(string pluginGUID)
			: base("Can't patch plugin " + pluginGUID + " because it doesn't exist!")
		{
		}
	}
	public class NotNetworkBehaviourException : Exception
	{
		public NotNetworkBehaviourException(Type type)
			: base("Netcode Runtime RPC Validator tried to NetcodeValidator.Patch type " + type.Name + " that doesn't inherit from NetworkBehaviour!")
		{
		}
	}
	public class MustCallFromDeclaredTypeException : Exception
	{
		public MustCallFromDeclaredTypeException()
			: base("Netcode Runtime RPC Validator tried to run NetcodeValidator.PatchAll from a delegate! You must call PatchAll from a declared type.")
		{
		}
	}
	public static class FastBufferExtensions
	{
		private const BindingFlags BindingAll = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static void WriteSystemSerializable(this FastBufferWriter fastBufferWriter, object serializable)
		{
			//IL_0025: 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)
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			binaryFormatter.Serialize(memoryStream, serializable);
			byte[] array = memoryStream.ToArray();
			int num = array.Length;
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0);
		}

		private static void ReadSystemSerializable(this FastBufferReader fastBufferReader, out object serializable)
		{
			//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)
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			byte[] buffer = new byte[num];
			((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref buffer, num, 0);
			using MemoryStream memoryStream = new MemoryStream(buffer);
			memoryStream.Seek(0L, SeekOrigin.Begin);
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			serializable = binaryFormatter.Deserialize(memoryStream);
		}

		private static void WriteNetcodeSerializable(this FastBufferWriter fastBufferWriter, object networkSerializable)
		{
			//IL_0010: 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_0027: 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)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(1024, (Allocator)2, -1);
			try
			{
				BufferSerializer<BufferSerializerWriter> val2 = default(BufferSerializer<BufferSerializerWriter>);
				val2..ctor(new BufferSerializerWriter(val));
				object obj = ((networkSerializable is INetworkSerializable) ? networkSerializable : null);
				if (obj != null)
				{
					((INetworkSerializable)obj).NetworkSerialize<BufferSerializerWriter>(val2);
				}
				byte[] array = ((FastBufferWriter)(ref val)).ToArray();
				int num = array.Length;
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void ReadNetcodeSerializable(this FastBufferReader fastBufferReader, Type type, out object serializable)
		{
			//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_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_0051: Unknown result type (might be due to invalid IL or missing references)
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			byte[] array = new byte[num];
			((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref array, num, 0);
			FastBufferReader val = default(FastBufferReader);
			((FastBufferReader)(ref val))..ctor(array, (Allocator)2, -1, 0);
			try
			{
				BufferSerializer<BufferSerializerReader> val2 = default(BufferSerializer<BufferSerializerReader>);
				val2..ctor(new BufferSerializerReader(val));
				serializable = Activator.CreateInstance(type);
				object obj = serializable;
				object obj2 = ((obj is INetworkSerializable) ? obj : null);
				if (obj2 != null)
				{
					((INetworkSerializable)obj2).NetworkSerialize<BufferSerializerReader>(val2);
				}
			}
			finally
			{
				((IDisposable)(FastBufferReader)(ref val)).Dispose();
			}
		}

		public static void WriteMethodInfoAndParameters(this FastBufferWriter fastBufferWriter, MethodBase methodInfo, object[] args)
		{
			//IL_001f: 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_0079: 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_00a6: 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)
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(methodInfo.Name, false);
			ParameterInfo[] parameters = methodInfo.GetParameters();
			int num = parameters.Length;
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				object obj = args[i];
				bool flag = obj == null || parameterInfo.ParameterType == typeof(ServerRpcParams) || parameterInfo.ParameterType == typeof(ClientRpcParams);
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					continue;
				}
				if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable)))
				{
					fastBufferWriter.WriteNetcodeSerializable(obj);
					continue;
				}
				if (parameterInfo.ParameterType.IsSerializable)
				{
					fastBufferWriter.WriteSystemSerializable(obj);
					continue;
				}
				throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo));
			}
		}

		public static MethodInfo ReadMethodInfoAndParameters(this FastBufferReader fastBufferReader, Type methodDeclaringType, ref object[] args)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_00af: 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)
			string name = default(string);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref name, false);
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			MethodInfo method = methodDeclaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (num != method?.GetParameters().Length)
			{
				throw new Exception(TextHandler.InconsistentParameterCount(method, num));
			}
			bool flag = default(bool);
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					continue;
				}
				ParameterInfo parameterInfo = method.GetParameters()[i];
				object serializable;
				if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable)))
				{
					fastBufferReader.ReadNetcodeSerializable(parameterInfo.ParameterType, out serializable);
				}
				else
				{
					if (!parameterInfo.ParameterType.IsSerializable)
					{
						throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo));
					}
					fastBufferReader.ReadSystemSerializable(out serializable);
				}
				args[i] = serializable;
			}
			return method;
		}
	}
	public sealed class NetcodeValidator : IDisposable
	{
		private static readonly List<string> AlreadyRegistered = new List<string>();

		internal const string TypeCustomMessageHandlerPrefix = "Net";

		private static List<(NetcodeValidator validator, Type custom, Type native)> BoundNetworkObjects { get; } = new List<(NetcodeValidator, Type, Type)>();


		private List<string> CustomMessageHandlers { get; }

		private Harmony Patcher { get; }

		public string PluginGuid { get; }

		internal static event Action<NetcodeValidator, Type> AddedNewBoundBehaviour;

		private event Action<string> AddedNewCustomMessageHandler;

		public NetcodeValidator(string pluginGuid)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue(pluginGuid, out var _))
			{
				throw new InvalidPluginGuidException(pluginGuid);
			}
			if (AlreadyRegistered.Contains(pluginGuid))
			{
				throw new AlreadyRegisteredException(pluginGuid);
			}
			AlreadyRegistered.Add(pluginGuid);
			PluginGuid = pluginGuid;
			CustomMessageHandlers = new List<string>();
			Patcher = new Harmony(pluginGuid + "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator");
			Plugin.NetworkManagerInitialized += NetworkManagerInitialized;
			Plugin.NetworkManagerShutdown += NetworkManagerShutdown;
		}

		internal static void TryLoadRelatedComponentsInOrder(NetworkBehaviour __instance, MethodBase __originalMethod)
		{
			foreach (var item in from obj in BoundNetworkObjects
				where obj.native == __originalMethod.DeclaringType
				select obj into it
				orderby it.validator.PluginGuid
				select it)
			{
				Plugin.Logger.LogInfo((object)TextHandler.CustomComponentAddedToExistingObject(item, __originalMethod));
				Component obj2 = ((Component)__instance).gameObject.AddComponent(item.custom);
				((NetworkBehaviour)(object)((obj2 is NetworkBehaviour) ? obj2 : null)).SyncWithNetworkObject();
			}
		}

		private bool Patch(MethodInfo rpcMethod, out bool isServerRpc, out bool isClientRpc)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			isServerRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ServerRpcAttribute>().Any();
			isClientRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ClientRpcAttribute>().Any();
			bool flag = rpcMethod.Name.EndsWith("ServerRpc");
			bool flag2 = rpcMethod.Name.EndsWith("ClientRpc");
			if (!isClientRpc && !isServerRpc && !flag2 && !flag)
			{
				return false;
			}
			if ((!isServerRpc && flag) || (!isClientRpc && flag2))
			{
				Plugin.Logger.LogError((object)TextHandler.MethodLacksRpcAttribute(rpcMethod));
				return false;
			}
			if ((isServerRpc && !flag) || (isClientRpc && !flag2))
			{
				Plugin.Logger.LogError((object)TextHandler.MethodLacksSuffix(rpcMethod));
				return false;
			}
			Patcher.Patch((MethodBase)rpcMethod, new HarmonyMethod(typeof(NetworkBehaviourExtensions), "MethodPatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		public void BindToPreExistingObjectByBehaviour<TCustomBehaviour, TNativeBehaviour>() where TCustomBehaviour : NetworkBehaviour where TNativeBehaviour : NetworkBehaviour
		{
			if (Object.op_Implicit((Object)(object)NetworkManager.Singleton) && (NetworkManager.Singleton.IsListening || NetworkManager.Singleton.IsConnectedClient))
			{
				Plugin.Logger.LogError((object)TextHandler.PluginTriedToBindToPreExistingObjectTooLate(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour)));
			}
			else
			{
				OnAddedNewBoundBehaviour(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour));
			}
		}

		public void Patch(Type netBehaviourTyped)
		{
			if (netBehaviourTyped.BaseType != typeof(NetworkBehaviour))
			{
				throw new NotNetworkBehaviourException(netBehaviourTyped);
			}
			OnAddedNewCustomMessageHandler("Net." + netBehaviourTyped.Name);
			int num = 0;
			int num2 = 0;
			MethodInfo[] methods = netBehaviourTyped.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo rpcMethod in methods)
			{
				if (Patch(rpcMethod, out var isServerRpc, out var isClientRpc))
				{
					num += (isServerRpc ? 1 : 0);
					num2 += (isClientRpc ? 1 : 0);
				}
			}
			Plugin.Logger.LogInfo((object)TextHandler.SuccessfullyPatchedType(netBehaviourTyped, num, num2));
		}

		public void Patch(Assembly assembly)
		{
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.BaseType == typeof(NetworkBehaviour))
				{
					Patch(type);
				}
			}
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType?.Assembly;
			if (assembly == null)
			{
				throw new MustCallFromDeclaredTypeException();
			}
			Patch(assembly);
		}

		public void UnpatchSelf()
		{
			Plugin.Logger.LogInfo((object)TextHandler.PluginUnpatchedAllRPCs(this));
			Patcher.UnpatchSelf();
		}

		private static void RegisterMessageHandlerWithNetworkManager(string handler)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(handler, new HandleNamedMessageDelegate(NetworkBehaviourExtensions.ReceiveNetworkMessage));
		}

		private void NetworkManagerInitialized()
		{
			AddedNewCustomMessageHandler += RegisterMessageHandlerWithNetworkManager;
			foreach (string customMessageHandler in CustomMessageHandlers)
			{
				RegisterMessageHandlerWithNetworkManager(customMessageHandler);
			}
		}

		private void NetworkManagerShutdown()
		{
			AddedNewCustomMessageHandler -= RegisterMessageHandlerWithNetworkManager;
			foreach (string customMessageHandler in CustomMessageHandlers)
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(customMessageHandler);
			}
		}

		public void Dispose()
		{
			Plugin.NetworkManagerInitialized -= NetworkManagerInitialized;
			Plugin.NetworkManagerShutdown -= NetworkManagerShutdown;
			AlreadyRegistered.Remove(PluginGuid);
			if (Object.op_Implicit((Object)(object)NetworkManager.Singleton))
			{
				NetworkManagerShutdown();
			}
			if (Patcher.GetPatchedMethods().Any())
			{
				UnpatchSelf();
			}
		}

		private void OnAddedNewCustomMessageHandler(string obj)
		{
			CustomMessageHandlers.Add(obj);
			this.AddedNewCustomMessageHandler?.Invoke(obj);
		}

		private static void OnAddedNewBoundBehaviour(NetcodeValidator validator, Type custom, Type native)
		{
			BoundNetworkObjects.Add((validator, custom, native));
			NetcodeValidator.AddedNewBoundBehaviour?.Invoke(validator, native);
		}
	}
	public static class NetworkBehaviourExtensions
	{
		public enum RpcState
		{
			FromUser,
			FromNetworking
		}

		private static RpcState RpcSource;

		public static ClientRpcParams CreateSendToFromReceived(this ServerRpcParams senderId)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			ClientRpcParams result = default(ClientRpcParams);
			result.Send = new ClientRpcSendParams
			{
				TargetClientIds = new ulong[1] { senderId.Receive.SenderClientId }
			};
			return result;
		}

		public static void SyncWithNetworkObject(this NetworkBehaviour networkBehaviour)
		{
			if (!networkBehaviour.NetworkObject.ChildNetworkBehaviours.Contains(networkBehaviour))
			{
				networkBehaviour.NetworkObject.ChildNetworkBehaviours.Add(networkBehaviour);
			}
			networkBehaviour.UpdateNetworkProperties();
		}

		private static bool ValidateRPCMethod(NetworkBehaviour networkBehaviour, MethodBase method, RpcState state, out RpcAttribute rpcAttribute)
		{
			bool flag = ((MemberInfo)method).GetCustomAttributes<ServerRpcAttribute>().Any();
			bool flag2 = ((MemberInfo)method).GetCustomAttributes<ClientRpcAttribute>().Any();
			bool num = flag && ((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>().RequireOwnership;
			rpcAttribute = (RpcAttribute)(flag ? ((object)((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>()) : ((object)((MemberInfo)method).GetCustomAttribute<ClientRpcAttribute>()));
			if (num && networkBehaviour.OwnerClientId != NetworkManager.Singleton.LocalClientId)
			{
				Plugin.Logger.LogError((object)TextHandler.NotOwnerOfNetworkObject((state == RpcState.FromUser) ? "We" : "Client", method, networkBehaviour.NetworkObject));
				return false;
			}
			if (state == RpcState.FromUser && flag2 && !NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				Plugin.Logger.LogError((object)TextHandler.CantRunClientRpcFromClient(method));
				return false;
			}
			if (state == RpcState.FromUser && !flag && !flag2)
			{
				Plugin.Logger.LogError((object)TextHandler.MethodPatchedButLacksAttributes(method));
				return false;
			}
			if (state == RpcState.FromNetworking && !flag && !flag2)
			{
				Plugin.Logger.LogError((object)TextHandler.MethodPatchedAndNetworkCalledButLacksAttributes(method));
				return false;
			}
			if (state == RpcState.FromNetworking && flag && !networkBehaviour.IsServer && !networkBehaviour.IsHost)
			{
				Plugin.Logger.LogError((object)TextHandler.CantRunServerRpcAsClient(method));
				return false;
			}
			return true;
		}

		private static bool MethodPatchInternal(NetworkBehaviour networkBehaviour, MethodBase method, object[] args)
		{
			//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_00a5: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)NetworkManager.Singleton) || (!NetworkManager.Singleton.IsListening && !NetworkManager.Singleton.IsConnectedClient))
			{
				Plugin.Logger.LogError((object)TextHandler.NoNetworkManagerPresentToSendRpc(networkBehaviour));
				return false;
			}
			RpcState rpcSource = RpcSource;
			RpcSource = RpcState.FromUser;
			if (rpcSource == RpcState.FromNetworking)
			{
				return true;
			}
			if (!ValidateRPCMethod(networkBehaviour, method, rpcSource, out var rpcAttribute))
			{
				return false;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor((method.GetParameters().Length + 1) * 128, (Allocator)2, -1);
			ulong networkObjectId = networkBehaviour.NetworkObjectId;
			((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref networkObjectId, default(ForPrimitives));
			ushort networkBehaviourId = networkBehaviour.NetworkBehaviourId;
			((FastBufferWriter)(ref val)).WriteValueSafe<ushort>(ref networkBehaviourId, default(ForPrimitives));
			val.WriteMethodInfoAndParameters(method, args);
			string text = new StringBuilder("Net").Append(".").Append(method.DeclaringType.Name).ToString();
			NetworkDelivery val2 = (NetworkDelivery)(((int)rpcAttribute.Delivery == 0) ? 2 : 0);
			if (rpcAttribute is ServerRpcAttribute)
			{
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, 0uL, val, val2);
			}
			else
			{
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length != 0 && parameters[^1].ParameterType == typeof(ClientRpcParams))
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, ((ClientRpcParams)args[^1]).Send.TargetClientIds, val, val2);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(text, val, val2);
				}
			}
			return false;
		}

		internal static void ReceiveNetworkMessage(ulong sender, 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_0019: 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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: 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_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: 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)
			ulong key = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref key, default(ForPrimitives));
			ushort num = default(ushort);
			((FastBufferReader)(ref reader)).ReadValueSafe<ushort>(ref num, default(ForPrimitives));
			int position = ((FastBufferReader)(ref reader)).Position;
			string text = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
			((FastBufferReader)(ref reader)).Seek(position);
			if (!NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(key, out var value))
			{
				Plugin.Logger.LogError((object)TextHandler.RpcCalledBeforeObjectSpawned());
				return;
			}
			NetworkBehaviour networkBehaviourAtOrderIndex = value.GetNetworkBehaviourAtOrderIndex(num);
			MethodInfo method = ((object)networkBehaviourAtOrderIndex).GetType().GetMethod(text, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			RpcAttribute rpcAttribute;
			if (method == null)
			{
				Plugin.Logger.LogError((object)TextHandler.NetworkCalledNonExistentMethod(networkBehaviourAtOrderIndex, text));
			}
			else if (ValidateRPCMethod(networkBehaviourAtOrderIndex, method, RpcState.FromNetworking, out rpcAttribute))
			{
				RpcSource = RpcState.FromNetworking;
				ParameterInfo[] parameters = method.GetParameters();
				bool num2 = rpcAttribute is ServerRpcAttribute && parameters.Length != 0 && parameters[^1].ParameterType == typeof(ServerRpcParams);
				object[] args = null;
				if (parameters.Length != 0)
				{
					args = new object[parameters.Length];
				}
				reader.ReadMethodInfoAndParameters(method.DeclaringType, ref args);
				if (num2)
				{
					args[^1] = (object)new ServerRpcParams
					{
						Receive = new ServerRpcReceiveParams
						{
							SenderClientId = sender
						}
					};
				}
				method.Invoke(networkBehaviourAtOrderIndex, args);
			}
		}

		internal static bool MethodPatch(NetworkBehaviour __instance, MethodBase __originalMethod, object[] __args)
		{
			return MethodPatchInternal(__instance, __originalMethod, __args);
		}
	}
	[BepInPlugin("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator", "RuntimeNetcodeRPCValidator", "0.2.5")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator");

		private List<Type> AlreadyPatchedNativeBehaviours { get; } = new List<Type>();


		internal static ManualLogSource Logger { get; private set; }

		public static event Action NetworkManagerInitialized;

		public static event Action NetworkManagerShutdown;

		private void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			NetcodeValidator.AddedNewBoundBehaviour += NetcodeValidatorOnAddedNewBoundBehaviour;
			_harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Initialize", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerInitialized", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerShutdown", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void NetcodeValidatorOnAddedNewBoundBehaviour(NetcodeValidator validator, Type netBehaviour)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (!AlreadyPatchedNativeBehaviours.Contains(netBehaviour))
			{
				AlreadyPatchedNativeBehaviours.Add(netBehaviour);
				MethodBase methodBase = AccessTools.Method(netBehaviour, "Awake", (Type[])null, (Type[])null);
				if (methodBase == null)
				{
					methodBase = AccessTools.Method(netBehaviour, "Start", (Type[])null, (Type[])null);
				}
				if (methodBase == null)
				{
					methodBase = AccessTools.Constructor(netBehaviour, (Type[])null, false);
				}
				Logger.LogInfo((object)TextHandler.RegisteredPatchForType(validator, netBehaviour, methodBase));
				HarmonyMethod val = new HarmonyMethod(typeof(NetcodeValidator), "TryLoadRelatedComponentsInOrder", (Type[])null);
				_harmony.Patch(methodBase, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		protected static void OnNetworkManagerInitialized()
		{
			Plugin.NetworkManagerInitialized?.Invoke();
		}

		protected static void OnNetworkManagerShutdown()
		{
			Plugin.NetworkManagerShutdown?.Invoke();
		}
	}
	internal static class TextHandler
	{
		private const string NoNetworkManagerPresentToSendRpcConst = "NetworkBehaviour {0} tried to send a RPC but the NetworkManager is non-existant!";

		private const string MethodLacksAttributeConst = "Can't patch method {0}.{1} because it lacks a [{2}] attribute.";

		private const string MethodLacksSuffixConst = "Can't patch method {0}.{1} because it's name doesn't end with '{2}'!";

		private const string SuccessfullyPatchedTypeConst = "Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}.";

		private const string NotOwnerOfNetworkObjectConst = "{0} tried to run ServerRPC {1} but not the owner of NetworkObject {2}";

		private const string CantRunClientRpcFromClientConst = "Tried to run ClientRpc {0} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!";

		private const string CantRunServerRpcAsClientConst = "Received message to run ServerRPC {0}.{1} but we're a client!";

		private const string MethodPatchedButLacksAttributesConst = "Rpc Method {0} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!";

		private const string MethodPatchedAndNetworkCalledButLacksAttributesConst = "Rpc Method {0} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!";

		private const string RpcCalledBeforeObjectSpawnedConst = "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs.";

		private const string NetworkCalledNonExistentMethodConst = "NetworkBehaviour {0} received RPC {1} but that method doesn't exist on {2}!";

		private const string ObjectNotSerializableConst = "[Network] Parameter ({0} {1}) is not marked [Serializable] nor does it implement INetworkSerializable!";

		private const string InconsistentParameterCountConst = "[Network] NetworkBehaviour received a RPC {0} but the number of parameters sent {1} != MethodInfo param count {2}";

		private const string PluginTriedToBindToPreExistingObjectTooLateConst = "Plugin '{0}' tried to bind {1} to {2} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient.";

		private const string RegisteredPatchForTypeConst = "Successfully registered first patch for type {0}.{1} | Triggered by {2}";

		private const string CustomComponentAddedToExistingObjectConst = "Successfully added {0} to {1} via {2}. Triggered by plugin {3}";

		private const string PluginUnpatchedAllRPCsConst = "Plugin {0} has unpatched all RPCs!";

		internal static string NoNetworkManagerPresentToSendRpc(NetworkBehaviour networkBehaviour)
		{
			return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} tried to send a RPC but the NetworkManager is non-existant!";
		}

		internal static string MethodLacksRpcAttribute(MethodInfo method)
		{
			return string.Format("Can't patch method {0}.{1} because it lacks a [{2}] attribute.", method.DeclaringType?.Name, method.Name, method.Name.EndsWith("ServerRpc") ? "ServerRpc" : "ClientRpc");
		}

		internal static string MethodLacksSuffix(MethodBase method)
		{
			return string.Format("Can't patch method {0}.{1} because it's name doesn't end with '{2}'!", method.DeclaringType?.Name, method.Name, (((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>() != null) ? "ServerRpc" : "ClientRpc");
		}

		internal static string SuccessfullyPatchedType(Type networkType, int serverRpcCount, int clientRpcCount)
		{
			return string.Format("Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}.", serverRpcCount, (serverRpcCount == 1) ? "" : "s", clientRpcCount, (clientRpcCount == 1) ? "" : "s", networkType.Name);
		}

		internal static string NotOwnerOfNetworkObject(string whoIsNotOwner, MethodBase method, NetworkObject networkObject)
		{
			return $"{whoIsNotOwner} tried to run ServerRPC {method.Name} but not the owner of NetworkObject {networkObject.NetworkObjectId}";
		}

		internal static string CantRunClientRpcFromClient(MethodBase method)
		{
			return $"Tried to run ClientRpc {method.Name} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!";
		}

		internal static string CantRunServerRpcAsClient(MethodBase method)
		{
			return $"Received message to run ServerRPC {method.DeclaringType?.Name}.{method.Name} but we're a client!";
		}

		internal static string MethodPatchedButLacksAttributes(MethodBase method)
		{
			return $"Rpc Method {method.Name} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!";
		}

		internal static string MethodPatchedAndNetworkCalledButLacksAttributes(MethodBase method)
		{
			return $"Rpc Method {method.Name} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!";
		}

		internal static string RpcCalledBeforeObjectSpawned()
		{
			return "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs.";
		}

		internal static string NetworkCalledNonExistentMethod(NetworkBehaviour networkBehaviour, string rpcName)
		{
			return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} received RPC {rpcName} but that method doesn't exist on {((object)networkBehaviour).GetType().Name}!";
		}

		internal static string ObjectNotSerializable(ParameterInfo paramInfo)
		{
			return $"[Network] Parameter ({paramInfo.ParameterType.Name} {paramInfo.Name}) is not marked [Serializable] nor does it implement INetworkSerializable!";
		}

		internal static string InconsistentParameterCount(MethodBase method, int paramsSent)
		{
			return $"[Network] NetworkBehaviour received a RPC {method.Name} but the number of parameters sent {paramsSent} != MethodInfo param count {method.GetParameters().Length}";
		}

		internal static string PluginTriedToBindToPreExistingObjectTooLate(NetcodeValidator netcodeValidator, Type from, Type to)
		{
			return $"Plugin '{netcodeValidator.PluginGuid}' tried to bind {from.Name} to {to.Name} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient.";
		}

		internal static string RegisteredPatchForType(NetcodeValidator validator, Type netBehaviour, MethodBase method)
		{
			return $"Successfully registered first patch for type {netBehaviour.Name}.{method.Name} | Triggered by {validator.PluginGuid}";
		}

		internal static string CustomComponentAddedToExistingObject((NetcodeValidator validator, Type custom, Type native) it, MethodBase methodBase)
		{
			return $"Successfully added {it.custom.Name} to {it.native.Name} via {methodBase.Name}. Triggered by plugin {it.validator.PluginGuid}";
		}

		internal static string PluginUnpatchedAllRPCs(NetcodeValidator netcodeValidator)
		{
			return $"Plugin {netcodeValidator.PluginGuid} has unpatched all RPCs!";
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator";

		public const string PLUGIN_NAME = "RuntimeNetcodeRPCValidator";

		public const string PLUGIN_VERSION = "0.2.5";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/Dependencies/NotAtomicBomb-TerminalApi-1.5.0/TerminalApi.dll

Decompiled 10 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 Microsoft.CodeAnalysis;
using TMPro;
using TerminalApi.Classes;
using TerminalApi.Interfaces;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("NotAtomicBomb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Terminal Api for the terminal in Lethal Company")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1+9b12d17b39fe1f9518b55effc9f9d6af53ea5e0d")]
[assembly: AssemblyProduct("TerminalApi")]
[assembly: AssemblyTitle("TerminalApi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NotAtomicBomb/TerminalApi")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TerminalApi
{
	internal class DelayedAddTerminalKeyword : IDelayedAction
	{
		internal Action<TerminalKeyword, CommandInfo> Action { get; set; }

		internal CommandInfo CommandInfo { get; set; }

		internal TerminalKeyword Keyword { get; set; }

		public void Run()
		{
			Action(Keyword, CommandInfo);
		}
	}
	[BepInPlugin("atomic.terminalapi", "Terminal Api", "1.5.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ConfigEntry<bool> configEnableLogs;

		public ManualLogSource Log;

		internal void SetupConfig()
		{
			configEnableLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "enableLogs", true, "Whether or not to display logs pertaining to TerminalAPI. Will still log that the mod has loaded.");
		}

		private void Awake()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			SetupConfig();
			object obj = this;
			obj = (object)((!configEnableLogs.Value) ? ((ManualLogSource)null) : new ManualLogSource("Terminal Api"));
			((Plugin)obj).Log = (ManualLogSource)obj;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin TerminalApi is loaded!");
			if (Log != null)
			{
				Logger.Sources.Add((ILogSource)(object)Log);
			}
			TerminalApi.plugin = this;
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
	public static class TerminalApi
	{
		public static Plugin plugin;

		internal static List<IDelayedAction> QueuedDelayedActions = new List<IDelayedAction>();

		internal static List<CommandInfo> CommandInfos = new List<CommandInfo>();

		public static Terminal Terminal { get; internal set; }

		public static List<TerminalNode> SpecialNodes => Terminal.terminalNodes.specialNodes;

		public static string CurrentText => Terminal.currentText;

		public static TMP_InputField ScreenText => Terminal.screenText;

		public static bool IsInGame()
		{
			try
			{
				return Terminal != null;
			}
			catch (NullReferenceException)
			{
				return false;
			}
		}

		public static void AddCommand(string commandWord, string displayText, string verbWord = null, bool clearPreviousText = true)
		{
			commandWord = commandWord.ToLower();
			TerminalKeyword val = CreateTerminalKeyword(commandWord);
			TerminalNode val2 = CreateTerminalNode(displayText, clearPreviousText);
			if (verbWord != null)
			{
				verbWord = verbWord.ToLower();
				TerminalKeyword terminalKeyword = CreateTerminalKeyword(verbWord, isVerb: true);
				AddTerminalKeyword(val.defaultVerb = terminalKeyword.AddCompatibleNoun(val, val2));
				AddTerminalKeyword(val);
			}
			else
			{
				val.specialKeywordResult = val2;
				AddTerminalKeyword(val);
			}
		}

		public static void AddCommand(string commandWord, CommandInfo commandInfo, string verbWord = null, bool clearPreviousText = true)
		{
			commandWord = commandWord.ToLower();
			TerminalKeyword val = CreateTerminalKeyword(commandWord);
			TerminalNode val3 = (commandInfo.TriggerNode = CreateTerminalNode("", clearPreviousText));
			if (verbWord != null)
			{
				verbWord = verbWord.ToLower();
				TerminalKeyword terminalKeyword = CreateTerminalKeyword(verbWord, isVerb: true);
				AddTerminalKeyword(val.defaultVerb = terminalKeyword.AddCompatibleNoun(val, val3));
				AddTerminalKeyword(val, commandInfo);
			}
			else
			{
				val.specialKeywordResult = val3;
				AddTerminalKeyword(val, commandInfo);
			}
		}

		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, TerminalNode triggeringNode = null)
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			obj.word = word.ToLower();
			obj.isVerb = isVerb;
			obj.specialKeywordResult = triggeringNode;
			return obj;
		}

		public static TerminalKeyword CreateTerminalKeyword(string word, string displayText, bool clearPreviousText = false, string terminalEvent = "")
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			obj.word = word.ToLower();
			obj.isVerb = false;
			obj.specialKeywordResult = CreateTerminalNode(displayText, clearPreviousText, terminalEvent);
			return obj;
		}

		public static TerminalNode CreateTerminalNode(string displayText, bool clearPreviousText = false, string terminalEvent = "")
		{
			TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>();
			obj.displayText = displayText;
			obj.clearPreviousText = clearPreviousText;
			obj.terminalEvent = terminalEvent;
			return obj;
		}

		public static void AddTerminalKeyword(TerminalKeyword terminalKeyword)
		{
			if (IsInGame())
			{
				if (GetKeyword(terminalKeyword.word) == null)
				{
					Terminal.terminalNodes.allKeywords = Terminal.terminalNodes.allKeywords.Add(terminalKeyword);
					ManualLogSource log = plugin.Log;
					if (log != null)
					{
						log.LogMessage((object)("Added " + terminalKeyword.word + " keyword to terminal keywords."));
					}
				}
				else
				{
					ManualLogSource log2 = plugin.Log;
					if (log2 != null)
					{
						log2.LogWarning((object)("Failed to add " + terminalKeyword.word + " keyword. Already exists."));
					}
				}
			}
			else
			{
				ManualLogSource log3 = plugin.Log;
				if (log3 != null)
				{
					log3.LogMessage((object)("Not in game, waiting to be in game to add " + terminalKeyword.word + " keyword."));
				}
				Action<TerminalKeyword, CommandInfo> action = AddTerminalKeyword;
				DelayedAddTerminalKeyword item = new DelayedAddTerminalKeyword
				{
					Action = action,
					Keyword = terminalKeyword
				};
				QueuedDelayedActions.Add(item);
			}
		}

		public static void AddTerminalKeyword(TerminalKeyword terminalKeyword, CommandInfo commandInfo = null)
		{
			if (IsInGame())
			{
				if (GetKeyword(terminalKeyword.word) == null)
				{
					if (commandInfo?.DisplayTextSupplier != null)
					{
						if (commandInfo?.TriggerNode == null)
						{
							commandInfo.TriggerNode = terminalKeyword.specialKeywordResult;
						}
						CommandInfos.Add(commandInfo);
					}
					if (commandInfo != null)
					{
						((Object)terminalKeyword).name = commandInfo.Title ?? (terminalKeyword.word.Substring(0, 1).ToUpper() + terminalKeyword.word.Substring(1));
						string text = "\n>" + ((Object)terminalKeyword).name.ToUpper() + "\n" + commandInfo.Description + "\n\n";
						NodeAppendLine(commandInfo.Category, text);
					}
					Terminal.terminalNodes.allKeywords = Terminal.terminalNodes.allKeywords.Add(terminalKeyword);
					ManualLogSource log = plugin.Log;
					if (log != null)
					{
						log.LogMessage((object)("Added " + terminalKeyword.word + " keyword to terminal keywords."));
					}
				}
				else
				{
					ManualLogSource log2 = plugin.Log;
					if (log2 != null)
					{
						log2.LogWarning((object)("Failed to add " + terminalKeyword.word + " keyword. Already exists."));
					}
				}
			}
			else
			{
				ManualLogSource log3 = plugin.Log;
				if (log3 != null)
				{
					log3.LogMessage((object)("Not in game, waiting to be in game to add " + terminalKeyword.word + " keyword."));
				}
				Action<TerminalKeyword, CommandInfo> action = AddTerminalKeyword;
				DelayedAddTerminalKeyword item = new DelayedAddTerminalKeyword
				{
					Action = action,
					Keyword = terminalKeyword,
					CommandInfo = commandInfo
				};
				QueuedDelayedActions.Add(item);
			}
		}

		public static void NodeAppendLine(string word, string text)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(word.ToLower());
			if ((Object)(object)keyword != (Object)null)
			{
				keyword.specialKeywordResult.displayText = keyword.specialKeywordResult.displayText.Trim() + "\n" + text;
				return;
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("Failed to add text to " + word + ". Does not exist."));
			}
		}

		public static TerminalKeyword GetKeyword(string keyword)
		{
			if (IsInGame())
			{
				return ((IEnumerable<TerminalKeyword>)Terminal.terminalNodes.allKeywords).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword Kw) => Kw.word == keyword));
			}
			return null;
		}

		public static void UpdateKeyword(TerminalKeyword keyword)
		{
			if (!IsInGame())
			{
				return;
			}
			for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++)
			{
				if (Terminal.terminalNodes.allKeywords[i].word == keyword.word)
				{
					Terminal.terminalNodes.allKeywords[i] = keyword;
					return;
				}
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("Failed to update " + keyword.word + ". Was not found in keywords."));
			}
		}

		public static void DeleteKeyword(string word)
		{
			if (!IsInGame())
			{
				return;
			}
			for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++)
			{
				if (Terminal.terminalNodes.allKeywords[i].word == word.ToLower())
				{
					int newSize = Terminal.terminalNodes.allKeywords.Length - 1;
					for (int j = i + 1; j < Terminal.terminalNodes.allKeywords.Length; j++)
					{
						Terminal.terminalNodes.allKeywords[j - 1] = Terminal.terminalNodes.allKeywords[j];
					}
					Array.Resize(ref Terminal.terminalNodes.allKeywords, newSize);
					ManualLogSource log = plugin.Log;
					if (log != null)
					{
						log.LogMessage((object)(word + " was deleted successfully."));
					}
					return;
				}
			}
			ManualLogSource log2 = plugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)("Failed to delete " + word + ". Was not found in keywords."));
			}
		}

		public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode newTriggerNode)
		{
			if (!IsInGame() || !verbKeyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = verbKeyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result = newTriggerNode;
					UpdateKeyword(verbKeyword);
					return;
				}
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}");
			}
		}

		public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, TerminalNode newTriggerNode)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			if (!keyword.isVerb || verbWord == null)
			{
				return;
			}
			for (int i = 0; i < keyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = keyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result = newTriggerNode;
					UpdateKeyword(keyword);
					return;
				}
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)$"WARNING: No noun found for {keyword}");
			}
		}

		public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, string newDisplayText)
		{
			if (!IsInGame() || !verbKeyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = verbKeyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result.displayText = newDisplayText;
					UpdateKeyword(verbKeyword);
					return;
				}
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}");
			}
		}

		public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, string newDisplayText)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			if (!keyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < keyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = keyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result.displayText = newDisplayText;
					UpdateKeyword(keyword);
					return;
				}
			}
			ManualLogSource log = plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)$"WARNING: No noun found for {keyword}");
			}
		}

		public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, string displayText, bool clearPreviousText = false)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(noun);
				verbKeyword = verbKeyword.AddCompatibleNoun(keyword, displayText, clearPreviousText);
				UpdateKeyword(verbKeyword);
			}
		}

		public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode triggerNode)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(noun);
				verbKeyword = verbKeyword.AddCompatibleNoun(keyword, triggerNode);
				UpdateKeyword(verbKeyword);
			}
		}

		public static void AddCompatibleNoun(string verbWord, string noun, TerminalNode triggerNode)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			TerminalKeyword keyword2 = GetKeyword(noun);
			if ((Object)(object)keyword == (Object)null)
			{
				ManualLogSource log = plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"The verb given does not exist.");
				}
			}
			else
			{
				keyword = keyword.AddCompatibleNoun(keyword2, triggerNode);
				UpdateKeyword(keyword);
			}
		}

		public static void AddCompatibleNoun(string verbWord, string noun, string displayText, bool clearPreviousText = false)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			TerminalKeyword keyword2 = GetKeyword(noun);
			if ((Object)(object)keyword == (Object)null)
			{
				ManualLogSource log = plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"The verb given does not exist.");
				}
			}
			else
			{
				keyword = keyword.AddCompatibleNoun(keyword2, displayText, clearPreviousText);
				UpdateKeyword(keyword);
			}
		}

		public static string GetTerminalInput()
		{
			if (IsInGame())
			{
				return CurrentText.Substring(CurrentText.Length - Terminal.textAdded);
			}
			return "";
		}

		public static void SetTerminalInput(string terminalInput)
		{
			Terminal.TextChanged(CurrentText.Substring(0, CurrentText.Length - Terminal.textAdded) + terminalInput);
			ScreenText.text = CurrentText;
			Terminal.textAdded = terminalInput.Length;
		}
	}
	public static class TerminalExtenstionMethods
	{
		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, TerminalNode result)
		{
			//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)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = noun,
					result = result
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, TerminalNode result)
		{
			//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)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = TerminalApi.CreateTerminalKeyword(noun),
					result = result
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, string displayText)
		{
			//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)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = TerminalApi.CreateTerminalKeyword(noun),
					result = TerminalApi.CreateTerminalNode(displayText)
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, string displayText, bool clearPreviousText = false)
		{
			//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)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = noun,
					result = TerminalApi.CreateTerminalNode(displayText, clearPreviousText)
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		internal static T[] Add<T>(this T[] array, T newItem)
		{
			int num = array.Length + 1;
			Array.Resize(ref array, num);
			array[num - 1] = newItem;
			return array;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TerminalApi";

		public const string PLUGIN_NAME = "TerminalApi";

		public const string PLUGIN_VERSION = "1.5.1";
	}
}
namespace TerminalApi.Interfaces
{
	internal interface IDelayedAction
	{
		internal void Run();
	}
}
namespace TerminalApi.Events
{
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	public static class Events
	{
		public class TerminalEventArgs : EventArgs
		{
			public Terminal Terminal { get; set; }
		}

		public delegate void TerminalEventHandler(object sender, TerminalEventArgs e);

		public class TerminalParseSentenceEventArgs : TerminalEventArgs
		{
			public TerminalNode ReturnedNode { get; set; }

			public string SubmittedText { get; set; }
		}

		public delegate void TerminalParseSentenceEventHandler(object sender, TerminalParseSentenceEventArgs e);

		public class TerminalTextChangedEventArgs : TerminalEventArgs
		{
			public string NewText;

			public string CurrentInputText;
		}

		public delegate void TerminalTextChangedEventHandler(object sender, TerminalTextChangedEventArgs e);

		public static event TerminalEventHandler TerminalAwake;

		public static event TerminalEventHandler TerminalWaking;

		public static event TerminalEventHandler TerminalStarted;

		public static event TerminalEventHandler TerminalStarting;

		public static event TerminalEventHandler TerminalBeginUsing;

		public static event TerminalEventHandler TerminalBeganUsing;

		public static event TerminalEventHandler TerminalExited;

		public static event TerminalParseSentenceEventHandler TerminalParsedSentence;

		public static event TerminalTextChangedEventHandler TerminalTextChanged;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		public static void Awake(ref Terminal __instance)
		{
			TerminalApi.Terminal = __instance;
			if (TerminalApi.QueuedDelayedActions.Count > 0)
			{
				ManualLogSource log = TerminalApi.plugin.Log;
				if (log != null)
				{
					log.LogMessage((object)"In game, applying any changes now.");
				}
				foreach (IDelayedAction queuedDelayedAction in TerminalApi.QueuedDelayedActions)
				{
					queuedDelayedAction.Run();
				}
				TerminalApi.QueuedDelayedActions.Clear();
			}
			Events.TerminalAwake?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPostfix]
		public static void BeganUsing(ref Terminal __instance)
		{
			Events.TerminalBeganUsing?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("QuitTerminal")]
		[HarmonyPostfix]
		public static void OnQuitTerminal(ref Terminal __instance)
		{
			Events.TerminalExited?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPrefix]
		public static void OnBeginUsing(ref Terminal __instance)
		{
			Events.TerminalBeginUsing?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("ParsePlayerSentence")]
		[HarmonyPostfix]
		public static void ParsePlayerSentence(ref Terminal __instance, TerminalNode __result)
		{
			CommandInfo commandInfo = TerminalApi.CommandInfos.FirstOrDefault((CommandInfo cI) => (Object)(object)cI.TriggerNode == (Object)(object)__result);
			if (commandInfo != null)
			{
				__result.displayText = commandInfo?.DisplayTextSupplier();
			}
			string submittedText = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
			Events.TerminalParsedSentence?.Invoke(__instance, new TerminalParseSentenceEventArgs
			{
				Terminal = __instance,
				SubmittedText = submittedText,
				ReturnedNode = __result
			});
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void Started(ref Terminal __instance)
		{
			Events.TerminalStarted?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		public static void Starting(ref Terminal __instance)
		{
			Events.TerminalStarting?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("TextChanged")]
		[HarmonyPostfix]
		public static void OnTextChanged(ref Terminal __instance, string newText)
		{
			string currentInputText = "";
			if (newText.Trim().Length >= __instance.textAdded)
			{
				currentInputText = newText.Substring(newText.Length - __instance.textAdded);
			}
			Events.TerminalTextChanged?.Invoke(__instance, new TerminalTextChangedEventArgs
			{
				Terminal = __instance,
				NewText = newText,
				CurrentInputText = currentInputText
			});
		}

		[HarmonyPatch("Awake")]
		[HarmonyPrefix]
		public static void Waking(ref Terminal __instance)
		{
			Events.TerminalWaking?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}
	}
}
namespace TerminalApi.Classes
{
	public class CommandInfo
	{
		public string Title { get; set; }

		public string Category { get; set; }

		public string Description { get; set; }

		public TerminalNode TriggerNode { get; set; }

		public Func<string> DisplayTextSupplier { get; set; }
	}
}

plugins/Dependencies/FlipMods-ReservedItemSlotCore-1.8.8/ReservedItemSlotCore.dll

Decompiled 10 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 BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using ReservedItemSlotCore.Config;
using ReservedItemSlotCore.Input;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using TMPro;
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("ReservedItemSlotCore")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedItemSlotCore")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ReservedFlashlightSlot")]
[assembly: InternalsVisibleTo("ReservedWalkieSlot")]
[assembly: InternalsVisibleTo("ReservedWeaponSlot")]
[assembly: InternalsVisibleTo("ReservedUtilitySlot")]
[assembly: InternalsVisibleTo("ReservedSprayPaintSlot")]
[assembly: InternalsVisibleTo("ReservedBoomboxSlot")]
[assembly: InternalsVisibleTo("ReservedPersonalBoomboxSlot")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedItemSlotCore
{
	internal class ReservedPlayerData
	{
		public PlayerControllerB playerController;

		public ReservedItemInfo grabbingReservedItem = null;

		public int previousHotbarIndex = -1;

		public bool inReservedHotbarSlots = false;

		public int hotbarSize = 4;

		public int reservedHotbarStartIndex = 4;

		public bool isLocalPlayer => (Object)(object)StartOfRound.Instance?.localPlayerController != (Object)null && (Object)(object)playerController == (Object)(object)StartOfRound.Instance.localPlayerController;

		public int currentItemSlot => playerController.currentItemSlot;

		public bool currentItemSlotIsReserved => currentItemSlot >= reservedHotbarStartIndex && currentItemSlot < reservedHotbarStartIndex + SyncManager.numReservedItemSlots;

		public GrabbableObject previouslyHeldItem => (previousHotbarIndex >= 0 && previousHotbarIndex < playerController.ItemSlots.Length) ? playerController.ItemSlots[previousHotbarIndex] : null;

		public bool IsReservedItemSlot(int index)
		{
			return index >= reservedHotbarStartIndex && index < reservedHotbarStartIndex + SyncManager.numReservedItemSlots;
		}

		public int GetNumHeldReservedItems(bool safe = false)
		{
			int num = 0;
			if (!safe)
			{
				for (int i = reservedHotbarStartIndex; i < reservedHotbarStartIndex + SyncManager.numReservedItemSlots; i++)
				{
					num += (((Object)(object)playerController.ItemSlots[i] != (Object)null) ? 1 : 0);
				}
			}
			else
			{
				for (int j = 0; j < playerController.ItemSlots.Length; j++)
				{
					GrabbableObject val = playerController.ItemSlots[j];
					num += (((Object)(object)val != (Object)null && SyncManager.IsReservedItem(val.itemProperties.itemName)) ? 1 : 0);
				}
			}
			return num;
		}

		public string DumpData()
		{
			string text = "[ReservedPlayerData Dump]\nPlayer: " + ((Object)playerController).name + (isLocalPlayer ? " [LocalPlayer]" : "") + "\nCurrentItemSlot: " + currentItemSlot + "\nRegisteredHotbarSize: " + hotbarSize + "\nActualHotbarSize: " + playerController.ItemSlots.Length + "\nCurrentlyGrabbingReservedItem: " + ((grabbingReservedItem != null) ? grabbingReservedItem.itemName : "false") + "\nReservedHotbarStartIndex: " + reservedHotbarStartIndex + "\n" + (isLocalPlayer ? ("NumItemSlotsHUD: " + HUDManager.Instance.itemSlotIconFrames.Length + "\n") : "") + "ItemsInInventory: [";
			for (int i = 0; i < playerController.ItemSlots.Length; i++)
			{
				if (i > 0)
				{
					text += ", ";
				}
				text += (("[" + i + "] " + (object)playerController.ItemSlots[i] != null) ? ((Object)playerController.ItemSlots[i]).name : "Empty");
			}
			return text + "]\nNumHeldReservedItems: " + GetNumHeldReservedItems(safe: true);
		}
	}
	[BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "1.8.8")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin instance;

		private static ManualLogSource logger;

		public static Dictionary<string, ReservedItemInfo> reservedItemsDictDefault => ReservedItemInfo.reservedItemsDictDefault;

		public static List<ReservedItemInfo> reservedItemsListDefault => ReservedItemInfo.reservedItemsListDefault;

		public static List<ReservedItemInfo> reservedItemSlotRepsDefault => ReservedItemInfo.reservedItemSlotRepsDefault;

		public static int numReservedItemSlotsDefault => ReservedItemInfo.numReservedItemSlotsDefault;

		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("ReservedItemSlotCore");
			_harmony.PatchAll();
			Log("ReservedItemSlotCore loaded");
		}

		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 bool IsReservedItemDefault(string itemName)
		{
			return reservedItemsDictDefault.ContainsKey(itemName);
		}

		public static ReservedItemInfo GetReservedItemInfoDefault(string itemName)
		{
			return IsReservedItemDefault(itemName) ? reservedItemsDictDefault[itemName] : null;
		}

		public static ReservedItemInfo GetReservedItemInfoDefault(GrabbableObject item)
		{
			return ((Object)(object)item != (Object)null) ? GetReservedItemInfoDefault(item.itemProperties.itemName) : null;
		}

		public static int GetReservedItemHotbarIndex(string itemName)
		{
			return IsReservedItemDefault(itemName) ? reservedItemsDictDefault[itemName].indexInInventory : (-1);
		}
	}
	internal class ReservedItemInfo
	{
		public static Dictionary<string, ReservedItemInfo> reservedItemsDictDefault = new Dictionary<string, ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemsListDefault = new List<ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemSlotRepsDefault = new List<ReservedItemInfo>();

		public static Dictionary<string, ReservedItemInfo> reservedItemsDict = new Dictionary<string, ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemsList = new List<ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemSlotReps = new List<ReservedItemInfo>();

		public string itemName = "";

		public HashSet<string> acceptedItemNames;

		public int hotbarSlotPriority = 0;

		public int reservedItemIndex = 0;

		public bool forceUpdateCanBeGrabbedBeforeGameStart = false;

		public bool canBeGrabbedBeforeGameStart = false;

		public bool forceUpdateRequiresBattery = false;

		public bool requiresBattery = false;

		public static int numReservedItemSlotsDefault => reservedItemSlotRepsDefault.Count;

		public int indexInInventory => ((Object)(object)PlayerPatcher.localPlayerController != (Object)null) ? (PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedItemIndex) : (-1);

		public ReservedItemInfo()
		{
		}

		public ReservedItemInfo(string itemName, int hotbarSlotPriority, bool forceUpdateCanBeGrabbedBeforeGameStart = false, bool canBeGrabbedBeforeGameStart = false, bool forceUpdateRequiresBattery = false, bool requiresBattery = false)
		{
			this.itemName = itemName;
			this.hotbarSlotPriority = hotbarSlotPriority;
			AddItemInfoToList(this);
			ReservedItemInfo info = new ReservedItemInfo(this);
			AddItemInfoToList(info, reservedItemsListDefault, reservedItemsDictDefault, reservedItemSlotRepsDefault);
		}

		public static void AddItemInfoToList(ReservedItemInfo info, List<ReservedItemInfo> _reservedItemsList = null, Dictionary<string, ReservedItemInfo> _reservedItemsDict = null, List<ReservedItemInfo> _reservedItemSlotReps = null)
		{
			if (_reservedItemsList == null)
			{
				_reservedItemsList = reservedItemsList;
			}
			if (_reservedItemsDict == null)
			{
				_reservedItemsDict = reservedItemsDict;
			}
			if (_reservedItemSlotReps == null)
			{
				_reservedItemSlotReps = reservedItemSlotReps;
			}
			if (!_reservedItemsDict.ContainsKey(info.itemName))
			{
				_reservedItemsDict.Add(info.itemName, info);
				_reservedItemsList.Add(info);
				int i;
				for (i = 0; i < _reservedItemSlotReps.Count; i++)
				{
					ReservedItemInfo reservedItemInfo = _reservedItemSlotReps[i];
					if (info.hotbarSlotPriority >= reservedItemInfo.hotbarSlotPriority)
					{
						break;
					}
				}
				info.reservedItemIndex = i;
				if (i == _reservedItemSlotReps.Count || info.hotbarSlotPriority != _reservedItemSlotReps[i].hotbarSlotPriority)
				{
					info.acceptedItemNames = new HashSet<string> { info.itemName };
					_reservedItemSlotReps.Insert(i, info);
					{
						foreach (ReservedItemInfo _reservedItems in _reservedItemsList)
						{
							if (info != _reservedItems && _reservedItems.reservedItemIndex >= i)
							{
								_reservedItems.reservedItemIndex++;
							}
						}
						return;
					}
				}
				info.acceptedItemNames = _reservedItemSlotReps[i].acceptedItemNames;
				info.acceptedItemNames.Add(info.itemName);
			}
			else
			{
				Plugin.Log($"Tried to add duplicate item name to the ReservedItems list: {info.itemName}. Sorting instead");
			}
		}

		public ReservedItemInfo(ReservedItemInfo copyFrom)
		{
			itemName = copyFrom.itemName;
			hotbarSlotPriority = copyFrom.hotbarSlotPriority;
			reservedItemIndex = copyFrom.reservedItemIndex;
			forceUpdateCanBeGrabbedBeforeGameStart = copyFrom.forceUpdateCanBeGrabbedBeforeGameStart;
			canBeGrabbedBeforeGameStart = copyFrom.canBeGrabbedBeforeGameStart;
			forceUpdateRequiresBattery = copyFrom.forceUpdateRequiresBattery;
			requiresBattery = copyFrom.requiresBattery;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedItemSlotCore";

		public const string PLUGIN_NAME = "ReservedItemSlotCore";

		public const string PLUGIN_VERSION = "1.8.8";
	}
}
namespace ReservedItemSlotCore.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> focusReservedHotbarHotkey;

		public static ConfigEntry<bool> toggleFocusReservedHotbar;

		public static ConfigEntry<bool> preventReservedItemSlotFade;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			focusReservedHotbarHotkey = AddConfigEntry<string>(((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "FocusReservedItemSlotsHotkey", "<Keyboard>/leftAlt", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)"));
			toggleFocusReservedHotbar = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "ToggleFocusReservedHotbar", false, "If set to true, swapping to the reserved hotbar slots will be toggled when pressing the hotkey rather than while holding the hotkey. Setting this option to true may have bugs at this current time."));
			preventReservedItemSlotFade = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "PreventReservedHotbarSlotFade", false, "If true, the reserved hotbar slots will not fade with the rest of the default slots."));
			TryRemoveOldConfigSettings();
		}

		public static ConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			currentConfigEntries.Add(((ConfigEntryBase)configEntry).Definition.Key, (ConfigEntryBase)(object)configEntry);
			return configEntry;
		}

		public static string GetDisplayName(string key)
		{
			try
			{
				if (key.Length <= 1)
				{
					return key;
				}
				int num = key.IndexOf(">/");
				key = ((num >= 0) ? key.Substring(num + 2) : key);
				string text = key.ToLower();
				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");
				text = text.Replace("middlebutton", "MMB");
				text = text.Replace("lefttrigger", "LT");
				text = text.Replace("righttrigger", "RT");
				text = text.Replace("leftshoulder", "LB");
				text = text.Replace("rightshoulder", "RB");
				text = text.Replace("leftstickpress", "LS");
				text = text.Replace("rightstickpress", "RS");
				try
				{
					text = char.ToUpper(text[0]) + text.Substring(1);
				}
				catch
				{
				}
				return text;
			}
			catch
			{
				return "";
			}
		}

		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
			{
			}
		}
	}
}
namespace ReservedItemSlotCore.Networking
{
	public static class NetworkHelper
	{
		private static int NONE_EXEC_STAGE = 0;

		private static int SERVER_EXEC_STAGE = 1;

		private static int CLIENT_EXEC_STAGE = 2;

		public static int GetExecStage(NetworkBehaviour __instance)
		{
			return (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue();
		}

		public static bool IsClientExecStage(NetworkBehaviour __instance)
		{
			return GetExecStage(__instance) == CLIENT_EXEC_STAGE;
		}

		public static bool IsServerExecStage(NetworkBehaviour __instance)
		{
			return GetExecStage(__instance) == SERVER_EXEC_STAGE;
		}

		public static bool IsValidClientRpcExecStage(NetworkBehaviour __instance)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				return false;
			}
			int num = (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue();
			if ((singleton.IsServer || singleton.IsHost) && num != 2)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal class SyncManager
	{
		public static PlayerControllerB localPlayerController;

		public static bool isSynced = false;

		public static bool canUseModDisabledOnHost = true;

		public static Dictionary<string, ReservedItemInfo> syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>();

		public static List<ReservedItemInfo> syncReservedItemsList = new List<ReservedItemInfo>();

		public static List<ReservedItemInfo> syncReservedItemSlotReps = new List<ReservedItemInfo>();

		public static int numReservedItemSlots => syncReservedItemSlotReps.Count;

		public static bool IsReservedItem(string itemName)
		{
			return syncReservedItemsDict.ContainsKey(itemName);
		}

		public static bool TryGetReservedItemInfo(string itemName, out ReservedItemInfo info)
		{
			info = null;
			if (IsReservedItem(itemName))
			{
				info = syncReservedItemsDict[itemName];
				return true;
			}
			return false;
		}

		public static bool TryGetReservedItemInfo(GrabbableObject item, out ReservedItemInfo info)
		{
			info = null;
			return (Object)(object)item != (Object)null && TryGetReservedItemInfo(item.itemProperties.itemName, out info);
		}

		public static int GetReservedItemHotbarIndex(string itemName)
		{
			return IsReservedItem(itemName) ? syncReservedItemsDict[itemName].indexInInventory : (-1);
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void ResetValues()
		{
			isSynced = false;
			localPlayerController = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init(PlayerControllerB __instance)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			localPlayerController = __instance;
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarClientRpc", new HandleNamedMessageDelegate(OnSwapHotbarClientRpc));
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncClientRpc", new HandleNamedMessageDelegate(RequestSyncClientRpc));
			if (NetworkManager.Singleton.IsServer)
			{
				isSynced = true;
				syncReservedItemsDict = ReservedItemInfo.reservedItemsDict;
				syncReservedItemsList = ReservedItemInfo.reservedItemsList;
				syncReservedItemSlotReps = ReservedItemInfo.reservedItemSlotReps;
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncServerRpc", new HandleNamedMessageDelegate(RequestSyncServerRpc));
				{
					foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList)
					{
						ReservedItemInfo reservedItemInfo = ReservedItemInfo.reservedItemsDictDefault[syncReservedItems.itemName];
						syncReservedItems.hotbarSlotPriority = reservedItemInfo.hotbarSlotPriority;
						syncReservedItems.reservedItemIndex = reservedItemInfo.reservedItemIndex;
					}
					return;
				}
			}
			isSynced = false;
			if (canUseModDisabledOnHost)
			{
				syncReservedItemsDict = ReservedItemInfo.reservedItemsDict;
				syncReservedItemsList = ReservedItemInfo.reservedItemsList;
				syncReservedItemSlotReps = ReservedItemInfo.reservedItemSlotReps;
			}
			else
			{
				syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>();
				syncReservedItemsList = new List<ReservedItemInfo>();
				syncReservedItemSlotReps = new List<ReservedItemInfo>();
			}
			RequestSyncWithServer();
		}

		private static void RequestSyncWithServer()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				Plugin.Log("Requesting sync with server.");
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-RequestSyncServerRpc", 0uL, new FastBufferWriter(0, (Allocator)2, -1), (NetworkDelivery)3);
			}
		}

		private static void RequestSyncServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_009b: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer)
			{
				return;
			}
			Plugin.Log("Receiving sync request from client: " + clientId);
			int num = 4 * syncReservedItemsList.Count;
			foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList)
			{
				num += 4 + 2 * syncReservedItems.itemName.Length;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num, (Allocator)2, -1);
			int count = syncReservedItemsList.Count;
			((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives));
			foreach (ReservedItemInfo syncReservedItems2 in syncReservedItemsList)
			{
				count = syncReservedItems2.itemName.Length;
				((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives));
				string itemName = syncReservedItems2.itemName;
				for (int i = 0; i < itemName.Length; i++)
				{
					char c = itemName[i];
					((FastBufferWriter)(ref val)).WriteValue<char>(ref c, default(ForPrimitives));
				}
				((FastBufferWriter)(ref val)).WriteValue<int>(ref syncReservedItems2.hotbarSlotPriority, default(ForPrimitives));
			}
			Plugin.Log("Sent sync to client.");
			NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-RequestSyncClientRpc", clientId, val, (NetworkDelivery)3);
		}

		private static void RequestSyncClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_005e: 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_0079: 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_00a5: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsClient || NetworkManager.Singleton.IsServer)
			{
				return;
			}
			PlayerPatcher.isSynced = false;
			isSynced = true;
			syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>();
			syncReservedItemsList = new List<ReservedItemInfo>();
			syncReservedItemSlotReps = new List<ReservedItemInfo>();
			Plugin.Log("Receiving sync from server.");
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
			int num2 = default(int);
			char c = default(char);
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives));
				((FastBufferReader)(ref reader)).TryBeginRead(2 * num2);
				string text = "";
				for (int j = 0; j < num2; j++)
				{
					((FastBufferReader)(ref reader)).ReadValue<char>(ref c, default(ForPrimitives));
					text += c;
				}
				bool flag = ReservedItemInfo.reservedItemsDict.ContainsKey(text);
				ReservedItemInfo reservedItemInfo = (ReservedItemInfo.reservedItemsDict.ContainsKey(text) ? ReservedItemInfo.reservedItemsDict[text] : new ReservedItemInfo
				{
					itemName = text
				});
				((FastBufferReader)(ref reader)).ReadValue<int>(ref reservedItemInfo.hotbarSlotPriority, default(ForPrimitives));
				Plugin.Log("Receiving sync for item: - Item: " + reservedItemInfo.itemName + " Prio: " + reservedItemInfo.hotbarSlotPriority);
				ReservedItemInfo.AddItemInfoToList(reservedItemInfo, syncReservedItemsList, syncReservedItemsDict, syncReservedItemSlotReps);
			}
			Plugin.Log("Received sync for " + syncReservedItemSlotReps.Count + " reserved item slots. (" + syncReservedItemsList.Count + " items total)");
		}

		private static void SendSwapHotbarUpdate(int hotbarSlot)
		{
			//IL_0024: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives));
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-OnSwapHotbarServerRpc", 0uL, val, (NetworkDelivery)3);
			}
		}

		private static void OnSwapHotbarServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsServer)
			{
				if (((FastBufferReader)(ref reader)).TryBeginRead(4))
				{
					int num = default(int);
					((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
					Plugin.Log("Receiving OnSwapReservedHotbar update from client. ClientId: " + clientId + " Slot: " + num);
					FastBufferWriter val = default(FastBufferWriter);
					((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1);
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("ReservedItemSlots-OnSwapHotbarClientRpc", val, (NetworkDelivery)3);
				}
				else
				{
					Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId);
				}
			}
		}

		private static void OnSwapHotbarClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_002e: 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_0042: 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 (!NetworkManager.Singleton.IsClient)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(12))
			{
				int hotbarSlot = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives));
				ulong num = default(ulong);
				((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives));
				Plugin.Log("Receiving OnSwapReservedHotbar update from client. ClientId: " + num + " Slot: " + hotbarSlot);
				if (num != localPlayerController.actualClientId && !TryUpdateClientHotbarSlot(num, hotbarSlot))
				{
					Plugin.Log("Failed to receive hotbar swap index from Client: " + num);
				}
			}
			else
			{
				Plugin.Log("Failed to receive hotbar swap index from Client");
			}
		}

		private static bool TryUpdateClientHotbarSlot(ulong clientId, int hotbarSlot)
		{
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i];
				if (val.actualClientId == clientId)
				{
					CallSwitchToItemSlotMethod(val, hotbarSlot);
					return true;
				}
			}
			return false;
		}

		public static void SwapHotbarSlot(int hotbarIndex)
		{
			SendSwapHotbarUpdate(hotbarIndex);
			CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex);
		}

		private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex)
		{
			if (!((Object)(object)playerController == (Object)null) && playerController.ItemSlots != null && hotbarIndex >= 0 && hotbarIndex < playerController.ItemSlots.Length)
			{
				if ((Object)(object)playerController == (Object)(object)localPlayerController)
				{
					ShipBuildModeManager.Instance.CancelBuildMode(true);
					playerController.playerBodyAnimator.SetBool("GrabValidated", false);
				}
				ReservedItemPatcher.SwitchToItemSlot(playerController, hotbarIndex);
				if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null)
				{
					((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f);
				}
			}
		}
	}
}
namespace ReservedItemSlotCore.Input
{
	internal class IngameKeybinds : LcInputActions
	{
		internal static IngameKeybinds Instance = new IngameKeybinds();

		[InputAction("<Keyboard>/leftAlt", Name = "[ReservedItemSlots]\nSwap hotbar")]
		public InputAction FocusReservedHotbarHotkey { get; set; }

		internal static InputActionAsset GetAsset()
		{
			return ((LcInputActions)Instance).Asset;
		}
	}
	internal class InputUtilsCompat
	{
		internal static InputActionAsset Asset => IngameKeybinds.GetAsset();

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

		public static InputAction FocusReservedHotbarHotkey => IngameKeybinds.Instance.FocusReservedHotbarHotkey;
	}
	[HarmonyPatch]
	internal class Keybinds
	{
		public static InputActionAsset Asset;

		public static InputActionMap ActionMap;

		public static InputAction FocusReservedHotbarAction;

		public static InputAction RawScrollAction;

		public static bool holdingModifierKey;

		public static bool scrollingReservedHotbar;

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

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		public static void AddToKeybindMenu()
		{
			InitKeybinds();
		}

		public static void InitKeybinds()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			if (InputUtilsCompat.Enabled)
			{
				Asset = InputUtilsCompat.Asset;
				FocusReservedHotbarAction = InputUtilsCompat.FocusReservedHotbarHotkey;
			}
			else
			{
				Asset = new InputActionAsset();
				ActionMap = new InputActionMap("ReservedItemSlots");
				InputActionSetupExtensions.AddActionMap(Asset, ActionMap);
				FocusReservedHotbarAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.FocusReservedHotbar", (InputActionType)0, ConfigSettings.focusReservedHotbarHotkey.Value, (string)null, (string)null, (string)null, (string)null);
			}
			RawScrollAction = new InputAction("ReservedItemSlots.RawScroll", (InputActionType)0, "<Mouse>/scroll/y", (string)null, (string)null, (string)null);
		}

		[HarmonyPatch(typeof(StartOfRound), "OnEnable")]
		[HarmonyPrefix]
		public static void OnEnable()
		{
			Asset.Enable();
			RawScrollAction.Enable();
			FocusReservedHotbarAction.performed += FocusReservedHotbarSlotsAction;
			if (!ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				FocusReservedHotbarAction.canceled += UnfocusReservedHotbarSlotsPerformed;
			}
			RawScrollAction.performed += OnScrollReservedHotbar;
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		[HarmonyPrefix]
		public static void OnDisable()
		{
			Asset.Disable();
			RawScrollAction.Disable();
			FocusReservedHotbarAction.performed -= FocusReservedHotbarSlotsAction;
			if (!ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				FocusReservedHotbarAction.canceled -= UnfocusReservedHotbarSlotsPerformed;
			}
			RawScrollAction.performed -= OnScrollReservedHotbar;
		}

		private static void FocusReservedHotbarSlotsAction(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !((NetworkBehaviour)localPlayerController).IsOwner || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject) || SyncManager.numReservedItemSlots <= 0 || !HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return;
			}
			if (!ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				holdingModifierKey = true;
			}
			if (((CallbackContext)(ref context)).performed && ReservedItemPatcher.CanSwapToReservedHotbarSlot())
			{
				if (!ConfigSettings.toggleFocusReservedHotbar.Value)
				{
					ReservedItemPatcher.FocusReservedHotbarSlots(active: true);
				}
				else
				{
					ReservedItemPatcher.FocusReservedHotbarSlots(!PlayerPatcher.playerDataLocal.currentItemSlotIsReserved);
				}
			}
		}

		private static void UnfocusReservedHotbarSlotsPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				holdingModifierKey = false;
				if (((CallbackContext)(ref context)).canceled && ReservedItemPatcher.CanSwapToReservedHotbarSlot())
				{
					ReservedItemPatcher.FocusReservedHotbarSlots(active: false);
				}
			}
		}

		private static void OnScrollReservedHotbar(CallbackContext context)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject) && ((CallbackContext)(ref context)).performed && PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && PlayerPatcher.playerDataLocal.grabbingReservedItem == null)
			{
				scrollingReservedHotbar = true;
				MethodInfo method = ((object)localPlayerController).GetType().GetMethod("ScrollMouse_performed", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(localPlayerController, new object[1] { context });
				((MonoBehaviour)localPlayerController).StartCoroutine(ResetScrollStateEndOfFrame());
			}
			static IEnumerator ResetScrollStateEndOfFrame()
			{
				yield return (object)new WaitForEndOfFrame();
				scrollingReservedHotbar = false;
			}
		}
	}
}
namespace ReservedItemSlotCore.Patches
{
	[HarmonyPatch]
	public static class HUDPatcher
	{
		private static float iconWidth;

		private static float xPos;

		private static TextMeshProUGUI hotkeyTooltip;

		public static List<Image> reservedItemSlots;

		private static bool usingController;

		public static bool hasReservedItemSlotsAndEnabled => reservedItemSlots != null && reservedItemSlots.Count > 0 && ((Component)reservedItemSlots[0]).gameObject.activeSelf && ((Behaviour)reservedItemSlots[0]).enabled;

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPostfix]
		public static void Initialize(HUDManager __instance)
		{
			//IL_002a: 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)
			CanvasScaler componentInParent = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>();
			AspectRatioFitter componentInParent2 = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>();
			iconWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x;
			xPos = componentInParent.referenceResolution.x / 2f / componentInParent2.aspectRatio - iconWidth / 4f;
			reservedItemSlots = new List<Image>();
		}

		[HarmonyPatch(typeof(StartOfRound), "Update")]
		[HarmonyPostfix]
		public static void UpdateUsingController(StartOfRound __instance)
		{
			if (!((Object)(object)__instance.localPlayerController == (Object)null) && !((Object)(object)hotkeyTooltip == (Object)null) && ((Component)hotkeyTooltip).gameObject.activeSelf && ((Behaviour)hotkeyTooltip).enabled && __instance.localPlayerUsingController != usingController)
			{
				usingController = __instance.localPlayerUsingController;
				UpdateHotkeyTooltipText();
			}
		}

		public static void AddNewHotbarSlotsHud()
		{
			//IL_0048: 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_0069: 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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: 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_0318: 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_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_035f: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerPatcher.reservedHotbarSize <= 0)
			{
				return;
			}
			List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames);
			List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons);
			float y = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.y;
			Vector3 eulerAngles = ((Transform)((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>()).eulerAngles;
			Vector3 eulerAngles2 = ((Transform)((Component)HUDManager.Instance.itemSlotIcons[0]).GetComponent<RectTransform>()).eulerAngles;
			Plugin.Log($"Adding {SyncManager.syncReservedItemSlotReps.Count} Reserved item slots to the inventory HUD. Previous inventory HUD size: {PlayerPatcher.playerDataLocal.reservedHotbarStartIndex}");
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < SyncManager.syncReservedItemSlotReps.Count; i++)
			{
				ReservedItemInfo reservedItemInfo = SyncManager.syncReservedItemSlotReps[i];
				Plugin.Log($"Adding Reserved item slot for item types [{reservedItemInfo.itemName}]. Inventory index: {list.Count}");
				float num3 = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * y * (float)i;
				Image val = Object.Instantiate<Image>(HUDManager.Instance.itemSlotIconFrames[PlayerPatcher.playerDataLocal.reservedHotbarStartIndex - 1], ((Component)HUDManager.Instance.itemSlotIconFrames[0]).transform.parent);
				((Object)val).name = "Slot" + list.Count + " [ReservedItemSlot]";
				((Graphic)val).rectTransform.anchoredPosition = new Vector2((reservedItemInfo.hotbarSlotPriority >= 0) ? xPos : (0f - xPos), num3);
				((Transform)((Graphic)val).rectTransform).eulerAngles = eulerAngles;
				CanvasGroup val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>();
				val2.ignoreParentGroups = ConfigSettings.preventReservedItemSlotFade.Value;
				val2.alpha = 1f;
				Image component = ((Component)((Component)val).transform.GetChild(0)).GetComponent<Image>();
				((Object)component).name = "Icon";
				((Transform)((Graphic)component).rectTransform).eulerAngles = eulerAngles2;
				reservedItemSlots.Add(val);
				list.Add(val);
				list2.Add(component);
				if (reservedItemInfo.hotbarSlotPriority >= 0)
				{
					num++;
				}
				else
				{
					num2++;
				}
			}
			if (SyncManager.numReservedItemSlots > 0 && (Object)(object)hotkeyTooltip == (Object)null)
			{
				hotkeyTooltip = new GameObject("ReservedItemSlotTooltip", new Type[2]
				{
					typeof(RectTransform),
					typeof(TextMeshProUGUI)
				}).GetComponent<TextMeshProUGUI>();
				RectTransform rectTransform = ((TMP_Text)hotkeyTooltip).rectTransform;
				((Component)rectTransform).transform.parent = ((Component)list[PlayerPatcher.playerDataLocal.reservedHotbarStartIndex]).transform;
				((Transform)rectTransform).localScale = Vector3.one;
				rectTransform.sizeDelta = new Vector2(((Graphic)list[0]).rectTransform.sizeDelta.x * 2f, 10f);
				rectTransform.pivot = Vector2.one / 2f;
				rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f);
				((TMP_Text)hotkeyTooltip).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font;
				((TMP_Text)hotkeyTooltip).fontSize = 7f;
				((TMP_Text)hotkeyTooltip).alignment = (TextAlignmentOptions)514;
				UpdateHotkeyTooltipText();
			}
			HUDManager.Instance.itemSlotIconFrames = list.ToArray();
			HUDManager.Instance.itemSlotIcons = list2.ToArray();
			Plugin.Log($"Finished adding {PlayerPatcher.reservedHotbarSize} Reserved Item slots in the inventory HUD.");
		}

		[HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")]
		[HarmonyPostfix]
		public static void UpdateHotkeyTextOnMenuClosed(QuickMenuManager __instance)
		{
			if (!__instance.isMenuOpen)
			{
				UpdateHotkeyTooltipText();
			}
		}

		private static void UpdateHotkeyTooltipText()
		{
			//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)
			//IL_0044: 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_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_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)
			int num = (StartOfRound.Instance.localPlayerUsingController ? 1 : 0);
			InputBinding val;
			string key;
			if (!InputUtilsCompat.Enabled)
			{
				val = Keybinds.FocusReservedHotbarAction.bindings[num];
				key = ((InputBinding)(ref val)).path;
			}
			else
			{
				val = Keybinds.FocusReservedHotbarAction.bindings[num];
				key = ((InputBinding)(ref val)).overridePath;
			}
			string displayName = ConfigSettings.GetDisplayName(key);
			TextMeshProUGUI obj = hotkeyTooltip;
			string text3;
			if (!ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				string text2 = (((TMP_Text)hotkeyTooltip).text = string.Format($"Hold: [{displayName}]"));
				text3 = text2;
			}
			else
			{
				text3 = string.Format($"Toggle: [{displayName}]");
			}
			((TMP_Text)obj).text = text3;
		}

		public static void UpdateHUD()
		{
			//IL_0024: 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)
			for (int i = 0; i < PlayerPatcher.reservedHotbarSize; i++)
			{
				int num = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + i;
				float num2 = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * iconWidth * (float)i;
				((Graphic)HUDManager.Instance.itemSlotIconFrames[num]).rectTransform.anchoredPosition = new Vector2(xPos, num2);
			}
		}
	}
	[HarmonyPatch]
	public static class MouseScrollPatcher
	{
		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPrefix]
		public static void CorrectReservedScrollDirectionNextItemSlot(ref bool forward)
		{
			if (Keybinds.scrollingReservedHotbar)
			{
				forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchItemSlotsServerRpc")]
		[HarmonyPrefix]
		public static void CorrectReservedScrollDirectionServerRpc(ref bool forward)
		{
			if (Keybinds.scrollingReservedHotbar)
			{
				forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")]
		[HarmonyPrefix]
		public static bool PreventInvertedScrollingReservedHotbar(CallbackContext context)
		{
			//IL_0068: 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)
			if (StartOfRound.Instance.localPlayerUsingController || SyncManager.numReservedItemSlots <= 0)
			{
				return true;
			}
			if (PlayerPatcher.playerDataLocal.currentItemSlotIsReserved)
			{
				if (!HUDPatcher.hasReservedItemSlotsAndEnabled)
				{
					return true;
				}
				if (HUDPatcher.reservedItemSlots.Count >= 2 && ((Graphic)HUDPatcher.reservedItemSlots[1]).rectTransform.anchoredPosition.y - ((Graphic)HUDPatcher.reservedItemSlots[0]).rectTransform.anchoredPosition.y <= 5f)
				{
					return true;
				}
				if (!Keybinds.scrollingReservedHotbar || SyncManager.numReservedItemSlots == 1 || (PlayerPatcher.playerDataLocal.GetNumHeldReservedItems() == 1 && (Object)(object)localPlayerController.ItemSlots[localPlayerController.currentItemSlot] != (Object)null))
				{
					return false;
				}
			}
			return true;
		}
	}
	[HarmonyPatch]
	public static class ReservedItemPatcher
	{
		public static int indexUnfocusedReservedHotbarLocal;

		public static int indexFocusedReservedHotbarLocal;

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static int reservedHotbarSize => SyncManager.numReservedItemSlots;

		private static GrabbableObject GetCurrentlyGrabbingObject(PlayerControllerB playerController)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			return (GrabbableObject)Traverse.Create((object)playerController).Field("currentlyGrabbingObject").GetValue();
		}

		private static void SetCurrentlyGrabbingObject(PlayerControllerB playerController, GrabbableObject grabbable)
		{
			Traverse.Create((object)playerController).Field("currentlyGrabbingObject").SetValue((object)grabbable);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPrefix]
		public static bool GrabReservedItemPrefix(PlayerControllerB __instance)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: 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)
			if ((!SyncManager.isSynced && !SyncManager.canUseModDisabledOnHost) || !HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return true;
			}
			PlayerPatcher.playerDataLocal.grabbingReservedItem = null;
			PlayerPatcher.playerDataLocal.previousHotbarIndex = -1;
			if (PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && !ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				return false;
			}
			if (__instance.twoHanded || __instance.sinkingValue > 0.73f)
			{
				return true;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			RaycastHit val2 = default(RaycastHit);
			if (Physics.Raycast(val, ref val2, __instance.grabDistance, PlayerPatcher.INTERACTABLE_OBJECT_MASK) && ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer != 8 && ((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp")
			{
				GrabbableObject component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>();
				if ((Object)(object)component != (Object)null && !__instance.inSpecialInteractAnimation && !component.isHeld && !component.isPocketed)
				{
					NetworkObject networkObject = ((NetworkBehaviour)component).NetworkObject;
					if ((Object)(object)networkObject != (Object)null && networkObject.IsSpawned && SyncManager.TryGetReservedItemInfo(((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>(), out var info))
					{
						Plugin.Log("Beginning grab on reserved item: " + info.itemName);
						PlayerPatcher.playerDataLocal.grabbingReservedItem = info;
						PlayerPatcher.playerDataLocal.previousHotbarIndex = __instance.currentItemSlot;
					}
				}
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPostfix]
		public static void GrabReservedItemPostfix(PlayerControllerB __instance)
		{
			if (PlayerPatcher.playerDataLocal.grabbingReservedItem != null)
			{
				SetSpecialGrabAnimationBool(__instance, setTrue: false);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPrefix]
		public static void GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if ((!SyncManager.isSynced && !SyncManager.canUseModDisabledOnHost) || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance))
			{
				return;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
			NetworkObject val = default(NetworkObject);
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening && grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
			{
				GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
				if (SyncManager.TryGetReservedItemInfo(component, out var info))
				{
					if (IsItemSlotEmpty(info, __instance))
					{
						Plugin.Log("OnGrabReservedItem for Player: " + ((Object)__instance).name + " Item: " + info.itemName);
						reservedPlayerData.grabbingReservedItem = info;
						reservedPlayerData.previousHotbarIndex = __instance.currentItemSlot;
						return;
					}
					Plugin.LogWarning("OnGrabReservedItem SlotFilled. Player: " + ((Object)__instance).name + " Item: " + info.itemName + " Slot: " + (reservedPlayerData.reservedHotbarStartIndex + info.reservedItemIndex));
				}
			}
			reservedPlayerData.grabbingReservedItem = null;
			reservedPlayerData.previousHotbarIndex = -1;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPostfix]
		public static void GrabReservedItemClientRpcPostfix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			//IL_00c7: 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_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)
			if ((!SyncManager.isSynced && SyncManager.canUseModDisabledOnHost) || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance))
			{
				return;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
			if (reservedPlayerData.grabbingReservedItem == null)
			{
				return;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening)
			{
				NetworkObject val = default(NetworkObject);
				if (grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
				{
					GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
					if (SyncManager.TryGetReservedItemInfo(component, out var info))
					{
						GrabbableObject val2 = __instance.ItemSlots[reservedPlayerData.previousHotbarIndex];
						SetSpecialGrabAnimationBool(__instance, (Object)(object)val2 != (Object)null, val2);
						Animator playerBodyAnimator = __instance.playerBodyAnimator;
						AnimatorStateInfo currentAnimatorStateInfo = __instance.playerBodyAnimator.GetCurrentAnimatorStateInfo(0);
						playerBodyAnimator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f);
						if ((Object)(object)val2 != (Object)null)
						{
							val2.EnableItemMeshes(true);
						}
						Traverse.Create((object)component).Field("previousPlayerHeldBy").SetValue((object)__instance);
						if ((Object)(object)__instance != (Object)(object)localPlayerController)
						{
							Plugin.Log("OnGrabReservedItem completed. Player: " + ((Object)__instance).name + " Item: " + info.itemName + " Switching to previous slot: " + reservedPlayerData.previousHotbarIndex);
							SwitchToItemSlot(__instance, reservedPlayerData.previousHotbarIndex);
							Animator playerBodyAnimator2 = __instance.playerBodyAnimator;
							currentAnimatorStateInfo = __instance.playerBodyAnimator.GetCurrentAnimatorStateInfo(0);
							playerBodyAnimator2.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f);
							reservedPlayerData.grabbingReservedItem = null;
							reservedPlayerData.previousHotbarIndex = -1;
						}
						else
						{
							int num = reservedPlayerData.reservedHotbarStartIndex + reservedPlayerData.grabbingReservedItem.reservedItemIndex;
							((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().SetBool("selectedSlot", false);
							((Component)HUDManager.Instance.itemSlotIconFrames[reservedPlayerData.previousHotbarIndex]).GetComponent<Animator>().SetBool("selectedSlot", true);
							((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().Play("PanelLines", 0, 1f);
							((Component)HUDManager.Instance.itemSlotIconFrames[reservedPlayerData.previousHotbarIndex]).GetComponent<Animator>().Play("PanelEnlarge", 0, 1f);
						}
						return;
					}
				}
				else if ((Object)(object)__instance == (Object)(object)localPlayerController)
				{
					Plugin.Log("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
					Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true);
				}
				else
				{
					Plugin.Log("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
				}
			}
			reservedPlayerData.grabbingReservedItem = null;
			reservedPlayerData.previousHotbarIndex = -1;
		}

		[HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")]
		[HarmonyPrefix]
		public static void OnReservedItemGrabbed(GrabbableObject __instance)
		{
			if (PlayerPatcher.playerDataLocal.grabbingReservedItem != null && !((Object)(object)__instance != (Object)(object)GetCurrentlyGrabbingObject(localPlayerController)))
			{
				((MonoBehaviour)localPlayerController).StartCoroutine(OnReservedItemGrabbedEndOfFrame());
			}
			IEnumerator OnReservedItemGrabbedEndOfFrame()
			{
				yield return (object)new WaitForEndOfFrame();
				SwitchToItemSlot(localPlayerController, PlayerPatcher.playerDataLocal.previousHotbarIndex);
				PlayerPatcher.playerDataLocal.grabbingReservedItem = null;
				PlayerPatcher.playerDataLocal.previousHotbarIndex = -1;
				__instance.PocketItem();
				Animator playerBodyAnimator = localPlayerController.playerBodyAnimator;
				AnimatorStateInfo currentAnimatorStateInfo = localPlayerController.playerBodyAnimator.GetCurrentAnimatorStateInfo(0);
				playerBodyAnimator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")]
		[HarmonyPrefix]
		public static void DebugSwitchToItemSlot(int slot, PlayerControllerB __instance)
		{
			if (!HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
			if (reservedPlayerData == null)
			{
				Plugin.LogError("PlayerData null for player: " + ((Object)__instance).name);
			}
			else
			{
				if (!reservedPlayerData.IsReservedItemSlot(slot))
				{
					return;
				}
				string text = "";
				reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
				if (slot < 0)
				{
					text = "Called SwitchToItemSlot on slot: " + slot;
				}
				else if (slot >= __instance.ItemSlots.Length)
				{
					text = "Called SwitchToItemSlot on slot: " + slot + " HotbarSize: " + __instance.ItemSlots.Length;
				}
				else
				{
					if (slot < HUDManager.Instance.itemSlotIconFrames.Length)
					{
						return;
					}
					text = "Called SwitchToItemSlot on slot: " + slot + " NumItemSlotsHUD: " + HUDManager.Instance.itemSlotIconFrames.Length;
				}
				text += "\n\n";
				text = text + reservedPlayerData.DumpData() + "\n\nReporting this error to Flip would be greatly appreciated!";
				Debug.LogError((object)text);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")]
		[HarmonyPostfix]
		public static void UpdateFocusReservedHotbar(int slot, PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				PlayerPatcher.allPlayerData[__instance].inReservedHotbarSlots = PlayerPatcher.allPlayerData[__instance].IsReservedItemSlot(__instance.currentItemSlot);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
		[HarmonyPostfix]
		public static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance)
		{
			if (reservedHotbarSize <= 0 || !HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
			ReservedItemInfo grabbingReservedItem = reservedPlayerData.grabbingReservedItem;
			if (grabbingReservedItem != null)
			{
				if (IsItemSlotEmpty(grabbingReservedItem, __instance))
				{
					__result = reservedPlayerData.reservedHotbarStartIndex + grabbingReservedItem.reservedItemIndex;
					return;
				}
				reservedPlayerData.grabbingReservedItem = null;
				reservedPlayerData.previousHotbarIndex = -1;
			}
			if (!reservedPlayerData.IsReservedItemSlot(__result))
			{
				return;
			}
			__result = -1;
			for (int i = 0; i < __instance.ItemSlots.Length; i++)
			{
				if (!reservedPlayerData.IsReservedItemSlot(i) && (Object)(object)__instance.ItemSlots[i] == (Object)null)
				{
					__result = i;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPostfix]
		public static void OnNextItemSlot(ref int __result, bool forward, PlayerControllerB __instance)
		{
			if (reservedHotbarSize <= 0 || !HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance];
			bool flag = reservedPlayerData.IsReservedItemSlot(__result);
			if (flag == reservedPlayerData.inReservedHotbarSlots && (!flag || (Object)(object)__instance.ItemSlots[__result] != (Object)null))
			{
				return;
			}
			int num = (forward ? 1 : (-1));
			__result = __instance.currentItemSlot + num;
			__result = ((__result < 0) ? (__instance.ItemSlots.Length - 1) : ((__result < __instance.ItemSlots.Length) ? __result : 0));
			bool flag2 = reservedPlayerData.IsReservedItemSlot(__result);
			if (!reservedPlayerData.inReservedHotbarSlots)
			{
				if (flag2)
				{
					__result = (forward ? ((reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize) % __instance.ItemSlots.Length) : (reservedPlayerData.reservedHotbarStartIndex - 1));
				}
				return;
			}
			__result = (flag2 ? __result : (forward ? reservedPlayerData.reservedHotbarStartIndex : (reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize - 1)));
			int numHeldReservedItems = reservedPlayerData.GetNumHeldReservedItems();
			while (numHeldReservedItems > 0 && __result != reservedPlayerData.currentItemSlot && (Object)(object)__instance.ItemSlots[__result] == (Object)null)
			{
				__result += num;
				__result = ((!reservedPlayerData.IsReservedItemSlot(__result)) ? (forward ? reservedPlayerData.reservedHotbarStartIndex : (reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize - 1)) : __result);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPrefix]
		public static void RefocusReservedHotbarAfterAnimation(PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled && !((Object)(object)__instance != (Object)(object)localPlayerController) && !ConfigSettings.toggleFocusReservedHotbar.Value && Keybinds.holdingModifierKey != PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && CanSwapToReservedHotbarSlot())
			{
				FocusReservedHotbarSlots(Keybinds.holdingModifierKey);
			}
		}

		public static bool CanSwapToReservedHotbarSlot()
		{
			if (!HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return false;
			}
			bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue();
			return !(PlayerPatcher.playerDataLocal.grabbingReservedItem != null || localPlayerController.isGrabbingObjectAnimation || localPlayerController.quickMenuManager.isMenuOpen || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem && !localPlayerController.jetpackControls && !localPlayerController.disablingJetpackControls && !localPlayerController.inTerminalMenu && !localPlayerController.isPlayerDead && !(GetTimeSinceSwitchingSlots(localPlayerController) < 0.3f);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "UpdateSpecialAnimationValue")]
		[HarmonyPostfix]
		public static void OnSpecialAnimationUpdate(bool specialAnimation, PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled && !((Object)(object)__instance != (Object)(object)localPlayerController) && !specialAnimation && !ConfigSettings.toggleFocusReservedHotbar.Value && PlayerPatcher.playerDataLocal.currentItemSlotIsReserved != Keybinds.holdingModifierKey)
			{
				FocusReservedHotbarSlots(Keybinds.holdingModifierKey);
			}
		}

		public static void FocusReservedHotbarSlots(bool active)
		{
			if (!HUDPatcher.hasReservedItemSlotsAndEnabled || (reservedHotbarSize <= 0 && active) || PlayerPatcher.playerDataLocal.currentItemSlotIsReserved == active)
			{
				return;
			}
			int num = localPlayerController.currentItemSlot;
			bool flag = active;
			if (flag && (num < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex || num >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize))
			{
				Plugin.Log("Focusing reserved hotbar slots.");
				if (indexFocusedReservedHotbarLocal == -1)
				{
					indexFocusedReservedHotbarLocal = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex;
				}
				indexUnfocusedReservedHotbarLocal = num;
				num = Mathf.Clamp(indexFocusedReservedHotbarLocal, PlayerPatcher.playerDataLocal.reservedHotbarStartIndex, PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize - 1);
				if ((Object)(object)localPlayerController.ItemSlots[num] == (Object)null)
				{
					for (int i = 0; i < reservedHotbarSize; i++)
					{
						int num2 = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + i;
						if ((Object)(object)localPlayerController.ItemSlots[num2] != (Object)null)
						{
							num = num2;
							break;
						}
					}
				}
			}
			else if (!flag && num >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex && num < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize)
			{
				Plugin.Log("Unfocusing reserved hotbar slots.");
				indexFocusedReservedHotbarLocal = num;
				if (indexUnfocusedReservedHotbarLocal >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex && indexUnfocusedReservedHotbarLocal < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize)
				{
					indexUnfocusedReservedHotbarLocal = 0;
				}
				num = indexUnfocusedReservedHotbarLocal;
			}
			SyncManager.SwapHotbarSlot(num);
		}

		internal static bool IsItemSlotEmpty(string itemName, PlayerControllerB playerController)
		{
			if (!SyncManager.TryGetReservedItemInfo(itemName, out var info))
			{
				return false;
			}
			return IsItemSlotEmpty(info, playerController);
		}

		internal static bool IsItemSlotEmpty(ReservedItemInfo itemInfo, PlayerControllerB playerController)
		{
			playerController = (((Object)(object)playerController == (Object)null) ? localPlayerController : playerController);
			if (reservedHotbarSize == 0)
			{
				return false;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[playerController];
			int num = reservedPlayerData.reservedHotbarStartIndex + itemInfo.reservedItemIndex;
			return num >= reservedPlayerData.reservedHotbarStartIndex && num < reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize && (Object)(object)playerController.ItemSlots[num] == (Object)null;
		}

		public static bool TryGetHeldReservedObject(string itemName, PlayerControllerB playerController, ref GrabbableObject obj)
		{
			playerController = (((Object)(object)playerController == (Object)null) ? localPlayerController : playerController);
			if ((Object)(object)playerController == (Object)null || reservedHotbarSize == 0)
			{
				return false;
			}
			if (!SyncManager.TryGetReservedItemInfo(itemName, out var info))
			{
				return false;
			}
			ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[playerController];
			int num = reservedPlayerData.reservedHotbarStartIndex + info.reservedItemIndex;
			obj = playerController.ItemSlots[num];
			return (Object)(object)obj != (Object)null;
		}

		public static float GetTimeSinceSwitchingSlots(PlayerControllerB playerController)
		{
			return (float)Traverse.Create((object)playerController).Field("timeSinceSwitchingSlots").GetValue();
		}

		public static void SetTimeSinceSwitchingSlots(PlayerControllerB playerController, float value)
		{
			Traverse.Create((object)playerController).Field("timeSinceSwitchingSlots").SetValue((object)value);
		}

		public static void SetSpecialGrabAnimationBool(PlayerControllerB playerController, bool setTrue, GrabbableObject currentItem = null)
		{
			MethodInfo method = ((object)playerController).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(playerController, new object[2] { setTrue, currentItem });
		}

		public static void SwitchToItemSlot(PlayerControllerB playerController, int slot, GrabbableObject fillSlotWithItem = null)
		{
			MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(playerController, new object[2] { slot, fillSlotWithItem });
			SetTimeSinceSwitchingSlots(playerController, 0f);
		}
	}
	[HarmonyPatch]
	public static class PlayerPatcher
	{
		public static PlayerControllerB localPlayerController;

		public static int vanillaHotbarSize = -1;

		public static int hotbarSizeBeforeSync = -1;

		internal static Dictionary<PlayerControllerB, ReservedPlayerData> allPlayerData = new Dictionary<PlayerControllerB, ReservedPlayerData>();

		public static bool spawned = false;

		public static bool isSynced = false;

		public static int INTERACTABLE_OBJECT_MASK { get; private set; }

		public static int reservedHotbarSize => SyncManager.numReservedItemSlots;

		internal static ReservedPlayerData playerDataLocal => (allPlayerData != null && (Object)(object)localPlayerController != (Object)null && allPlayerData.ContainsKey(localPlayerController)) ? allPlayerData[localPlayerController] : null;

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void InitSession(StartOfRound __instance)
		{
			localPlayerController = null;
			vanillaHotbarSize = -1;
			ReservedItemPatcher.indexUnfocusedReservedHotbarLocal = 0;
			ReservedItemPatcher.indexFocusedReservedHotbarLocal = -1;
			Keybinds.holdingModifierKey = false;
			allPlayerData.Clear();
			isSynced = false;
			spawned = false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
		[HarmonyPostfix]
		public static void InitializePlayerController(PlayerControllerB __instance)
		{
			if (vanillaHotbarSize == -1)
			{
				vanillaHotbarSize = __instance.ItemSlots.Length;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		public static void InitializePlayerControllerLate(PlayerControllerB __instance)
		{
			allPlayerData.Add(__instance, new ReservedPlayerData
			{
				playerController = __instance,
				hotbarSize = __instance.ItemSlots.Length,
				reservedHotbarStartIndex = __instance.ItemSlots.Length
			});
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			localPlayerController = __instance;
			INTERACTABLE_OBJECT_MASK = (int)Traverse.Create((object)__instance).Field("interactableObjectsMask").GetValue();
			((MonoBehaviour)__instance).StartCoroutine(UpdateHotbarSlotsAfterFirstSpawnAnimation());
		}

		private static IEnumerator UpdateHotbarSlotsAfterFirstSpawnAnimation()
		{
			yield return (object)new WaitForSeconds(3f);
			spawned = true;
			hotbarSizeBeforeSync = localPlayerController.ItemSlots.Length;
			if (!isSynced && (SyncManager.isSynced || SyncManager.canUseModDisabledOnHost))
			{
				OnSyncedWithServer();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPostfix]
		public static void OnUpdate(PlayerControllerB __instance)
		{
			if (!spawned)
			{
				return;
			}
			if (SyncManager.isSynced && !isSynced)
			{
				OnSyncedWithServer();
			}
			ReservedPlayerData reservedPlayerData = allPlayerData[__instance];
			if ((!isSynced && (!SyncManager.canUseModDisabledOnHost || (Object)(object)__instance != (Object)(object)localPlayerController)) || reservedHotbarSize <= 0 || reservedPlayerData.hotbarSize == __instance.ItemSlots.Length)
			{
				return;
			}
			Plugin.Log("On update inventory size for player: " + ((Object)__instance).name + " - Old hotbar size: " + reservedPlayerData.hotbarSize + " - New hotbar size: " + __instance.ItemSlots.Length);
			reservedPlayerData.hotbarSize = __instance.ItemSlots.Length;
			int num = -1;
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				for (int i = 0; i < HUDManager.Instance.itemSlotIconFrames.Length; i++)
				{
					if (((Object)HUDManager.Instance.itemSlotIconFrames[i]).name.ToLower().StartsWith("reserveditemslot"))
					{
						num = i;
						Plugin.Log("OnUpdateInventorySize A for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
						break;
					}
				}
			}
			if (num == -1)
			{
				for (int j = 0; j < __instance.ItemSlots.Length; j++)
				{
					GrabbableObject item = __instance.ItemSlots[j];
					if (SyncManager.TryGetReservedItemInfo(item, out var info))
					{
						num = j - info.reservedItemIndex;
						Plugin.Log("OnUpdateInventorySize B for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
						break;
					}
				}
				if (num == __instance.ItemSlots.Length)
				{
					num = -1;
				}
			}
			if (num == -1)
			{
				num = reservedPlayerData.reservedHotbarStartIndex;
				Plugin.Log("OnUpdateInventorySize C for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
			}
			if (num == -1)
			{
				num = vanillaHotbarSize;
				Plugin.Log("OnUpdateInventorySize D for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
			}
			reservedPlayerData.reservedHotbarStartIndex = num;
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				HUDPatcher.UpdateHUD();
			}
		}

		private static void OnSyncedWithServer()
		{
			Plugin.Log("Finalizing sync with server.");
			isSynced = SyncManager.isSynced;
			int num = hotbarSizeBeforeSync + reservedHotbarSize;
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				allPlayerData[val].reservedHotbarStartIndex = hotbarSizeBeforeSync;
				if (num != val.ItemSlots.Length)
				{
					val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[num];
				}
				allPlayerData[val].hotbarSize = val.ItemSlots.Length;
			}
			if (HUDPatcher.reservedItemSlots != null && HUDPatcher.reservedItemSlots.Count == SyncManager.numReservedItemSlots && playerDataLocal.reservedHotbarStartIndex < HUDManager.Instance.itemSlotIconFrames.Length && (Object)(object)HUDPatcher.reservedItemSlots[0] == (Object)(object)HUDManager.Instance.itemSlotIconFrames[playerDataLocal.reservedHotbarStartIndex])
			{
				return;
			}
			if (HUDPatcher.reservedItemSlots != null && HUDPatcher.reservedItemSlots.Count > 0)
			{
				List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames);
				List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons);
				for (int j = 0; j < HUDManager.Instance.itemSlotIconFrames.Length; j++)
				{
					Image val2 = HUDManager.Instance.itemSlotIconFrames[j];
					Image item = HUDManager.Instance.itemSlotIcons[j];
					if (((Object)val2).name.Contains("Reserved"))
					{
						list.Remove(val2);
						list2.Remove(item);
					}
				}
				HUDManager.Instance.itemSlotIconFrames = list.ToArray();
				HUDManager.Instance.itemSlotIcons = list2.ToArray();
			}
			HUDPatcher.AddNewHotbarSlotsHud();
		}
	}
}
namespace ReservedItemSlotCore.Compatibility
{
	public class AdvancedCompanyPatcher
	{
		public static bool Enabled => Plugin.IsModLoaded("com.potatoepet.AdvancedCompany");
	}
}

plugins/Dependencies/Evaisa-LethalLib-0.11.2/LethalLib.dll

Decompiled 10 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.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using LethalLib.Extras;
using LethalLib.Modules;
using LethalLib.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

[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: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("LethalLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Mod for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+77bc9a8c23df6420d447f3a5a6149e92babf4589")]
[assembly: AssemblyProduct("LethalLib")]
[assembly: AssemblyTitle("LethalLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
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 LethalLib
{
	[BepInPlugin("evaisa.lethallib", "LethalLib", "0.11.2")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.11.2";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		private void Awake()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			config = ((BaseUnityPlugin)this).Config;
			logger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!");
			MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lethallib"));
			new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook));
			Enemies.Init();
			Items.Init();
			Unlockables.Init();
			MapObjects.Init();
			Dungeon.Init();
			Weathers.Init();
			Player.Init();
			Utilities.Init();
			NetworkPrefabs.Init();
		}

		private void IlHook(ILContext il)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public))
			});
			val.RemoveRange(2);
			val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL);
		}

		private static string GetLineOrIL(StackFrame instance)
		{
			int fileLineNumber = instance.GetFileLineNumber();
			if (fileLineNumber == -1 || fileLineNumber == 0)
			{
				return "IL_" + instance.GetILOffset().ToString("X4");
			}
			return fileLineNumber.ToString();
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalLib";

		public const string PLUGIN_NAME = "LethalLib";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace LethalLib.Modules
{
	public class ContentLoader
	{
		public class CustomContent
		{
			private string id = "";

			public string ID => id;

			public CustomContent(string id)
			{
				this.id = id;
			}
		}

		public class CustomItem : CustomContent
		{
			public Action<Item> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal Item item;

			public Item Item => item;

			public CustomItem(string id, string contentPath, Action<Item> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
			}
		}

		public class ShopItem : CustomItem
		{
			public int initPrice = 0;

			public string buyNode1Path = null;

			public string buyNode2Path = null;

			public string itemInfoPath = null;

			public void RemoveFromShop()
			{
				Items.RemoveShopItem(base.Item);
			}

			public void SetPrice(int price)
			{
				Items.UpdateShopItemPrice(base.Item, price);
			}

			public ShopItem(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
			}
		}

		public class ScrapItem : CustomItem
		{
			private int rarity = 0;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides = null;

			public int Rarity => rarity;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Items.RemoveScrapFromLevels(base.Item, levelFlags);
			}

			public ScrapItem(string id, string contentPath, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				this.rarity = rarity;
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
			}
		}

		public class Unlockable : CustomContent
		{
			public Action<UnlockableItem> registryCallback = delegate
			{
			};

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice = 0;

			public string buyNode1Path = null;

			public string buyNode2Path = null;

			public string itemInfoPath = null;

			public StoreType storeType = StoreType.None;

			public UnlockableItem UnlockableItem => unlockable;

			public void RemoveFromShop()
			{
				Unlockables.DisableUnlockable(UnlockableItem);
			}

			public void SetPrice(int price)
			{
				Unlockables.UpdateUnlockablePrice(UnlockableItem, price);
			}

			public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
				this.storeType = storeType;
			}
		}

		public class CustomEnemy : CustomContent
		{
			public Action<EnemyType> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal EnemyType enemy;

			public string infoNodePath = null;

			public string infoKeywordPath = null;

			public int rarity = 0;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides = null;

			public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1);

			public EnemyType Enemy => enemy;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Enemies.RemoveEnemyFromLevels(Enemy, levelFlags);
			}

			public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				this.infoNodePath = infoNodePath;
				this.infoKeywordPath = infoKeywordPath;
				this.rarity = rarity;
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnType = spawnType;
			}
		}

		public class MapHazard : CustomContent
		{
			public Action<SpawnableMapObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableMapObjectDef hazard;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides = null;

			public SpawnableMapObjectDef Hazard => hazard;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides);
			}

			public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public class OutsideObject : CustomContent
		{
			public Action<SpawnableOutsideObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableOutsideObjectDef mapObject;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides = null;

			public SpawnableOutsideObjectDef MapObject => mapObject;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides);
			}

			public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		private Dictionary<string, CustomContent> loadedContent = new Dictionary<string, CustomContent>();

		public PluginInfo modInfo;

		private AssetBundle modBundle;

		public Action<CustomContent, GameObject> prefabCallback = delegate
		{
		};

		public Dictionary<string, CustomContent> LoadedContent => loadedContent;

		public string modName => modInfo.Metadata.Name;

		public string modVersion => modInfo.Metadata.Version.ToString();

		public string modGUID => modInfo.Metadata.GUID;

		public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			this.modInfo = modInfo;
			this.modBundle = modBundle;
			if (prefabCallback != null)
			{
				this.prefabCallback = prefabCallback;
			}
		}

		public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			return new ContentLoader(modInfo, modBundle, prefabCallback);
		}

		public void Register(CustomContent content)
		{
			if (loadedContent.ContainsKey(content.ID))
			{
				Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!"));
				return;
			}
			if (content is CustomItem customItem)
			{
				Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
				Utilities.FixMixerGroups(val.spawnPrefab);
				prefabCallback(content, val.spawnPrefab);
				customItem.registryCallback(val);
				if (content is ShopItem shopItem)
				{
					TerminalNode buyNode = null;
					TerminalNode buyNode2 = null;
					TerminalNode itemInfo = null;
					if (shopItem.buyNode1Path != null)
					{
						buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path);
					}
					if (shopItem.buyNode2Path != null)
					{
						buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path);
					}
					if (shopItem.itemInfoPath != null)
					{
						itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath);
					}
					Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice);
				}
				else if (content is ScrapItem scrapItem)
				{
					Items.RegisterScrap(val, scrapItem.Rarity, scrapItem.LevelTypes, scrapItem.levelOverrides);
				}
				else
				{
					Items.RegisterItem(val);
				}
			}
			else if (content is Unlockable unlockable)
			{
				UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath);
				if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null)
				{
					NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject);
					prefabCallback(content, unlockableItemDef.unlockable.prefabObject);
					Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject);
				}
				unlockable.unlockable = unlockableItemDef.unlockable;
				unlockable.registryCallback(unlockableItemDef.unlockable);
				TerminalNode buyNode3 = null;
				TerminalNode buyNode4 = null;
				TerminalNode itemInfo2 = null;
				if (unlockable.buyNode1Path != null)
				{
					buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path);
				}
				if (unlockable.buyNode2Path != null)
				{
					buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path);
				}
				if (unlockable.itemInfoPath != null)
				{
					itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath);
				}
				Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice);
			}
			else if (content is CustomEnemy customEnemy)
			{
				EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath);
				NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab);
				Utilities.FixMixerGroups(val2.enemyPrefab);
				customEnemy.enemy = val2;
				prefabCallback(content, val2.enemyPrefab);
				customEnemy.registryCallback(val2);
				TerminalNode infoNode = null;
				TerminalKeyword infoKeyword = null;
				if (customEnemy.infoNodePath != null)
				{
					infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath);
				}
				if (customEnemy.infoKeywordPath != null)
				{
					infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath);
				}
				if (customEnemy.spawnType == (Enemies.SpawnType)(-1))
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
				else
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
			}
			else if (content is MapHazard mapHazard)
			{
				SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				mapHazard.registryCallback(spawnableMapObjectDef);
				MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction);
			}
			else if (content is OutsideObject outsideObject)
			{
				SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				outsideObject.registryCallback(spawnableOutsideObjectDef);
				MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction);
			}
			loadedContent.Add(content.ID, content);
		}

		public void RegisterAll(CustomContent[] content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!");
			foreach (CustomContent content2 in content)
			{
				Register(content2);
			}
		}

		public void RegisterAll(List<CustomContent> content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!");
			foreach (CustomContent item in content)
			{
				Register(item);
			}
		}
	}
	public class Dungeon
	{
		public class CustomDungeonArchetype
		{
			public DungeonArchetype archeType;

			public Levels.LevelTypes LevelTypes;

			public int lineIndex = -1;
		}

		public class CustomGraphLine
		{
			public GraphLine graphLine;

			public Levels.LevelTypes LevelTypes;
		}

		public class CustomDungeon
		{
			public int rarity;

			public DungeonFlow dungeonFlow;

			public Levels.LevelTypes LevelTypes;

			public string[] levelOverrides;

			public int dungeonIndex = -1;

			public AudioClip firstTimeDungeonAudio;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor;

			public static hook_Start <1>__RoundManager_Start;
		}

		public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>();

		public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>();

		public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>();

		public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>();

		public static List<CustomDungeon> customDungeons = new List<CustomDungeon>();

		public static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			//IL_0032: 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_003d: Expected O, but got Unknown
			object obj = <>O.<0>__RoundManager_GenerateNewFloor;
			if (obj == null)
			{
				hook_GenerateNewFloor val = RoundManager_GenerateNewFloor;
				<>O.<0>__RoundManager_GenerateNewFloor = val;
				obj = (object)val;
			}
			RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj;
			object obj2 = <>O.<1>__RoundManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = RoundManager_Start;
				<>O.<1>__RoundManager_Start = val2;
				obj2 = (object)val2;
			}
			RoundManager.Start += (hook_Start)obj2;
		}

		private static void RoundManager_Start(orig_Start orig, RoundManager self)
		{
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: 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_0291: Expected O, but got Unknown
			foreach (CustomDungeon customDungeon in customDungeons)
			{
				if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow))
				{
					continue;
				}
				List<DungeonFlow> list = self.dungeonFlowTypes.ToList();
				list.Add(customDungeon.dungeonFlow);
				self.dungeonFlowTypes = list.ToArray();
				int dungeonIndex = self.dungeonFlowTypes.Length - 1;
				customDungeon.dungeonIndex = dungeonIndex;
				List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList();
				if (list2.Count != self.dungeonFlowTypes.Length - 1)
				{
					while (list2.Count < self.dungeonFlowTypes.Length - 1)
					{
						list2.Add(null);
					}
				}
				list2.Add(customDungeon.firstTimeDungeonAudio);
				self.firstTimeDungeonAudios = list2.ToArray();
			}
			StartOfRound instance = StartOfRound.Instance;
			foreach (CustomDungeon dungeon in customDungeons)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)
					{
						Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
						if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex))
						{
							List<IntWithRarity> list3 = val.dungeonFlowTypes.ToList();
							list3.Add(new IntWithRarity
							{
								id = dungeon.dungeonIndex,
								rarity = dungeon.rarity
							});
							val.dungeonFlowTypes = list3.ToArray();
						}
					}
				}
			}
			orig.Invoke(self);
		}

		private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self)
		{
			string name = ((Object)self.currentLevel).name;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), name))
			{
				Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name);
				int index = 0;
				self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line)
				{
					foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes)
					{
						if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index))
						{
							line.DungeonArchetypes.Add(customDungeonArchetype.archeType);
							Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name));
						}
					}
					foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
					{
						string name2 = ((Object)dungeonArchetype).name;
						if (extraTileSets.ContainsKey(name2))
						{
							TileSet val4 = extraTileSets[name2];
							if (!dungeonArchetype.TileSets.Contains(val4))
							{
								dungeonArchetype.TileSets.Add(val4);
								Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name));
							}
						}
						foreach (TileSet tileSet in dungeonArchetype.TileSets)
						{
							string name3 = ((Object)tileSet).name;
							if (extraRooms.ContainsKey(name3))
							{
								GameObjectChance item = extraRooms[name3];
								if (!tileSet.TileWeights.Weights.Contains(item))
								{
									tileSet.TileWeights.Weights.Add(item);
								}
							}
						}
					}
					index++;
				});
				foreach (CustomGraphLine customGraphLine in customGraphLines)
				{
					if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine))
					{
						self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine);
					}
				}
			}
			orig.Invoke(self);
			NetworkManager val = Object.FindObjectOfType<NetworkManager>();
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			RandomMapObject[] array2 = array;
			foreach (RandomMapObject val2 in array2)
			{
				for (int j = 0; j < val2.spawnablePrefabs.Count; j++)
				{
					string prefabName = ((Object)val2.spawnablePrefabs[j]).name;
					NetworkPrefab val3 = ((IEnumerable<NetworkPrefab>)val.NetworkConfig.Prefabs.m_Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName));
					if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j])
					{
						val2.spawnablePrefabs[j] = val3.Prefab;
					}
					else if (val3 == null)
					{
						Plugin.logger.LogError((object)("DungeonGeneration - Could not find network prefab (" + prefabName + ")! Make sure your assigned prefab is registered with the network manager, or named identically to the vanilla prefab you are referencing."));
					}
				}
			}
		}

		public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1)
		{
			CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype();
			customDungeonArchetype.archeType = archetype;
			customDungeonArchetype.LevelTypes = levelFlags;
			customDungeonArchetype.lineIndex = lineIndex;
			customDungeonArchetypes.Add(customDungeonArchetype);
		}

		public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags)
		{
			CustomGraphLine customGraphLine = new CustomGraphLine();
			customGraphLine.graphLine = line;
			customGraphLine.LevelTypes = levelFlags;
			customGraphLines.Add(customGraphLine);
		}

		public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags)
		{
			AddLine(line.graphLine, levelFlags);
		}

		public static void AddTileSet(TileSet set, string archetypeName)
		{
			extraTileSets.Add(archetypeName, set);
		}

		public static void AddRoom(GameObjectChance room, string tileSetName)
		{
			extraRooms.Add(tileSetName, room);
		}

		public static void AddRoom(GameObjectChanceDef room, string tileSetName)
		{
			AddRoom(room.gameObjectChance, tileSetName);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio
			});
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio,
				levelOverrides = levelOverrides
			});
		}
	}
	public class Enemies
	{
		public struct EnemyAssetInfo
		{
			public EnemyType EnemyAsset;

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public string[] spawnLevelOverrides;

			public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null)
			{
				this.enemy = enemy;
				this.rarity = rarity;
				this.spawnLevels = spawnLevels;
				this.spawnType = spawnType;
				this.spawnLevelOverrides = spawnLevelOverrides;
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__RegisterLevelEnemies;

			public static hook_Start <1>__Terminal_Start;
		}

		public static Terminal terminal;

		public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>();

		public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>();

		public static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			//IL_0032: 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_003d: Expected O, but got Unknown
			object obj = <>O.<0>__RegisterLevelEnemies;
			if (obj == null)
			{
				hook_Awake val = RegisterLevelEnemies;
				<>O.<0>__RegisterLevelEnemies = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
		}

		private static void Terminal_Start(orig_Start orig, Terminal self)
		{
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Expected O, but got Unknown
			terminal = self;
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<string> list = new List<string>();
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (list.Contains(spawnableEnemy.enemy.enemyName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				if ((Object)(object)spawnableEnemy.terminalNode == (Object)null)
				{
					spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>();
					spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n";
					spawnableEnemy.terminalNode.clearPreviousText = true;
					spawnableEnemy.terminalNode.maxCharactersToType = 35;
					spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName;
				}
				if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val));
				keyword2.defaultVerb = val;
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word))
				{
					list2.Add(keyword2);
					self.terminalNodes.allKeywords = list2.ToArray();
				}
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word))
				{
					list3.Add(new CompatibleNoun
					{
						noun = keyword2,
						result = spawnableEnemy.terminalNode
					});
				}
				val.compatibleNouns = list3.ToArray();
				spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count;
				self.enemyFiles.Add(spawnableEnemy.terminalNode);
				spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID;
				EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo);
				enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy;
				enemyAssetInfo.keyword = keyword2;
				EnemyAssetInfo item = enemyAssetInfo;
				enemyAssetInfos.Add(item);
			}
			orig.Invoke(self);
		}

		private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self)
		{
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			orig.Invoke(self);
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = spawnableEnemy.spawnLevels.HasFlag(Levels.LevelTypes.All) || (spawnableEnemy.spawnLevelOverrides != null && spawnableEnemy.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !spawnableEnemy.spawnLevels.HasFlag(levelTypes))
					{
						continue;
					}
					SpawnableEnemyWithRarity item2 = new SpawnableEnemyWithRarity
					{
						enemyType = spawnableEnemy.enemy,
						rarity = spawnableEnemy.rarity
					};
					switch (spawnableEnemy.spawnType)
					{
					case SpawnType.Default:
						if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.Enemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]"));
						}
						break;
					case SpawnType.Daytime:
						if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.DaytimeEnemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]"));
						}
						break;
					case SpawnType.Outside:
						if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.OutsideEnemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]"));
						}
						break;
					}
				}
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default), spawnLevelOverrides);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					List<SpawnableEnemyWithRarity> enemies = val.Enemies;
					List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies;
					List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies;
					enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType);
				}
			}
		}
	}
	public class Items
	{
		public struct ItemSaveOrderData
		{
			public int itemId;

			public string itemName;

			public string assetName;
		}

		public struct BuyableItemAssetInfo
		{
			public Item itemAsset;

			public TerminalKeyword keyword;
		}

		public class ScrapItem
		{
			public Item item;

			public Item origItem;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public string modName;

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject val2 = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)val2).name = "ScanNode";
						val2.transform.localPosition = new Vector3(0f, 0f, 0f);
						ScanNodeProperties component = val2.GetComponent<ScanNodeProperties>();
						component.headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				this.rarity = rarity;
				this.spawnLevels = spawnLevels;
				this.spawnLevelOverrides = spawnLevelOverrides;
			}
		}

		public class PlainItem
		{
			public Item item;

			public string modName;

			public PlainItem(Item item)
			{
				this.item = item;
			}
		}

		public class ShopItem
		{
			public Item item;

			public Item origItem;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public bool wasRemoved = false;

			public int price;

			public string modName;

			public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0)
			{
				origItem = item;
				if (item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = false;
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() != (Object)null)
					{
						Object.Destroy((Object)(object)((Component)val.GetComponentInChildren<ScanNodeProperties>()).gameObject);
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				this.price = price;
				if ((Object)(object)buyNode1 != (Object)null)
				{
					this.buyNode1 = buyNode1;
				}
				if ((Object)(object)buyNode2 != (Object)null)
				{
					this.buyNode2 = buyNode2;
				}
				if ((Object)(object)itemInfo != (Object)null)
				{
					this.itemInfo = itemInfo;
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Awake <1>__Terminal_Awake;

			public static hook_TextPostProcess <2>__Terminal_TextPostProcess;
		}

		public static ConfigEntry<bool> useSavedataFix;

		public static GameObject scanNodePrefab;

		public static List<Item> LethalLibItemList = new List<Item>();

		public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>();

		public static Terminal terminal;

		public static List<ScrapItem> scrapItems = new List<ScrapItem>();

		public static List<ShopItem> shopItems = new List<ShopItem>();

		public static List<PlainItem> plainItems = new List<PlainItem>();

		public static void Init()
		{
			//IL_0044: 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_004f: Expected O, but got Unknown
			//IL_0065: 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_0070: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally.");
			scanNodePrefab = Plugin.MainAssets.LoadAsset<GameObject>("Assets/Custom/ItemScanNode.prefab");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__Terminal_Awake;
			if (obj2 == null)
			{
				hook_Awake val2 = Terminal_Awake;
				<>O.<1>__Terminal_Awake = val2;
				obj2 = (object)val2;
			}
			Terminal.Awake += (hook_Awake)obj2;
			object obj3 = <>O.<2>__Terminal_TextPostProcess;
			if (obj3 == null)
			{
				hook_TextPostProcess val3 = Terminal_TextPostProcess;
				<>O.<2>__Terminal_TextPostProcess = val3;
				obj3 = (object)val3;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj3;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			List<Item> list = self.buyableItemsList.ToList();
			List<Item> list2 = self.buyableItemsList.ToList();
			list2.RemoveAll((Item x) => shopItems.FirstOrDefault((ShopItem item) => (Object)(object)item.origItem == (Object)(object)x || (Object)(object)item.item == (Object)(object)x)?.wasRemoved ?? false);
			self.buyableItemsList = list2.ToArray();
			string result = orig.Invoke(self, modifiedDisplayText, node);
			self.buyableItemsList = list.ToArray();
			return result;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost)
			{
				Plugin.logger.LogInfo((object)"Fixing Item savedata!!");
				List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>();
				StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item)
				{
					itemList.Add(new ItemSaveOrderData
					{
						itemId = item.itemId,
						itemName = item.itemName,
						assetName = ((Object)item).name
					});
				});
				if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName))
				{
					itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName);
				}
				List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
				List<Item> list = new List<Item>();
				foreach (ItemSaveOrderData item2 in itemList)
				{
					Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name));
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
					else
					{
						list.Add(ScriptableObject.CreateInstance<Item>());
					}
				}
				foreach (Item item3 in itemsList)
				{
					if (!list.Contains(item3))
					{
						list.Add(item3);
					}
				}
				StartOfRound.Instance.allItemsList.itemsList = list;
				ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName);
			}
			orig.Invoke(self);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_0121: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0890: Unknown result type (might be due to invalid IL or missing references)
			//IL_0895: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d3: Expected O, but got Unknown
			//IL_08d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_08da: Unknown result type (might be due to invalid IL or missing references)
			//IL_090f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0917: Expected O, but got Unknown
			//IL_0997: Unknown result type (might be due to invalid IL or missing references)
			//IL_099c: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b1: Expected O, but got Unknown
			//IL_0a56: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a5b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a63: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a70: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			foreach (ScrapItem scrapItem in scrapItems)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = scrapItem.spawnLevels.HasFlag(Levels.LevelTypes.All) || (scrapItem.spawnLevelOverrides != null && scrapItem.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (flag || scrapItem.spawnLevels.HasFlag(levelTypes))
					{
						SpawnableItemWithRarity item3 = new SpawnableItemWithRarity
						{
							spawnableItem = scrapItem.item,
							rarity = scrapItem.rarity
						};
						if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item))
						{
							val.spawnableScrap.Add(item3);
						}
					}
				}
			}
			foreach (ScrapItem scrapItem2 in scrapItems)
			{
				if (!instance.allItemsList.itemsList.Contains(scrapItem2.item))
				{
					if (scrapItem2.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered scrap item: " + scrapItem2.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered scrap item: " + scrapItem2.item.itemName));
					}
					LethalLibItemList.Add(scrapItem2.item);
					instance.allItemsList.itemsList.Add(scrapItem2.item);
				}
			}
			foreach (ShopItem shopItem in shopItems)
			{
				if (!instance.allItemsList.itemsList.Contains(shopItem.item))
				{
					if (shopItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(shopItem.modName + " registered shop item: " + shopItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered shop item: " + shopItem.item.itemName));
					}
					LethalLibItemList.Add(shopItem.item);
					instance.allItemsList.itemsList.Add(shopItem.item);
				}
			}
			foreach (PlainItem plainItem in plainItems)
			{
				if (!instance.allItemsList.itemsList.Contains(plainItem.item))
				{
					if (plainItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName));
					}
					LethalLibItemList.Add(plainItem.item);
					instance.allItemsList.itemsList.Add(plainItem.item);
				}
			}
			terminal = self;
			List<Item> list = self.buyableItemsList.ToList();
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val2.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val3 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal");
			foreach (ShopItem item2 in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item2.item.itemName) && !item2.wasRemoved)
				{
					Plugin.logger.LogInfo((object)("Item " + item2.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				item2.wasRemoved = false;
				if (item2.price == -1)
				{
					item2.price = item2.item.creditsWorth;
				}
				else
				{
					item2.item.creditsWorth = item2.price;
				}
				int num = -1;
				if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item2.item))
				{
					list.Add(item2.item);
				}
				else
				{
					num = list.IndexOf(item2.item);
				}
				int buyItemIndex = ((num == -1) ? (list.Count - 1) : num);
				string itemName = item2.item.itemName;
				char c = itemName[itemName.Length - 1];
				string text = itemName;
				Plugin.logger.LogInfo((object)("Adding " + itemName + " to terminal"));
				TerminalNode val4 = item2.buyNode2;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode2";
					val4.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 15;
					Plugin.logger.LogInfo((object)"Generating buynode2");
				}
				val4.buyItemIndex = buyItemIndex;
				val4.isConfirmationNode = false;
				val4.itemCost = item2.price;
				val4.playSyncedClip = 0;
				Plugin.logger.LogInfo((object)$"Item price: {val4.itemCost}, Item index: {val4.buyItemIndex}");
				TerminalNode val5 = item2.buyNode1;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = itemName.Replace(" ", "-") + "BuyNode1";
					val5.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 35;
					Plugin.logger.LogInfo((object)"Generating buynode1");
				}
				val5.buyItemIndex = buyItemIndex;
				val5.isConfirmationNode = true;
				val5.overrideOptions = true;
				val5.itemCost = item2.price;
				Plugin.logger.LogInfo((object)$"Item price: {val5.itemCost}, Item index: {val5.buyItemIndex}");
				val5.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val4
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				TerminalKeyword val6 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val2);
				Plugin.logger.LogInfo((object)("Generated keyword: " + val6.word));
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(val6);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val2.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = val6,
					result = val5
				});
				val2.compatibleNouns = list3.ToArray();
				TerminalNode val7 = item2.itemInfo;
				if ((Object)(object)val7 == (Object)null)
				{
					val7 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val7).name = itemName.Replace(" ", "-") + "InfoNode";
					val7.displayText = "[No information about this object was found.]\n\n";
					val7.clearPreviousText = true;
					val7.maxCharactersToType = 25;
					Plugin.logger.LogInfo((object)"Generated item info!!");
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val3.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = val6,
					result = val7
				});
				val3.compatibleNouns = list4.ToArray();
				BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo);
				buyableItemAssetInfo.itemAsset = item2.item;
				buyableItemAssetInfo.keyword = val6;
				BuyableItemAssetInfo item4 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item4);
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags)
		{
			ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			scrapItem.modName = name;
			scrapItems.Add(scrapItem);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags, levelOverrides);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			scrapItem.modName = name;
			scrapItems.Add(scrapItem);
		}

		public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterShopItem(Item shopItem, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterItem(Item plainItem)
		{
			PlainItem plainItem2 = new PlainItem(plainItem);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			plainItem2.modName = name;
			plainItems.Add(plainItem2);
		}

		public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					ScrapItem actualItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)scrapItem || (Object)(object)x.item == (Object)(object)scrapItem);
					SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)actualItem.item));
					if (val2 != null)
					{
						val.spawnableScrap.Remove(val2);
					}
				}
			}
		}

		public static void RemoveShopItem(Item shopItem)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem || (Object)(object)x.item == (Object)(object)shopItem);
			actualItem.wasRemoved = true;
			List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val2 = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			List<CompatibleNoun> list2 = val2.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
			if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
				list.Remove(asset.keyword);
				list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
				list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			}
			terminal.terminalNodes.allKeywords = list.ToArray();
			val2.compatibleNouns = list2.ToArray();
			val.compatibleNouns = list3.ToArray();
		}

		public static void UpdateShopItemPrice(Item shopItem, int price)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem || (Object)(object)x.item == (Object)(object)shopItem);
			actualItem.item.creditsWorth = price;
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = val.compatibleNouns.ToList();
			if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				return;
			}
			BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
			if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword))
			{
				return;
			}
			CompatibleNoun val2 = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			TerminalNode result2 = val2.result;
			result2.itemCost = price;
			if (result2.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result2.terminalOptions;
			foreach (CompatibleNoun val3 in terminalOptions)
			{
				if ((Object)(object)val3.result != (Object)null && val3.result.buyItemIndex != -1)
				{
					val3.result.itemCost = price;
				}
			}
		}
	}
	public class Levels
	{
		[Flags]
		public enum LevelTypes
		{
			None = 1,
			ExperimentationLevel = 4,
			AssuranceLevel = 8,
			VowLevel = 0x10,
			OffenseLevel = 0x20,
			MarchLevel = 0x40,
			RendLevel = 0x80,
			DineLevel = 0x100,
			TitanLevel = 0x200,
			Vanilla = 0x3FC,
			All = -1
		}
	}
	public class MapObjects
	{
		public class RegisteredMapObject
		{
			public SpawnableMapObject mapObject;

			public SpawnableOutsideObjectWithRarity outsideObject;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;

			public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects;
		}

		public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>();

		public static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			//IL_0032: 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_003d: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__RoundManager_SpawnMapObjects;
			if (obj2 == null)
			{
				hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects;
				<>O.<1>__RoundManager_SpawnMapObjects = val2;
				obj2 = (object)val2;
			}
			RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2;
		}

		private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self)
		{
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			RandomMapObject[] array2 = array;
			foreach (RandomMapObject val in array2)
			{
				foreach (RegisteredMapObject mapObject in mapObjects)
				{
					if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn))
					{
						val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn);
					}
				}
			}
			orig.Invoke(self);
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (RegisteredMapObject mapObject in mapObjects)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !mapObject.levels.HasFlag(levelTypes))
					{
						continue;
					}
					if (mapObject.mapObject != null)
					{
						if (!val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn))
						{
							List<SpawnableMapObject> list = val.spawnableMapObjects.ToList();
							list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn);
							val.spawnableMapObjects = list.ToArray();
						}
						SpawnableMapObject mapObject2 = mapObject.mapObject;
						if (mapObject.spawnRateFunction != null)
						{
							mapObject2.numberToSpawn = mapObject.spawnRateFunction(val);
						}
						List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList();
						list2.Add(mapObject2);
						val.spawnableMapObjects = list2.ToArray();
						Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name));
					}
					else
					{
						if (mapObject.outsideObject == null)
						{
							continue;
						}
						if (!val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn))
						{
							List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList();
							list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn);
							val.spawnableOutsideObjects = list3.ToArray();
						}
						SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject;
						if (mapObject.spawnRateFunction != null)
						{
							outsideObject.randomAmount = mapObject.spawnRateFunction(val);
						}
						List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList();
						list4.Add(outsideObject);
						val.spawnableOutsideObjects = list4.ToArray();
						Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name));
					}
				}
			}
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject.prefabToSpawn).ToArray();
				}
			}
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject.spawnableObject.prefabToSpawn).ToArray();
				}
			}
		}
	}
	public class NetworkPrefabs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__GameNetworkManager_Start;
		}

		private static List<GameObject> _networkPrefabs = new List<GameObject>();

		internal static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			object obj = <>O.<0>__GameNetworkManager_Start;
			if (obj == null)
			{
				hook_Start val = GameNetworkManager_Start;
				<>O.<0>__GameNetworkManager_Start = val;
				obj = (object)val;
			}
			GameNetworkManager.Start += (hook_Start)obj;
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!_networkPrefabs.Contains(prefab))
			{
				_networkPrefabs.Add(prefab);
			}
		}

		public static GameObject CreateNetworkPrefab(string name)
		{
			GameObject val = PrefabUtils.CreatePrefab(name);
			val.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(val);
			return val;
		}

		public static GameObject CloneNetworkPrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = PrefabUtils.ClonePrefab(prefabToClone, newName);
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + ((Object)val).name));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(val);
			return val;
		}

		private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self)
		{
			orig.Invoke(self);
			foreach (GameObject networkPrefab in _networkPrefabs)
			{
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab))
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				}
			}
		}
	}
	public class Player
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;
		}

		public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>();

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

		public static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (KeyValuePair<string, GameObject> ragdollRef in ragdollRefs)
			{
				if (!self.playerRagdolls.Contains(ragdollRef.Value))
				{
					self.playerRagdolls.Add(ragdollRef.Value);
					int value = self.playerRagdolls.Count - 1;
					if (ragdollIndexes.ContainsKey(ragdollRef.Key))
					{
						ragdollIndexes[ragdollRef.Key] = value;
					}
					else
					{
						ragdollIndexes.Add(ragdollRef.Key, value);
					}
				}
			}
		}

		public static int GetRagdollIndex(string id)
		{
			return ragdollIndexes[id];
		}

		public static GameObject GetRagdoll(string id)
		{
			return ragdollRefs[id];
		}

		public static void RegisterPlayerRagdoll(string id, GameObject ragdoll)
		{
			Plugin.logger.LogInfo((object)("Registering player ragdoll " + id));
			ragdollRefs.Add(id, ragdoll);
		}
	}
	public class PrefabUtils
	{
		internal static Lazy<GameObject> _prefabParent;

		internal static GameObject prefabParent => _prefabParent.Value;

		static PrefabUtils()
		{
			_prefabParent = new Lazy<GameObject>((Func<GameObject>)delegate
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Expected O, but got Unknown
				GameObject val = new GameObject("LethalLibGeneratedPrefabs");
				((Object)val).hideFlags = (HideFlags)61;
				val.SetActive(false);
				return val;
			});
		}

		public static GameObject ClonePrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = Object.Instantiate<GameObject>(prefabToClone, prefabParent.transform);
			((Object)val).hideFlags = (HideFlags)61;
			if (newName != null)
			{
				((Object)val).name = newName;
			}
			else
			{
				((Object)val).name = ((Object)prefabToClone).name;
			}
			return val;
		}

		public static GameObject CreatePrefab(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			((Object)val).hideFlags = (HideFlags)61;
			val.transform.SetParent(prefabParent.transform);
			return val;
		}
	}
	public class Shaders
	{
		public static void FixShaders(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				Material[] materials = val.materials;
				foreach (Material val2 in materials)
				{
					if (((Object)val2.shader).name.Contains("Standard"))
					{
						val2.shader = Shader.Find("HDRP/Lit");
					}
				}
			}
		}
	}
	public class TerminalUtils
	{
		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false)
		{
			TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)val).name = word;
			val.word = word;
			val.isVerb = isVerb;
			val.compatibleNouns = compatibleNouns;
			val.specialKeywordResult = specialKeywordResult;
			val.defaultVerb = defaultVerb;
			val.accessTerminalObjects = accessTerminalObjects;
			return val;
		}
	}
	public enum StoreType
	{
		None,
		ShipUpgrade,
		Decor
	}
	public class Unlockables
	{
		public class RegisteredUnlockable
		{
			public UnlockableItem unlockable;

			public StoreType StoreType;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public int price;

			public string modName;

			public bool disabled = false;

			public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
			{
				this.unlockable = unlockable;
				this.buyNode1 = buyNode1;
				this.buyNode2 = buyNode2;
				this.itemInfo = itemInfo;
				this.price = price;
			}
		}

		public struct BuyableUnlockableAssetInfo
		{
			public UnlockableItem itemAsset;

			public TerminalKeyword keyword;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__Terminal_Awake;

			public static hook_TextPostProcess <1>__Terminal_TextPostProcess;
		}

		public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>();

		public static List<BuyableUnlockableAssetInfo> buyableUnlockableAssetInfos = new List<BuyableUnlockableAssetInfo>();

		public static void Init()
		{
			//IL_0011: 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: Expected O, but got Unknown
			//IL_0032: 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_003d: Expected O, but got Unknown
			object obj = <>O.<0>__Terminal_Awake;
			if (obj == null)
			{
				hook_Awake val = Terminal_Awake;
				<>O.<0>__Terminal_Awake = val;
				obj = (object)val;
			}
			Terminal.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_TextPostProcess;
			if (obj2 == null)
			{
				hook_TextPostProcess val2 = Terminal_TextPostProcess;
				<>O.<1>__Terminal_TextPostProcess = val2;
				obj2 = (object)val2;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj2;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]"))
			{
				int num = modifiedDisplayText.IndexOf(":");
				foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables)
				{
					if (registeredUnlockable.StoreType == StoreType.ShipUpgrade && !registeredUnlockable.disabled)
					{
						string unlockableName = registeredUnlockable.unlockable.unlockableName;
						int price = registeredUnlockable.price;
						string value = $"\n* {unlockableName}    //    Price: ${price}";
						modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value);
					}
				}
			}
			return orig.Invoke(self, modifiedDisplayText, node);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_04dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			//IL_051f: Expected O, but got Unknown
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_0526: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Expected O, but got Unknown
			//IL_05ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0609: Expected O, but got Unknown
			//IL_069d: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06af: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bc: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list");
			foreach (RegisteredUnlockable unlockable2 in registeredUnlockables)
			{
				if (instance.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable2.unlockable.unlockableName))
				{
					Plugin.logger.LogInfo((object)("Unlockable " + unlockable2.unlockable.unlockableName + " already exists in unlockables list, skipping"));
					continue;
				}
				if ((Object)(object)unlockable2.unlockable.prefabObject != (Object)null)
				{
					PlaceableShipObject componentInChildren = unlockable2.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>();
					if ((Object)(object)componentInChildren != (Object)null)
					{
						componentInChildren.unlockableID = instance.unlockablesList.unlockables.Count;
					}
				}
				instance.unlockablesList.unlockables.Add(unlockable2.unlockable);
			}
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList();
			Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal");
			foreach (RegisteredUnlockable item in list)
			{
				string unlockableName = item.unlockable.unlockableName;
				TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val);
				if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word))
				{
					Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping."));
					continue;
				}
				int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName);
				StartOfRound instance2 = StartOfRound.Instance;
				if ((Object)(object)instance2 == (Object)null)
				{
					Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND");
				}
				item.disabled = false;
				if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null)
				{
					item.price = item.buyNode1.itemCost;
				}
				char c = unlockableName[unlockableName.Length - 1];
				string text = unlockableName;
				TerminalNode val3 = item.buyNode2;
				if ((Object)(object)val3 == (Object)null)
				{
					val3 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2";
					val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val3.clearPreviousText = true;
					val3.maxCharactersToType = 15;
				}
				val3.buyItemIndex = -1;
				val3.shipUnlockableID = shipUnlockableID;
				val3.buyUnlockable = true;
				val3.creatureName = unlockableName;
				val3.isConfirmationNode = false;
				val3.itemCost = item.price;
				val3.playSyncedClip = 0;
				TerminalNode val4 = item.buyNode1;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1";
					val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 35;
				}
				val4.buyItemIndex = -1;
				val4.shipUnlockableID = shipUnlockableID;
				val4.creatureName = unlockableName;
				val4.isConfirmationNode = true;
				val4.overrideOptions = true;
				val4.itemCost = item.price;
				val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val3
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				if (item.StoreType == StoreType.Decor)
				{
					item.unlockable.shopSelectionNode = val4;
				}
				else
				{
					item.unlockable.shopSelectionNode = null;
				}
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(keyword3);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = keyword3,
					result = val4
				});
				val.compatibleNouns = list3.ToArray();
				TerminalNode val5 = item.itemInfo;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode";
					val5.displayText = "[No information about this object was found.]\n\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 25;
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val2.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = keyword3,
					result = val5
				});
				val2.compatibleNouns = list4.ToArray();
				BuyableUnlockableAssetInfo buyableUnlockableAssetInfo = default(BuyableUnlockableAssetInfo);
				buyableUnlockableAssetInfo.itemAsset = item.unlockable;
				buyableUnlockableAssetInfo.keyword = keyword3;
				BuyableUnlockableAssetInfo item2 = buyableUnlockableAssetInfo;
				buyableUnlockableAssetInfos.Add(item2);
				Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName));
			}
			orig.Invoke(self);
		}

		public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None)
		{
			RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price);
		}

		public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None)
		{
			RegisterUnlockable(unlockable, storeType, null, null, null, price);
		}

		public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price);
		}

		public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price);
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			string name = callingAssembly.GetName().Name;
			registeredUnlockable.modName = name;
			registeredUnlockable.StoreType = storeType;
			registeredUnlockables.Add(registeredUnlockable);
		}

		public static void DisableUnlockable(UnlockableItemDef unlockable)
		{
			DisableUnlockable(unlockable.unlockable);
		}

		public static void DisableUnlockable(UnlockableItem unlockable)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			List<TerminalKeyword> list = Items.terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword val = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val2 = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val2.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> list2 = val2.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
			RegisteredUnlockable registeredUnlockable = registeredUnlockables.Find((RegisteredUnlockable unlock) => unlock.unlockable == unlockable);
			registeredUnlockable.disabled = true;
			if (buyableUnlockableAssetInfos.Any((BuyableUnlockableAssetInfo x) => x.itemAsset == unlockable))
			{
				BuyableUnlockableAssetInfo asset = buyableUnlockableAssetInfos.First((BuyableUnlockableAssetInfo x) => x.itemAsset == unlockable);
				list.Remove(asset.keyword);
				list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
				list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			}
			Items.terminal.terminalNodes.allKeywords = list.ToArray();
			val2.compatibleNouns = list2.ToArray();
			val.compatibleNouns = list3.ToArray();
		}

		public static void UpdateUnlockablePrice(UnlockableItem shopItem, int price)
		{
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			TerminalKeyword val = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = val.compatibleNouns.ToList();
			RegisteredUnlockable registeredUnlockable = registeredUnlockables.Find((RegisteredUnlockable unlock) => unlock.unlockable == shopItem);
			if (registeredUnlockable != null && registeredUnlockable.price != -1)
			{
				registeredUnlockable.price = price;
			}
			if (!buyableUnlockableAssetInfos.Any((BuyableUnlockableAssetInfo x) => x.itemAsset == shopItem))
			{
				return;
			}
			BuyableUnlockableAssetInfo asset = buyableUnlockableAssetInfos.First((BuyableUnlockableAssetInfo x) => x.itemAsset == shopItem);
			if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword))
			{
				return;
			}
			CompatibleNoun val2 = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			TerminalNode result2 = val2.result;
			result2.itemCost = price;
			if (result2.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result2.terminalOptions;
			foreach (CompatibleNoun val3 in terminalOptions)
			{
				if ((Object)(object)val3.result != (Object)null && val3.result.buyItemIndex != -1)
				{
					val3.result.itemCost = price;
				}
			}
		}
	}
	public class Utilities
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Start <1>__MenuManager_Start;
		}

		public static List<GameObject> prefabsToFix = new List<GameObject>();

		public static List<GameObject> fixedPrefabs = new List<GameObject>();

		public static void Init()
		{
			//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_002c: Expected O, but got Unknown
			//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_004d: Expected O, but got Unknown
			Plugin.logger.LogInfo((object)"Utilities.Init()");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__MenuManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = MenuManager_Start;
				<>O.<1>__MenuManager_Start = val2;
				obj2 = (object)val2;
			}
			MenuManager.Start += (hook_Start)obj2;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			AudioMixer diageticMixer = SoundManager.Instance.diageticMixer;
			Plugin.logger.LogInfo((object)("Diagetic mixer is " + ((Object)diageticMixer).name));
			Plugin.logger.LogInfo((object)$"Found {prefabsToFix.Count} prefabs to fix");
			List<GameObject> list = new List<GameObject>();
			for (int num = prefabsToFix.Count - 1; num >= 0; num--)
			{
				GameObject val = prefabsToFix[num];
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>();
				AudioSource[] array = componentsInChildren;
				foreach (AudioSource val2 in array)
				{
					if (!((Object)(object)val2.outputAudioMixerGroup == (Object)null) && ((Object)val2.outputAudioMixerGroup.audioMixer).name == "Diagetic")
					{
						AudioMixerGroup val3 = diageticMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0];
						if ((Object)(object)val3 != (Object)null)
						{
							val2.outputAudioMixerGroup = val3;
							Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to Diagetic:" + ((Object)val3).name));
							list.Add(val);
						}
					}
				}
			}
			foreach (GameObject item in list)
			{
				prefabsToFix.Remove(item);
			}
			orig.Invoke(self);
		}

		private static void MenuManager_Start(orig_Start orig, MenuManager self)
		{
			orig.Invoke(self);
			if ((Object)(object)((Component)self).GetComponent<AudioSource>() == (Object)null)
			{
				return;
			}
			AudioMixer audioMixer = ((Component)self).GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer;
			List<GameObject> list = new List<GameObject>();
			for (int num = prefabsToFix.Count - 1; num >= 0; num--)
			{
				GameObject val = prefabsToFix[num];
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>();
				AudioSource[] array = componentsInChildren;
				foreach (AudioSource val2 in array)
				{
					if (!((Object)(object)val2.outputAudioMixerGroup == (Object)null) && ((Object)val2.outputAudioMixerGroup.audioMixe

plugins/Dependencies/2018-LC_API-3.3.2/LC_API.dll

Decompiled 10 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;

[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.3.2.0")]
[assembly: AssemblyInformationalVersion("3.3.2+b15ff9853204e171c8e31468a9134b397b67e7e8")]
[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..");
			GameTips.ShowTip("Mod List:", "Asking all other players for installed mods..");
			GameTips.ShowTip("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);
			GameTips.ShowTip("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.3.2")]
	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.3.2";
	}
}
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 (_registerInfo == 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;
		}
	}
	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();
		}

		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]
			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_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e9: Invalid comparison between Unknown and I4
				//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_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_00b7: 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_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;
					}
					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;
					}
					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);
					

plugins/Game Balance/kyxino-LethalUtilities-1.2.14/LethalUtilities.dll

Decompiled 10 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalUtilities.Configuration;
using TMPro;
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: AssemblyTitle("LethalUtilities")]
[assembly: AssemblyDescription("A Lethal Company mod made by Kyxino.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kyxino")]
[assembly: AssemblyProduct("LethalUtilities")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d1273c8d-cadb-4ba8-9306-763e5ed6813c")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LethalUtilities
{
	public enum MapLevel
	{
		None = -1,
		CompanyBuilding = 3,
		Level1Experimentation = 0,
		Level2Assurance = 1,
		Level3Vow = 2,
		Level7Offense = 7,
		Level4March = 4,
		Level5Rend = 5,
		Level6Dine = 6,
		Level8Titan = 8
	}
	internal static class MapSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.MapConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the MapConfig executes.", 0);

		public static ConfigEntry<bool> ScrapModifiersEnabled = UtilsMod.MapConfig.Bind("Active Settings", "ScrapModifiersEnabled", defaultValue: false, "Whether or not the scrap multipliers apply.", 0);

		public static ConfigEntry<bool> MapModifiersEnabled = UtilsMod.MapConfig.Bind("Active Settings", "MapModifiersEnabled", defaultValue: false, "Whether or not the map multipliers apply.", 0);

		public static ConfigEntry<bool> TimeModifiersEnabled = UtilsMod.MapConfig.Bind("Active Settings", "TimeModifiersEnabled", defaultValue: false, "Whether or not the time multipliers apply.", 0);

		public static ConfigEntry<bool> SpawnModifiersEnabled = UtilsMod.MapConfig.Bind("Active Settings", "SpawnModifiersEnabled", defaultValue: false, "Whether or not the map spawn modifiers will apply.", 0);

		public static ConfigEntry<float> ScrapAmountScalar = UtilsMod.MapConfig.Bind("Global Map Settings", "ScrapAmountScalar", 1f, "The overall multiplier of spawned scrap.\n(Multiplies on top of individual scalars.)", 1);

		public static ConfigEntry<float> ScrapValueScalar = UtilsMod.MapConfig.Bind("Global Map Settings", "ScrapValueScalar", 0.4f, "The overall multiplier of scrap value.\n(Multiplies on top of individual scalars.)", 1);

		public static ConfigEntry<float> MapScalar = UtilsMod.MapConfig.Bind("Global Map Settings", "MapScalar", 1f, "The overall map scale.\nValues under 1 will be capped off at 1 before applying because it crashes the game.\n(Multiplies on top of individual scalars.)", 1);

		public static ConfigEntry<float> DayScalar = UtilsMod.MapConfig.Bind("Global Map Settings", "DayScalar", 1f, "The overall map day speed multiplier.\n(Ex: 0 starts at 6:00AM, 1 starts at 7:40AM, disregarding ship landing time.)\n(Multiplies on top of individual scalars.)", 1);

		public static ConfigEntry<float> TimeSpeedScalar = UtilsMod.MapConfig.Bind("Global Map Settings", "TimeSpeedScalar", 1.4f, "The overall time speed multiplier.\n(Multiplies on top of individual scalars.)", 1);

		public static Dictionary<MapLevel, Dictionary<string, ConfigEntryBase>> Settings = new Dictionary<MapLevel, Dictionary<string, ConfigEntryBase>>
		{
			[MapLevel.Level1Experimentation] = AddMapSettings("Experimentation", 11, 1f, 0f, 1f, 4f, 5f, 8, 12, 4, 8, 5, 51, 58, 28, 13, 16, 31, 1, 28, 1, 0, 0, 0, 0, 75, 0, 56, 0, 22, 74, 52),
			[MapLevel.Level2Assurance] = AddMapSettings("Assurance", 12, 1f, 0f, 1f, 3f, 10f, 13, 17, 6, 8, 7, 93, 69, 78, 14, 24, 28, 1, 14, 1, 0, 0, 0, 0, 78, 1, 95, 20, 58, 100, 43),
			[MapLevel.Level3Vow] = AddMapSettings("Vow", 13, 2.5f, 0f, 1.15f, 3f, 7f, 10, 13, 7, 6, 17, 61, 40, 63, 80, 9, 28, 0, 19, 0, 6, 0, 0, 0, 4, 100, 18, 0, 61, 100, 67),
			[MapLevel.Level7Offense] = AddMapSettings("Offense", 15, 2f, 0f, 1.25f, 4f, 10f, 14, 18, 12, 8, 20, 27, 44, 16, 3, 55, 32, 0, 7, 2, 25, 0, 0, 0, 100, 9, 37, 60, 58, 100, 43),
			[MapLevel.Level4March] = AddMapSettings("March", 16, 2.75f, 0f, 2f, 4f, 7f, 13, 17, 14, 12, 20, 38, 64, 36, 56, 74, 15, 0, 9, 3, 10, 1, 0, 0, 38, 64, 16, 72, 72, 83, 49),
			[MapLevel.Level5Rend] = AddMapSettings("Rend", 17, 2.7f, 0f, 1.2f, 3f, 10f, 18, 26, 10, 6, 20, 31, 43, 0, 51, 0, 6, 20, 7, 100, 70, 69, 0, 25, 74, 60, 18),
			[MapLevel.Level6Dine] = AddMapSettings("Dine", 18, 2.7f, 0f, 1.3f, 4f, 10f, 20, 28, 15, 6, 20, 52, 64, 48, 25, 48, 39, 18, 16, 60, 53, 66, 0, 0, 79, 28, 57),
			[MapLevel.Level8Titan] = AddMapSettings("Titan", 19, 6f, 0f, 2.35f, 2f, 10f, 23, 38, 18, 7, 20, 54, 59, 38, 62, 54, 20, 28, 16, 32, 59, 71, 0, 32, 80, 32, 4)
		};

		private static ConfigEntry<T> NewFormattedEntry<T>(string PrefixName, string Variable, T DefaultValue, string Description, int Order = -1)
		{
			return UtilsMod.MapConfig.Bind(PrefixName + " Settings", Variable ?? "", DefaultValue, Description.Replace("$VAR", Variable), Order);
		}

		private static Dictionary<string, ConfigEntryBase> AddMapSettings(string MapName, int Order = -1, float TimeToArrive = 1f, float OffsetFromGlobalTime = 0f, float FactorySizeMultiplier = 1f, float SpawnProbabilityRange = 1f, float DaytimeEnemiesProbabilityRange = 1f, int MinScrapAmount = 0, int MaxScrapAmount = 0, int MaxEnemyPower = 10, int MaxOutsideEnemyPower = 10, int MaxDaytimeEnemyPower = 20, int Centipede = 0, int SandSpider = 0, int HoarderBug = 0, int Flowerman = 0, int Crawler = 0, int Blob = 0, int DressGirl = 0, int Puffer = 0, int Nutcracker = 0, int SpringMan = 0, int Jester = 0, int LassoMan = 0, int Mask = 0, int MouthDog = 0, int ForestGiant = 0, int SandWorm = 0, int BaboonHawk = 0, int RedLocustBees = 0, int Doublewing = 0, int DocileLocustBees = 0)
		{
			return new Dictionary<string, ConfigEntryBase>
			{
				["ScrapAmountScalar"] = NewFormattedEntry(MapName + " Scrap", "ScrapAmountScalar", 1f, "The " + MapName + " multiplier of spawned scrap.", Order),
				["ScrapValueScalar"] = NewFormattedEntry(MapName + " Scrap", "ScrapValueScalar", 1f, "The " + MapName + " multiplier of scrap value.", Order),
				["MapScalar"] = NewFormattedEntry(MapName + " Map", "MapScalar", 1f, "The " + MapName + " scalar of the inside.\nValues under 1 will be capped off at 1 before applying because it crashes the game.", Order),
				["DayScalar"] = NewFormattedEntry(MapName + " Time", "DayScalar", 1f, "The " + MapName + " speed scalar of the day.\n(Ex: 0 starts at 6:00AM, 1 starts at 7:40AM, disregarding ship landing time.)", Order),
				["TimeSpeedScalar"] = NewFormattedEntry(MapName + " Time", "TimeSpeedScalar", 1f, "The " + MapName + " time scalar of the day.", Order),
				["TimeToArrive"] = NewFormattedEntry(MapName + " Time", "TimeToArrive", TimeToArrive, "The " + MapName + " $VAR.", Order),
				["OffsetFromGlobalTime"] = NewFormattedEntry(MapName + " Time", "OffsetFromGlobalTime", OffsetFromGlobalTime, "The " + MapName + " $VAR.", Order),
				["SpawnProbabilityRange"] = NewFormattedEntry(MapName + " Spawn", "SpawnProbabilityRange", SpawnProbabilityRange, "The " + MapName + " $VAR.", Order),
				["DaytimeEnemiesProbabilityRange"] = NewFormattedEntry(MapName + " Spawn", "DaytimeEnemiesProbabilityRange", DaytimeEnemiesProbabilityRange, "The " + MapName + " $VAR.", Order),
				["MinScrapAmount"] = NewFormattedEntry(MapName + " Scrap", "MinScrapAmount", MinScrapAmount, "The " + MapName + " $VAR.", Order),
				["MaxScrapAmount"] = NewFormattedEntry(MapName + " Scrap", "MaxScrapAmount", MaxScrapAmount, "The " + MapName + " $VAR.", Order),
				["MinEnemiesToSpawn"] = NewFormattedEntry(MapName + " Spawn", "MinEnemiesToSpawn", 0, "The " + MapName + " $VAR.", Order),
				["MinOutsideEnemiesToSpawn"] = NewFormattedEntry(MapName + " Spawn", "MinOutsideEnemiesToSpawn", 0, "The " + MapName + " $VAR.", Order),
				["HourTimeBetweenEnemySpawnBatches"] = NewFormattedEntry(MapName + " Spawn", "HourTimeBetweenEnemySpawnBatches", 2, "The " + MapName + " $VAR.", Order),
				["MaxEnemyPower"] = NewFormattedEntry(MapName + " Spawn", "MaxInsideEnemyPower", MaxEnemyPower, "The " + MapName + " $VAR.", Order),
				["MaxOutsideEnemyPower"] = NewFormattedEntry(MapName + " Spawn", "MaxOutsideEnemyPower", MaxOutsideEnemyPower, "The " + MapName + " $VAR.", Order),
				["MaxDaytimeEnemyPower"] = NewFormattedEntry(MapName + " Spawn", "MaxDaytimeEnemyPower", MaxDaytimeEnemyPower, "The " + MapName + " $VAR.", Order),
				["CentipedeSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "CentipedeSpawnWeight", Centipede, "The " + MapName + " $VAR.", Order),
				["SandSpiderSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "SandSpiderSpawnWeight", SandSpider, "The " + MapName + " $VAR.", Order),
				["HoarderBugSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "HoarderBugSpawnWeight", HoarderBug, "The " + MapName + " $VAR.", Order),
				["FlowermanSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "FlowermanSpawnWeight", Flowerman, "The " + MapName + " $VAR.", Order),
				["CrawlerSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "CrawlerSpawnWeight", Crawler, "The " + MapName + " $VAR.", Order),
				["BlobSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "BlobSpawnWeight", Blob, "The " + MapName + " $VAR.", Order),
				["DressGirlSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "DressGirlSpawnWeight", DressGirl, "The " + MapName + " $VAR.", Order),
				["PufferSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "PufferSpawnWeight", Puffer, "The " + MapName + " $VAR.", Order),
				["NutcrackerSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "NutcrackerSpawnWeight", Nutcracker, "The " + MapName + " $VAR.", Order),
				["SpringManSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "SpringManSpawnWeight", SpringMan, "The " + MapName + " $VAR.", Order),
				["JesterSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "JesterSpawnWeight", Jester, "The " + MapName + " $VAR.", Order),
				["LassoManSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "LassoManSpawnWeight", LassoMan, "The " + MapName + " $VAR.", Order),
				["MaskSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "MaskSpawnWeight", Mask, "The " + MapName + " $VAR.", Order),
				["MouthDogSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "MouthDogSpawnWeight", MouthDog, "The " + MapName + " $VAR.", Order),
				["ForestGiantSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "ForestGiantSpawnWeight", ForestGiant, "The " + MapName + " $VAR.", Order),
				["SandWormSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "SandWormSpawnWeight", SandWorm, "The " + MapName + " $VAR.", Order),
				["BaboonHawkSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "BaboonHawkSpawnWeight", BaboonHawk, "The " + MapName + " $VAR.", Order),
				["RedLocustBeesSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "RedLocustBeesSpawnWeight", RedLocustBees, "The " + MapName + " $VAR.", Order),
				["DoublewingSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "DoublewingSpawnWeight", Doublewing, "The " + MapName + " $VAR.", Order),
				["DocileLocustBeesSpawnWeight"] = NewFormattedEntry(MapName + " Spawn", "DocileLocustBeesSpawnWeight", DocileLocustBees, "The " + MapName + " $VAR.", Order)
			};
		}
	}
	internal class MapPatch
	{
	}
	internal static class WeatherSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.WeatherConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the WeatherConfig executes.");

		public static ConfigEntry<bool> ScrapModifiersEnabled = UtilsMod.WeatherConfig.Bind("Active Settings", "ScrapModifiersEnabled", defaultValue: false, "Whether or not the scrap multipliers apply.");

		public static ConfigEntry<bool> MapModifiersEnabled = UtilsMod.WeatherConfig.Bind("Active Settings", "MapModifiersEnabled", defaultValue: false, "Whether or not the map multipliers apply. (Why not? Make Eclipsed have giant maps if you want.)");

		public static ConfigEntry<bool> TimeModifiersEnabled = UtilsMod.WeatherConfig.Bind("Active Settings", "TimeModifiersEnabled", defaultValue: false, "Whether or not the time multipliers apply.");

		public static ConfigEntry<bool> SpawnModifiersEnabled = UtilsMod.WeatherConfig.Bind("Active Settings", "SpawnModifiersEnabled", defaultValue: false, "Whether or not the weather spawn modifiers will apply. (Will set default values beforehand for compatibility/stability reasons.)");

		public static Dictionary<LevelWeatherType, Dictionary<string, ConfigEntryBase>> Settings = new Dictionary<LevelWeatherType, Dictionary<string, ConfigEntryBase>>
		{
			[(LevelWeatherType)(-1)] = AddMapSettings("Normal"),
			[(LevelWeatherType)0] = AddMapSettings("Dusty"),
			[(LevelWeatherType)1] = AddMapSettings("Rainy"),
			[(LevelWeatherType)2] = AddMapSettings("Stormy"),
			[(LevelWeatherType)3] = AddMapSettings("Foggy"),
			[(LevelWeatherType)4] = AddMapSettings("Flooded"),
			[(LevelWeatherType)5] = AddMapSettings("Eclipsed")
		};

		private static ConfigEntry<float> NewFloatEntryWithMapVar(string PrefixName, string Variable, string AddPrefixToNew, float DefaultValue, string Description)
		{
			ConfigDefinition configDefinition = new ConfigDefinition(PrefixName + " Weather Settings", ((PrefixName == "Normal") ? "DefaultWeather" : PrefixName) + Variable);
			ConfigEntry<float> configEntry = UtilsMod.WeatherConfig.Bind(configDefinition, DefaultValue);
			ConfigEntry<float> configEntry2 = UtilsMod.WeatherConfig.Bind(PrefixName + " " + AddPrefixToNew + " Settings", Variable, DefaultValue, Description.Replace("$VAR", Variable));
			if (configEntry.Value != (float)configEntry.DefaultValue && configEntry2.Value == (float)configEntry2.DefaultValue)
			{
				configEntry2.Value = configEntry.Value;
			}
			UtilsMod.WeatherConfig.Remove(configDefinition);
			UtilsMod.WeatherConfig.Save();
			return configEntry2;
		}

		private static ConfigEntry<T> NewEntry<T>(string PrefixName, string Variable, T DefaultValue, string Description)
		{
			return UtilsMod.WeatherConfig.Bind(PrefixName + " Settings", Variable ?? "", DefaultValue, Description.Replace("$VAR", Variable));
		}

		private static Dictionary<string, ConfigEntryBase> AddMapSettings(string WeatherType)
		{
			Dictionary<string, ConfigEntryBase> dictionary = new Dictionary<string, ConfigEntryBase>();
			dictionary["ScrapAmountScalar"] = NewFloatEntryWithMapVar(WeatherType, "ScrapAmountScalar", "Scrap", 1f, "The " + WeatherType + " multiplier of spawned scrap.");
			dictionary["ScrapValueScalar"] = NewFloatEntryWithMapVar(WeatherType, "ScrapValueScalar", "Scrap", 1f, "The " + WeatherType + " multiplier of scrap value.");
			dictionary["MapScalar"] = NewFloatEntryWithMapVar(WeatherType, "MapScalar", "Map", 1f, "The " + WeatherType + " scalar of the inside.\nValues under 1 will be capped off at 1 before applying because it crashes the game.");
			dictionary["DayScalar"] = NewFloatEntryWithMapVar(WeatherType, "DayScalar", "Time", 1f, "The " + WeatherType + " speed scalar of the day.\n(Ex: 0 starts at 6:00AM, 1 starts at 7:40AM, disregarding ship landing time.)");
			dictionary["TimeSpeedScalar"] = NewEntry(WeatherType + " Time", "TimeSpeedScalar", 1f, "The " + WeatherType + " time scalar of the day.");
			dictionary["CentipedeMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "CentipedeMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["CentipedeAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "CentipedeAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["SandSpiderMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "SandSpiderMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["SandSpiderAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "SandSpiderAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["HoarderBugMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "HoarderBugMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["HoarderBugAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "HoarderBugAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["FlowermanMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "FlowermanMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["FlowermanAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "FlowermanAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["CrawlerMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "CrawlerMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["CrawlerAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "CrawlerAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["BlobMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "BlobMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["BlobAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "BlobAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["DressGirlMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "DressGirlMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["DressGirlAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "DressGirlAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["PufferMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "PufferMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["PufferAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "PufferAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["NutcrackerMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "NutcrackerMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["NutcrackerAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "NutcrackerAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["SpringManMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "SpringManMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["SpringManAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "SpringManAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["JesterMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "JesterMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["JesterAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "JesterAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["LassoManMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "LassoManMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["LassoManAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "LassoManAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["MaskMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "MaskMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["MaskAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "MaskAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["MouthDogMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "MouthDogMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["MouthDogAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "MouthDogAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["ForestGiantMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "ForestGiantMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["ForestGiantAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "ForestGiantAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["SandWormMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "SandWormMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["SandWormAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "SandWormAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["BaboonHawkMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "BaboonHawkMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["BaboonHawkAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "BaboonHawkAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["RedLocustBeesMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "RedLocustBeesMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["RedLocustBeesAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "RedLocustBeesAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["DoublewingMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "DoublewingMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["DoublewingAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "DoublewingAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			dictionary["DocileLocustBeesMapSpawnMultiplier"] = NewEntry(WeatherType + " Spawn", "DocileLocustBeesMapSpawnMultiplier", 1f, "The " + WeatherType + " $VAR.\n(Multiplier of the map spawn weight during " + WeatherType + " weather.");
			dictionary["DocileLocustBeesAddSpawnWeight"] = NewEntry(WeatherType + " Spawn", "DocileLocustBeesAddSpawnWeight", 0, "The " + WeatherType + " $VAR.\n(Additional spawn weight (aka chance, somewhat) added to the enemy during " + WeatherType + " weather.)");
			return dictionary;
		}
	}
	internal class WeatherPatch
	{
	}
	internal static class SpawnSettings
	{
	}
	internal class SpawnPatch
	{
		[HarmonyPatch(typeof(RoundManager), "LoadNewLevel")]
		[HarmonyPostfix]
		private static void PatchCHECK(ref SelectableLevel newLevel)
		{
			//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)
			MapLevel levelID = (MapLevel)newLevel.levelID;
			LevelWeatherType currentWeather = newLevel.currentWeather;
			UtilsMod.MLS.LogInfo((object)$"{RoundManager.Instance.hourTimeBetweenEnemySpawnBatches} {RoundManager.Instance.minEnemiesToSpawn} {RoundManager.Instance.minOutsideEnemiesToSpawn} {newLevel.maxEnemyPowerCount} {newLevel.maxOutsideEnemyPowerCount} {newLevel.maxDaytimeEnemyPowerCount} {newLevel.spawnProbabilityRange} {newLevel.daytimeEnemiesProbabilityRange} {newLevel.timeToArrive} {newLevel.OffsetFromGlobalTime}");
		}

		private static void AddEnemiesToLevel(List<SpawnableEnemyWithRarity> TypeOfEnemies, List<SpawnableEnemyWithRarity> AddToEnemies)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			foreach (SpawnableEnemyWithRarity AddToEnemy in AddToEnemies)
			{
				EnemyType enemyType = AddToEnemy.enemyType;
				GameObject enemyPrefab = enemyType.enemyPrefab;
				EnemyAI component = enemyPrefab.GetComponent<EnemyAI>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					continue;
				}
				bool flag = false;
				foreach (SpawnableEnemyWithRarity TypeOfEnemy in TypeOfEnemies)
				{
					if (TypeOfEnemy.enemyType.enemyName != enemyType.enemyName)
					{
						continue;
					}
					flag = true;
					break;
				}
				if (!flag)
				{
					SpawnableEnemyWithRarity val = new SpawnableEnemyWithRarity();
					val.enemyType = enemyType;
					val.rarity = 0;
					TypeOfEnemies.Add(val);
				}
			}
		}

		private static void ChangeEnemyRarities(List<SpawnableEnemyWithRarity> TypeOfEnemies, MapLevel Map, LevelWeatherType Weather)
		{
			//IL_00b6: 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)
			for (int i = 0; i < TypeOfEnemies.Count; i++)
			{
				SpawnableEnemyWithRarity val = TypeOfEnemies[i];
				if (!MapSettings.Settings.ContainsKey(Map))
				{
					continue;
				}
				Dictionary<string, ConfigEntryBase> dictionary = MapSettings.Settings[Map];
				if (dictionary.ContainsKey(((Object)val.enemyType).name + "SpawnWeight"))
				{
					ConfigEntry<int> configEntry = (ConfigEntry<int>)dictionary[((Object)val.enemyType).name + "SpawnWeight"];
					val.rarity = (MapSettings.SpawnModifiersEnabled.Value ? configEntry.Value : ((int)configEntry.DefaultValue));
					if (WeatherSettings.SpawnModifiersEnabled.Value && WeatherSettings.Settings.ContainsKey(Weather))
					{
						Dictionary<string, ConfigEntryBase> dictionary2 = WeatherSettings.Settings[Weather];
						val.rarity = (int)((float)val.rarity * (dictionary2[((Object)val.enemyType).name + "MapSpawnMultiplier"] as ConfigEntry<float>).Value) + (dictionary2[((Object)val.enemyType).name + "AddSpawnWeight"] as ConfigEntry<int>).Value;
					}
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager), "LoadNewLevel")]
		[HarmonyPrefix]
		[HarmonyPriority(1114)]
		private static void PatchLoadNewLevel(ref SelectableLevel newLevel)
		{
			//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_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			MapLevel levelID = (MapLevel)newLevel.levelID;
			LevelWeatherType currentWeather = newLevel.currentWeather;
			if (MapSettings.Settings.ContainsKey(levelID))
			{
				Dictionary<string, ConfigEntryBase> dictionary = MapSettings.Settings[levelID];
				if (MapSettings.SpawnModifiersEnabled.Value)
				{
					if (((ConfigEntry<int>)dictionary["HourTimeBetweenEnemySpawnBatches"]).Value != 2)
					{
						RoundManager.Instance.hourTimeBetweenEnemySpawnBatches = ((ConfigEntry<int>)dictionary["HourTimeBetweenEnemySpawnBatches"]).Value;
					}
					if (((ConfigEntry<int>)dictionary["MinEnemiesToSpawn"]).Value != 0)
					{
						RoundManager.Instance.minEnemiesToSpawn = ((ConfigEntry<int>)dictionary["MinEnemiesToSpawn"]).Value;
					}
					if (((ConfigEntry<int>)dictionary["MinOutsideEnemiesToSpawn"]).Value != 0)
					{
						RoundManager.Instance.minOutsideEnemiesToSpawn = ((ConfigEntry<int>)dictionary["MinOutsideEnemiesToSpawn"]).Value;
					}
					newLevel.maxEnemyPowerCount = ((ConfigEntry<int>)dictionary["MaxEnemyPower"]).Value;
					newLevel.maxOutsideEnemyPowerCount = ((ConfigEntry<int>)dictionary["MaxOutsideEnemyPower"]).Value;
					newLevel.maxDaytimeEnemyPowerCount = ((ConfigEntry<int>)dictionary["MaxDaytimeEnemyPower"]).Value;
					newLevel.spawnProbabilityRange = ((ConfigEntry<float>)dictionary["SpawnProbabilityRange"]).Value;
					newLevel.daytimeEnemiesProbabilityRange = ((ConfigEntry<float>)dictionary["DaytimeEnemiesProbabilityRange"]).Value;
				}
				if (MapSettings.TimeModifiersEnabled.Value)
				{
					newLevel.timeToArrive = ((ConfigEntry<float>)dictionary["TimeToArrive"]).Value;
					newLevel.OffsetFromGlobalTime = ((ConfigEntry<float>)dictionary["OffsetFromGlobalTime"]).Value;
				}
			}
			UtilsMod.MLS.LogInfo((object)$"{RoundManager.Instance.hourTimeBetweenEnemySpawnBatches} {RoundManager.Instance.minEnemiesToSpawn} {RoundManager.Instance.minOutsideEnemiesToSpawn} {newLevel.maxEnemyPowerCount} {newLevel.maxOutsideEnemyPowerCount} {newLevel.maxDaytimeEnemyPowerCount} {newLevel.spawnProbabilityRange} {newLevel.daytimeEnemiesProbabilityRange} {newLevel.timeToArrive} {newLevel.OffsetFromGlobalTime}");
			List<SpawnableEnemyWithRarity> enemies = newLevel.Enemies;
			List<SpawnableEnemyWithRarity> outsideEnemies = newLevel.OutsideEnemies;
			List<SpawnableEnemyWithRarity> daytimeEnemies = newLevel.DaytimeEnemies;
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			for (int i = 0; i < levels.Length; i++)
			{
				AddEnemiesToLevel(enemies, levels[i].Enemies);
				AddEnemiesToLevel(outsideEnemies, levels[i].OutsideEnemies);
				AddEnemiesToLevel(daytimeEnemies, levels[i].DaytimeEnemies);
			}
			ChangeEnemyRarities(enemies, levelID, currentWeather);
			ChangeEnemyRarities(outsideEnemies, levelID, currentWeather);
			ChangeEnemyRarities(daytimeEnemies, levelID, currentWeather);
		}
	}
	public enum UsernameFilter
	{
		Default,
		Nothing
	}
	internal static class LobbySettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.LobbyConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the LobbyConfig executes. (NOT TESTED)");

		public static ConfigEntry<UsernameFilter> UsernameFiltering = UtilsMod.LobbyConfig.Bind("Lobby Settings", "UsernameFiltering", UsernameFilter.Default, "How names should be filtered.");
	}
	internal class LobbyPatch
	{
		[HarmonyPatch(typeof(PlayerControllerB), "NoPunctuation")]
		[HarmonyPrefix]
		public static bool PlayerNoPunctuation(ref string __result, string input)
		{
			if (LobbySettings.UsernameFiltering.Value == UsernameFilter.Default)
			{
				return true;
			}
			__result = input;
			return false;
		}

		[HarmonyPatch(typeof(GameNetworkManager), "NoPunctuation")]
		[HarmonyPrefix]
		public static bool NetworkNoPunctuation(ref string __result, string input)
		{
			if (LobbySettings.UsernameFiltering.Value == UsernameFilter.Default)
			{
				return true;
			}
			__result = input;
			return false;
		}

		[HarmonyPatch(typeof(StartOfRound), "NoPunctuation")]
		[HarmonyPrefix]
		public static bool RoundNoPunctuation(ref string __result, string input)
		{
			if (LobbySettings.UsernameFiltering.Value == UsernameFilter.Default)
			{
				return true;
			}
			__result = input;
			return false;
		}
	}
	public enum DoorInSpace
	{
		DoesNothing,
		OpenWithBarrier
	}
	internal static class ShipSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.ShipConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the ShipConfig executes.");

		public static ConfigEntry<DoorInSpace> DoorInSpaceOptions = UtilsMod.ShipConfig.Bind("Ship Settings", "DoorInSpace", DoorInSpace.DoesNothing, "Settings for the door while in space.");
	}
	internal class ShipPatch
	{
		[HarmonyPatch(typeof(HangarShipDoor), "PlayDoorAnimation")]
		[HarmonyPrefix]
		private static void SetPlayDoorAnimation(HangarShipDoor __instance, ref bool ___buttonsEnabled)
		{
			if (ShipSettings.DoorInSpaceOptions.Value != 0)
			{
				__instance.buttonsEnabled = true;
			}
		}
	}
	public enum UponDeathShipLoses
	{
		Nothing,
		ScrapOnly
	}
	internal static class RoundSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.RoundConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the RoundConfig executes.");

		public static ConfigEntry<UponDeathShipLoses> LoseUponDeath = UtilsMod.RoundConfig.Bind("Round Settings", "LoseUponDeath", UponDeathShipLoses.ScrapOnly, "What you lose when everybody dies.");
	}
	internal class RoundPatch
	{
		public static bool AllPlayersDead;

		[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
		[HarmonyPrefix]
		private static void PreSkipPropDespawn()
		{
			if (RoundSettings.LoseUponDeath.Value != UponDeathShipLoses.ScrapOnly)
			{
				AllPlayersDead = StartOfRound.Instance.allPlayersDead;
				StartOfRound.Instance.allPlayersDead = false;
			}
		}

		[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
		[HarmonyPostfix]
		private static void PostSkipPropDespawn()
		{
			if (RoundSettings.LoseUponDeath.Value == UponDeathShipLoses.ScrapOnly)
			{
				StartOfRound.Instance.allPlayersDead = AllPlayersDead;
			}
		}
	}
	public enum MonsterAggression
	{
		Hostile,
		OnlyVerbal,
		NonHostile
	}
	internal static class CompanySettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.CompanyConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the CompanyConfig executes.");

		public static ConfigEntry<MonsterAggression> SetMonsterAggression = UtilsMod.CompanyConfig.Bind("Company Settings", "SetMonsterAggression", MonsterAggression.Hostile, "Whether or not the monster will attack you.");

		public static ConfigEntry<bool> AlwaysFullBuyingRate = UtilsMod.CompanyConfig.Bind("Company Settings", "AlwaysFullBuyingRate", defaultValue: false, "Whether or not the Company is buying at full rate at all times.");

		public static ConfigEntry<float> BellCooldown = UtilsMod.CompanyConfig.Bind("Company Settings", "BellCooldown", 1f, new ConfigDescription("How long the cooldown is for ringing the bell. (You should make it 0 and spam until you die, yes yes.)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f)));

		public static ConfigEntry<float> GrabObjectsWaitTime = UtilsMod.CompanyConfig.Bind("Company Settings", "GrabObjectsWaitTime", 10f, new ConfigDescription("How long until the Company takes your stuff.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f)));
	}
	internal class CompanyPatch
	{
		[HarmonyPatch(typeof(DepositItemsDesk), "Start")]
		[HarmonyPrefix]
		private static void PatchDepositDesk(ref float ___grabObjectsWaitTime)
		{
			if (CompanySettings.GrabObjectsWaitTime.Value != 10f)
			{
				___grabObjectsWaitTime = CompanySettings.GrabObjectsWaitTime.Value;
			}
		}

		[HarmonyPatch(typeof(InteractTrigger), "Start")]
		[HarmonyPostfix]
		private static void PatchBellCooldown(InteractTrigger __instance, ref float ___cooldownTime, ref float ___currentCooldownValue)
		{
			if (CompanySettings.BellCooldown.Value != (float)CompanySettings.BellCooldown.DefaultValue && !((Object)(object)((Component)__instance).gameObject != (Object)(object)GameObject.Find("BellDinger/Trigger")))
			{
				___cooldownTime = CompanySettings.BellCooldown.Value;
				___currentCooldownValue = ___cooldownTime;
			}
		}

		[HarmonyPatch(typeof(TimeOfDay), "SetBuyingRateForDay")]
		[HarmonyPostfix]
		private static void SetBuyingRateForDay()
		{
			if (CompanySettings.AlwaysFullBuyingRate.Value)
			{
				StartOfRound.Instance.companyBuyingRate = 1f;
			}
		}

		[HarmonyPatch(typeof(DepositItemsDesk), "Attack")]
		[HarmonyPrefix]
		private static bool PatchPreAttack(DepositItemsDesk __instance)
		{
			if (CompanySettings.SetMonsterAggression.Value == MonsterAggression.OnlyVerbal)
			{
				__instance.timeSinceAttacking = 0f;
				__instance.patienceLevel += 6f;
				if (!__instance.doorOpen)
				{
					__instance.OpenShutDoor(true);
				}
				__instance.MakeLoudNoise(2);
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(DepositItemsDesk), "Update")]
		[HarmonyPostfix]
		private static void PatchDepositItems(ref float ___patienceLevel)
		{
			if (CompanySettings.SetMonsterAggression.Value == MonsterAggression.NonHostile)
			{
				___patienceLevel = 3f;
			}
		}
	}
	internal static class CharacterSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.CharacterConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the CharacterConfig executes.");

		public static ConfigEntry<bool> InfStamina = UtilsMod.CharacterConfig.Bind("Character Settings", "InfStamina", defaultValue: false, "Whether or not the player has infinite stamina.");

		public static ConfigEntry<bool> FallDamage = UtilsMod.CharacterConfig.Bind("Character Settings", "FallDamage", defaultValue: true, "Whether or not the player takes fall damage.");

		public static ConfigEntry<bool> ApplyMovementModifiers = UtilsMod.CharacterConfig.Bind("Movement Settings", "ApplyMovementModifiers", defaultValue: false, "Whether or not the Movement Settings apply.");

		public static ConfigEntry<float> WalkSpeed = UtilsMod.CharacterConfig.Bind("Movement Settings", "WalkSpeed", 4.6f, "Walking speed.");

		public static ConfigEntry<float> SprintTime = UtilsMod.CharacterConfig.Bind("Movement Settings", "SprintTime", 10f, "Sprint time.");

		public static ConfigEntry<float> SprintMultiplier = UtilsMod.CharacterConfig.Bind("Movement Settings", "SprintMultiplier", 2.25f, "Sprint walking speed multiplier.");

		public static ConfigEntry<float> ClimbSpeed = UtilsMod.CharacterConfig.Bind("Movement Settings", "ClimbSpeed", 4f, "Ladder climb speed.");

		public static ConfigEntry<float> FastClimbTime = UtilsMod.CharacterConfig.Bind("Movement Settings", "FastClimbTime", 10f, "Fast climbing time.");

		public static ConfigEntry<float> FastClimbMultiplier = UtilsMod.CharacterConfig.Bind("Movement Settings", "FastClimbMultiplier", 1f, "Fast climbing speed multiplier.");
	}
	internal class CharacterPatch
	{
		private static float PreviousSprintMeter = 1f;

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		private static void PatchPlayerPreUpdate(PlayerControllerB __instance)
		{
			PreviousSprintMeter = __instance.sprintMeter;
			if (CharacterSettings.ApplyMovementModifiers.Value)
			{
				__instance.sprintTime = CharacterSettings.SprintTime.Value;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void PatchPlayerUpdate(PlayerControllerB __instance, ref bool ___isWalking, ref float ___sprintMultiplier)
		{
			if (CharacterSettings.ApplyMovementModifiers.Value)
			{
				float num = PreviousSprintMeter - __instance.sprintMeter;
				if (___isWalking)
				{
					float value = CharacterSettings.WalkSpeed.Value;
					float num2 = (___sprintMultiplier - 1f) / 1.25f;
					float value2 = CharacterSettings.SprintMultiplier.Value;
					__instance.movementSpeed = (value + (value2 * value - value) * num2) / ___sprintMultiplier;
				}
				if (__instance.isClimbingLadder)
				{
					float num3 = CharacterSettings.ClimbSpeed.Value;
					if (__instance.isSprinting)
					{
						__instance.sprintMeter = Mathf.Clamp(PreviousSprintMeter - num * __instance.sprintTime / CharacterSettings.FastClimbTime.Value, 0f, 1f);
						num3 *= CharacterSettings.FastClimbMultiplier.Value;
					}
					if (num3 != 4f)
					{
						__instance.climbSpeed = num3;
					}
				}
			}
			if (CharacterSettings.InfStamina.Value)
			{
				__instance.sprintMeter = 1f;
			}
			if (!CharacterSettings.FallDamage.Value)
			{
				__instance.takingFallDamage = false;
			}
		}
	}
	internal static class GeneralSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.GeneralConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the GeneralConfig executes.");

		public static ConfigEntry<int> SaveItemCount = UtilsMod.GeneralConfig.Bind("General Settings", "SaveItemCount", 45, "The amount of items that save.");
	}
	internal class GeneralPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void PatchMaxItemCapacity(ref int ___maxShipItemCapacity)
		{
			if (GeneralSettings.SaveItemCount.Value != 45)
			{
				___maxShipItemCapacity = GeneralSettings.SaveItemCount.Value;
			}
		}

		[HarmonyPatch(typeof(InitializeGame), "Awake")]
		[HarmonyPrefix]
		private static void SkipBoot(ref bool ___runBootUpScreen)
		{
			___runBootUpScreen = false;
		}
	}
	public enum ClockType
	{
		Display12Hour,
		Display24Hour,
		DisplayMilitary
	}
	internal static class HUDSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.HUDConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the HUDConfig executes.");

		public static ConfigEntry<bool> ViewClockInShip = UtilsMod.HUDConfig.Bind("Clock Settings", "ViewClockInShip", defaultValue: false, "Whether or not people can view the clock inside the ship.");

		public static ConfigEntry<bool> ViewClockOutside = UtilsMod.HUDConfig.Bind("Clock Settings", "ViewClockOutside", defaultValue: true, "Whether or not people can view the clock outside. (You should make it false and suffer.)");

		public static ConfigEntry<bool> ViewClockInBuilding = UtilsMod.HUDConfig.Bind("Clock Settings", "ViewClockInBuilding", defaultValue: false, "Whether or not people can view the clock inside the building.");

		public static ConfigEntry<ClockType> TimeDisplay = UtilsMod.HUDConfig.Bind("Clock Settings", "TimeDisplay", ClockType.Display12Hour, "How the clock displays time.");
	}
	internal class HUDPatch
	{
		[HarmonyPatch(typeof(HUDManager), "SetClock")]
		[HarmonyPrefix]
		private static bool Patch24HourClock(ref TextMeshProUGUI ___clockNumber, ref float timeNormalized, ref float numberOfHours)
		{
			if (HUDSettings.TimeDisplay.Value == ClockType.Display12Hour)
			{
				return true;
			}
			int num = (int)(timeNormalized * (60f * numberOfHours)) + 360;
			int num2 = (int)Mathf.Floor((float)(num / 60));
			int num3 = num % 60;
			((TMP_Text)___clockNumber).text = string.Format("{0:00}{1}{2:00}", num2, (HUDSettings.TimeDisplay.Value == ClockType.Display24Hour) ? ":" : "", num3).TrimStart(new char[1] { '0' });
			return false;
		}

		[HarmonyPatch(typeof(TimeOfDay), "SetInsideLightingDimness")]
		[HarmonyPostfix]
		public static void PatchClockVisibility()
		{
			if (HUDSettings.ViewClockInShip.Value || !HUDSettings.ViewClockOutside.Value || HUDSettings.ViewClockInBuilding.Value)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (!localPlayerController.isPlayerDead)
				{
					bool isInsideFactory = localPlayerController.isInsideFactory;
					bool isInHangarShipRoom = localPlayerController.isInHangarShipRoom;
					bool clockVisible = (isInsideFactory && HUDSettings.ViewClockInBuilding.Value) || (isInHangarShipRoom && HUDSettings.ViewClockInShip.Value) || (!isInsideFactory && !isInHangarShipRoom && HUDSettings.ViewClockOutside.Value);
					HUDManager.Instance.SetClockVisible(clockVisible);
				}
			}
		}
	}
	internal static class MultipliersSettings
	{
	}
	internal class MultipliersPatch
	{
		private static float ScrapAmountMult = 1f;

		private static float ScrapValueMult = 0.4f;

		private static float DaySpeedMult = 1f;

		private static float TimeSpeedMult = 1.4f;

		[HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")]
		[HarmonyPrefix]
		private static void PatchLevelMultiplierSettings(RoundManager __instance)
		{
			//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_00e9: 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)
			float num = 1f;
			if (MapSettings.MapModifiersEnabled.Value)
			{
				num = MapSettings.MapScalar.Value;
				MapLevel levelID = (MapLevel)__instance.currentLevel.levelID;
				if (MapSettings.Settings.ContainsKey(levelID))
				{
					Dictionary<string, ConfigEntryBase> dictionary = MapSettings.Settings[levelID];
					num *= (dictionary["MapScalar"] as ConfigEntry<float>).Value;
				}
			}
			else
			{
				num = (float)MapSettings.MapScalar.DefaultValue;
				MapLevel levelID2 = (MapLevel)__instance.currentLevel.levelID;
				if (MapSettings.Settings.ContainsKey(levelID2))
				{
					Dictionary<string, ConfigEntryBase> dictionary2 = MapSettings.Settings[levelID2];
					num *= (float)(dictionary2["MapScalar"] as ConfigEntry<float>).DefaultValue;
				}
			}
			if (WeatherSettings.MapModifiersEnabled.Value)
			{
				LevelWeatherType currentWeather = __instance.currentLevel.currentWeather;
				if (WeatherSettings.Settings.ContainsKey(currentWeather))
				{
					Dictionary<string, ConfigEntryBase> dictionary3 = WeatherSettings.Settings[currentWeather];
					num *= (dictionary3["MapScalar"] as ConfigEntry<float>).Value;
				}
			}
			__instance.mapSizeMultiplier = Mathf.Max(num, 1f);
		}

		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		[HarmonyPrefix]
		private static void PatchMultiplierSettings(RoundManager __instance)
		{
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			MapLevel levelID = (MapLevel)__instance.currentLevel.levelID;
			if (MapSettings.ConfigEnabled.Value && MapSettings.ScrapModifiersEnabled.Value && MapSettings.Settings.ContainsKey(levelID))
			{
				Dictionary<string, ConfigEntryBase> dictionary = MapSettings.Settings[levelID];
				__instance.currentLevel.minScrap = ((ConfigEntry<int>)dictionary["MinScrapAmount"]).Value;
				__instance.currentLevel.maxScrap = ((ConfigEntry<int>)dictionary["MaxScrapAmount"]).Value;
			}
			if (MapSettings.ConfigEnabled.Value)
			{
				if (MapSettings.ScrapModifiersEnabled.Value)
				{
					ScrapAmountMult = MapSettings.ScrapAmountScalar.Value;
					ScrapValueMult = MapSettings.ScrapValueScalar.Value;
				}
				if (MapSettings.TimeModifiersEnabled.Value)
				{
					TimeSpeedMult = MapSettings.TimeSpeedScalar.Value;
					DaySpeedMult = MapSettings.DayScalar.Value;
				}
				if (MapSettings.Settings.ContainsKey(levelID))
				{
					Dictionary<string, ConfigEntryBase> dictionary2 = MapSettings.Settings[levelID];
					if (MapSettings.ScrapModifiersEnabled.Value)
					{
						ScrapAmountMult *= (dictionary2["ScrapAmountScalar"] as ConfigEntry<float>).Value;
						ScrapValueMult *= (dictionary2["ScrapValueScalar"] as ConfigEntry<float>).Value;
					}
					if (MapSettings.TimeModifiersEnabled.Value)
					{
						DaySpeedMult *= (dictionary2["DayScalar"] as ConfigEntry<float>).Value;
						TimeSpeedMult *= (dictionary2["TimeSpeedScalar"] as ConfigEntry<float>).Value;
					}
				}
			}
			if (WeatherSettings.ConfigEnabled.Value)
			{
				LevelWeatherType currentWeather = __instance.currentLevel.currentWeather;
				if (WeatherSettings.Settings.ContainsKey(currentWeather))
				{
					Dictionary<string, ConfigEntryBase> dictionary3 = WeatherSettings.Settings[currentWeather];
					if (WeatherSettings.ScrapModifiersEnabled.Value)
					{
						ScrapAmountMult *= (dictionary3["ScrapAmountScalar"] as ConfigEntry<float>).Value;
						ScrapValueMult *= (dictionary3["ScrapValueScalar"] as ConfigEntry<float>).Value;
					}
					if (WeatherSettings.TimeModifiersEnabled.Value)
					{
						DaySpeedMult *= (dictionary3["DayScalar"] as ConfigEntry<float>).Value;
						TimeSpeedMult *= (dictionary3["TimeSpeedScalar"] as ConfigEntry<float>).Value;
					}
				}
			}
			if (WeatherSettings.ScrapModifiersEnabled.Value || MapSettings.ScrapModifiersEnabled.Value)
			{
				__instance.scrapAmountMultiplier = ScrapAmountMult;
				__instance.scrapValueMultiplier = ScrapValueMult;
			}
			if (WeatherSettings.TimeModifiersEnabled.Value || MapSettings.TimeModifiersEnabled.Value)
			{
				__instance.currentLevel.DaySpeedMultiplier = DaySpeedMult;
				__instance.timeScript.globalTimeSpeedMultiplier = TimeSpeedMult;
			}
		}

		[HarmonyPatch(typeof(LungProp), "DisconnectFromMachinery")]
		[HarmonyPostfix]
		private static void FixApparatusScrapValMult(LungProp __instance)
		{
			((GrabbableObject)__instance).SetScrapValue((int)((float)((GrabbableObject)__instance).scrapValue * RoundManager.Instance.scrapValueMultiplier / 0.4f));
		}
	}
	internal static class GearSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.GearConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the GearConfig executes.");

		public static ConfigEntry<bool> InfFlashlight = UtilsMod.GearConfig.Bind("Flashlight Settings", "InfFlashlight", defaultValue: false, "Whether or not the flashlight has infinite energy.");

		public static ConfigEntry<bool> InfProFlashlight = UtilsMod.GearConfig.Bind("Flashlight Settings", "InfProFlashlight", defaultValue: false, "Whether or not the pro flashlight has infinite energy.");

		public static ConfigEntry<bool> InfWalkie = UtilsMod.GearConfig.Bind("Walkie Talkie Settings", "InfWalkie", defaultValue: false, "Whether or not the walkie has infinite energy.");

		public static ConfigEntry<bool> InfPaint = UtilsMod.GearConfig.Bind("Spray Paint Settings", "InfPaint", defaultValue: false, "Whether or not the spray paint is infinite.");

		public static ConfigEntry<bool> RequireShaking = UtilsMod.GearConfig.Bind("Spray Paint Settings", "RequireShaking", defaultValue: true, "Whether or not the spray paint needs to be shook.");

		public static ConfigEntry<float> PaintSpeed = UtilsMod.GearConfig.Bind("Spray Paint Settings", "PaintSpeed", 0.2f, "Interval at which the paint decals apply.");

		public static ConfigEntry<int> MaxPaintDecals = UtilsMod.GearConfig.Bind("Spray Paint Settings", "MaxPaintDecals", 1000, "How many spray paint decals stay at once.");

		public static ConfigEntry<bool> InfBoombox = UtilsMod.GearConfig.Bind("Boombox Settings", "InfBoombox", defaultValue: false, "Whether or not the boombox has infinite energy.");

		public static ConfigEntry<bool> PocketBoombox = UtilsMod.GearConfig.Bind("Boombox Settings", "PocketBoombox", defaultValue: false, "Whether or not the boombox continues to play when put away.");

		public static ConfigEntry<bool> GroundBoombox = UtilsMod.GearConfig.Bind("Boombox Settings", "GroundBoombox", defaultValue: true, "Whether or not the boombox continues to play when thrown down.");

		public static ConfigEntry<bool> ReusableUnlockKeys = UtilsMod.GearConfig.Bind("Key Settings", "ReusableUnlockKeys", defaultValue: false, "Whether or not the key is reusable for unlocking.");

		public static ConfigEntry<bool> ReusableLockKeys = UtilsMod.GearConfig.Bind("Key Settings", "ReusableLockKeys", defaultValue: false, "Whether or not the key is reusable for locking.");

		public static ConfigEntry<bool> KeysCanLockDoors = UtilsMod.GearConfig.Bind("Key Settings", "KeysCanLockDoors", defaultValue: false, "Whether or not the key can lock doors.");
	}
	internal class GearPatch
	{
		public static bool BoomboxBeingPocketed;

		[HarmonyPatch(typeof(DoorLock), "UnlockDoor")]
		[HarmonyPrefix]
		private static bool PatchUnlockDoor(ref DoorLock __instance, ref bool ___isDoorOpened)
		{
			if (__instance.isLocked || !GearSettings.KeysCanLockDoors.Value)
			{
				return true;
			}
			if (___isDoorOpened)
			{
				return false;
			}
			__instance.doorLockSFX.PlayOneShot(__instance.unlockSFX);
			__instance.LockDoor(30f);
			return false;
		}

		[HarmonyPatch(typeof(DoorLock), "Update")]
		[HarmonyPrefix]
		private static void PreLockpickDoor(ref DoorLock __instance, ref InteractTrigger ___doorTrigger, out bool __state)
		{
			__state = false;
			if (__instance.isLocked && __instance.isPickingLock && GearSettings.KeysCanLockDoors.Value)
			{
				__state = true;
				__instance.isPickingLock = false;
			}
		}

		[HarmonyPatch(typeof(DoorLock), "Update")]
		[HarmonyPostfix]
		private static void PostLockpickDoor(ref DoorLock __instance, ref InteractTrigger ___doorTrigger, bool __state)
		{
			if (__state)
			{
				DoorLock obj = __instance;
				obj.lockPickTimeLeft -= Time.deltaTime;
				___doorTrigger.disabledHoverTip = $"Picking lock: {(int)__instance.lockPickTimeLeft} sec.";
				if (((NetworkBehaviour)__instance).IsServer && __instance.lockPickTimeLeft < 0f)
				{
					__instance.UnlockDoorServerRpc();
				}
				__instance.isPickingLock = true;
			}
		}

		[HarmonyPatch(typeof(DoorLock), "UnlockDoorSyncWithServer")]
		[HarmonyPrefix]
		private static bool UnlockDoorSyncWithServer(ref DoorLock __instance)
		{
			if (!GearSettings.KeysCanLockDoors.Value)
			{
				return true;
			}
			if (__instance.isLocked)
			{
				__instance.UnlockDoorServerRpc();
			}
			return false;
		}

		[HarmonyPatch(typeof(KeyItem), "ItemActivate")]
		[HarmonyPrefix]
		private static bool ItemActivatePatch(ref KeyItem __instance)
		{
			//IL_004e: 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)
			if (!GearSettings.KeysCanLockDoors.Value)
			{
				return true;
			}
			PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy;
			if (!Object.op_Implicit((Object)(object)playerHeldBy) || !((NetworkBehaviour)__instance).IsOwner)
			{
				return false;
			}
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(new Ray(((Component)playerHeldBy.gameplayCamera).transform.position, ((Component)playerHeldBy.gameplayCamera).transform.forward), ref val, 3f, 2816))
			{
				DoorLock component = ((Component)((RaycastHit)(ref val)).transform).GetComponent<DoorLock>();
				if (!Object.op_Implicit((Object)(object)component) || component.isPickingLock)
				{
					return false;
				}
				if (!component.isLocked && !GearSettings.KeysCanLockDoors.Value)
				{
					return false;
				}
				component.UnlockDoorServerRpc();
				if ((component.isLocked && !GearSettings.ReusableUnlockKeys.Value) || !GearSettings.ReusableLockKeys.Value)
				{
					playerHeldBy.DespawnHeldObject();
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(WalkieTalkie), "Start")]
		[HarmonyPostfix]
		private static void PatchInfWalkie(ref Item ___itemProperties)
		{
			if (GearSettings.InfWalkie.Value)
			{
				___itemProperties.requiresBattery = false;
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "Start")]
		[HarmonyPostfix]
		private static void PatchInfFlashlight(ref Item ___itemProperties)
		{
			if (!((___itemProperties.itemId == 1) ? (!GearSettings.InfProFlashlight.Value) : (!GearSettings.InfFlashlight.Value)))
			{
				___itemProperties.requiresBattery = false;
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem), "Start")]
		[HarmonyPostfix]
		private static void PatchPaintStart(ref Item ___itemProperties, SprayPaintItem __instance)
		{
			__instance.sprayIntervalSpeed = GearSettings.PaintSpeed.Value;
			__instance.maxSprayPaintDecals = GearSettings.MaxPaintDecals.Value;
		}

		[HarmonyPatch(typeof(SprayPaintItem), "LateUpdate")]
		[HarmonyPostfix]
		private static void PatchInfPaint(ref float ___sprayCanTank, ref float ___sprayCanShakeMeter)
		{
			if (GearSettings.InfPaint.Value)
			{
				___sprayCanTank = 1f;
			}
			if (GearSettings.RequireShaking.Value)
			{
				___sprayCanShakeMeter = 1f;
			}
		}

		[HarmonyPatch(typeof(BoomboxItem), "Start")]
		[HarmonyPostfix]
		private static void PatchInfBoombox(ref Item ___itemProperties)
		{
			if (GearSettings.InfBoombox.Value)
			{
				___itemProperties.requiresBattery = false;
			}
		}

		[HarmonyPatch(typeof(BoomboxItem), "PocketItem")]
		[HarmonyPrefix]
		private static void PatchPocketBoombox()
		{
			if (GearSettings.PocketBoombox.Value)
			{
				BoomboxBeingPocketed = true;
			}
		}

		[HarmonyPatch(typeof(BoomboxItem), "StartMusic")]
		[HarmonyPrefix]
		private static bool PatchStartMusic()
		{
			if (GearSettings.PocketBoombox.Value && BoomboxBeingPocketed)
			{
				BoomboxBeingPocketed = false;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SetObjectAsNoLongerHeld")]
		[HarmonyPrefix]
		private static void PatchSetObjectAsNoLongerHeld(ref GrabbableObject dropObject)
		{
			if (!GearSettings.GroundBoombox.Value && dropObject is BoomboxItem)
			{
				dropObject.ItemActivate(false, true);
			}
		}
	}
	public enum ItemsOnTPOptions
	{
		Drop,
		DropExceptGear,
		DropExceptGearAndHeldItem,
		DropExceptHeldItem,
		DontDrop
	}
	internal static class TeleportSettings
	{
		public static ConfigEntry<bool> ConfigEnabled = UtilsMod.TeleportConfig.Bind("Active Settings", "ConfigEnabled", defaultValue: false, "Whether or not the TeleportConfig executes.");

		public static ConfigEntry<ItemsOnTPOptions> ItemsOnTP = UtilsMod.TeleportConfig.Bind("TP Settings", "ItemsOnTP", ItemsOnTPOptions.Drop, "Whether or not you keep your items upon teleportation.");

		public static ConfigEntry<int> CooldownTP = UtilsMod.TeleportConfig.Bind("TP Settings", "CooldownTP", 10, "How long until you can use the teleporter.");

		public static ConfigEntry<ItemsOnTPOptions> ItemsOnInverseTP = UtilsMod.TeleportConfig.Bind("TP Settings", "ItemsOnInverseTP", ItemsOnTPOptions.Drop, "Whether or not you keep your items upon inverse teleportation.");

		public static ConfigEntry<int> CooldownInverseTP = UtilsMod.TeleportConfig.Bind("TP Settings", "CooldownInverseTP", 210, "How long until you can use the inverse teleporter.");
	}
	internal class TeleportPatch
	{
		[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
		[HarmonyPrefix]
		private static void PostShipTPAwake(ref float ___cooldownAmount, ref float ___cooldownTime, ref bool ___isInverseTeleporter)
		{
			int num = (___isInverseTeleporter ? TeleportSettings.CooldownInverseTP.Value : TeleportSettings.CooldownTP.Value);
			if (!(___isInverseTeleporter ? (num == 210) : (num == 10)))
			{
				___cooldownAmount = num;
				___cooldownTime = ___cooldownAmount;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DropAllHeldItems")]
		[HarmonyPrefix]
		private static bool PreDropAllHeldItems(PlayerControllerB __instance, out GrabbableObject[] __state)
		{
			__state = (GrabbableObject[])(object)new GrabbableObject[__instance.ItemSlots.Length];
			int shipTeleporterId = __instance.shipTeleporterId;
			bool flag = shipTeleporterId == 1;
			bool flag2 = shipTeleporterId == 2;
			if (!flag && !flag2)
			{
				return true;
			}
			ItemsOnTPOptions itemsOnTPOptions = (flag2 ? TeleportSettings.ItemsOnInverseTP.Value : TeleportSettings.ItemsOnTP.Value);
			int num;
			switch (itemsOnTPOptions)
			{
			case ItemsOnTPOptions.Drop:
				return true;
			case ItemsOnTPOptions.DontDrop:
				return false;
			default:
				num = ((itemsOnTPOptions == ItemsOnTPOptions.DropExceptGearAndHeldItem) ? 1 : 0);
				break;
			case ItemsOnTPOptions.DropExceptHeldItem:
				num = 1;
				break;
			}
			bool flag3 = (byte)num != 0;
			bool flag4 = itemsOnTPOptions == ItemsOnTPOptions.DropExceptGear || itemsOnTPOptions == ItemsOnTPOptions.DropExceptGearAndHeldItem;
			for (int i = 0; i < __instance.ItemSlots.Length; i++)
			{
				GrabbableObject val = __instance.ItemSlots[i];
				if (Object.op_Implicit((Object)(object)val) && ((flag3 && !val.isPocketed) || (flag4 && (val is ExtensionLadderItem || val is JetpackItem || val is KeyItem || val is RadarBoosterItem || val is RemoteProp || val is BoomboxItem || val is ClipboardItem || val is FlashlightItem || val is LockPicker || val is MapDevice || val is Shovel || val is WalkieTalkie || val is StunGrenadeItem || val is TetraChemicalItem || val is ShotgunItem || val is HauntedMaskItem || val is GunAmmo || val is WhoopieCushionItem || val is SprayPaintItem))))
				{
					__state[i] = val;
					__instance.ItemSlots[i] = null;
				}
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DropAllHeldItems")]
		[HarmonyPostfix]
		private static void PostDropAllHeldItems(PlayerControllerB __instance, GrabbableObject[] __state)
		{
			for (int i = 0; i < __state.Length; i++)
			{
				GrabbableObject val = __state[i];
				if (Object.op_Implicit((Object)(object)val))
				{
					__instance.ItemSlots[i] = val;
					__state[i] = null;
				}
			}
		}

		[HarmonyPatch(typeof(ShipTeleporter), "TeleportPlayerOutWithInverseTeleporter")]
		[HarmonyPrefix]
		private static bool TeleportPlayerOutWithInverseTeleporter(ShipTeleporter __instance, ref int[] ___playersBeingTeleported, int playerObj, Vector3 teleportPos)
		{
			//IL_0085: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerObj];
			if (val.isPlayerDead)
			{
				return true;
			}
			val.DropAllHeldItems(true, false);
			val.shipTeleporterId = -1;
			___playersBeingTeleported[val.playerClientId] = (int)val.playerClientId;
			if (Object.op_Implicit((Object)(object)Object.FindObjectOfType<AudioReverbPresets>()))
			{
				Object.FindObjectOfType<AudioReverbPresets>().audioPresets[2].ChangeAudioReverbForPlayer(val);
			}
			val.isInElevator = false;
			val.isInHangarShipRoom = false;
			val.isInsideFactory = true;
			val.averageVelocity = 0f;
			val.velocityLastFrame = Vector3.zero;
			val.TeleportPlayer(teleportPos, false, 0f, false, true);
			val.beamOutParticle.Play();
			__instance.shipTeleporterAudio.PlayOneShot(__instance.teleporterBeamUpSFX);
			val.movementAudio.PlayOneShot(__instance.teleporterBeamUpSFX);
			if ((Object)(object)val == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				Debug.Log((object)"Teleporter shaking camera");
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			return false;
		}
	}
	[BepInPlugin("Kyxino.LethalUtils", "LethalUtilities", "1.2.14")]
	public class UtilsMod : BaseUnityPlugin
	{
		public const bool DEBUGGINGMODE = false;

		private const string ModGUID = "Kyxino.LethalUtils";

		private const string ModName = "LethalUtilities";

		private const string ModVersion = "1.2.14";

		private const string ModWebsite = "https://discord.gg/rzQcgRDQw3";

		private const string ModDescription = "(No longer includes config due to overwriting, please run game once to load.) Customize all kinds of things like your gear, sprint, teleporters, map/weather multipliers for spawn chances and scrap value/amount, and more!";

		public static BepInPlugin Metadata = MetadataHelper.GetMetadata(typeof(UtilsMod));

		private string[] Dependencies = new string[1] { "BepInEx-BepInExPack-5.4.2100" };

		private readonly Harmony harmony = new Harmony("Kyxino.LethalUtils");

		public static ManualLogSource MLS;

		public static ConfigFile GeneralConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\GeneralSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile RoundConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\RoundSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile CompanyConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\CompanySettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile HUDConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\HUDSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile CharacterConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\CharacterSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile TeleportConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\TeleportSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile GearConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\GearSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile MapConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\MapSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile WeatherConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\WeatherSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile ShipConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\ShipSettings.cfg", saveOnInit: true, Metadata);

		public static ConfigFile LobbyConfig = new ConfigFile(Paths.ConfigPath + "\\LethalUtilities\\LobbySettings.cfg", saveOnInit: true, Metadata);

		public static ConfigEntry<string> MODVERSION = GeneralConfig.Bind("Active Settings", "ModVersion", "1.2.14", "Version of the mod from which the configs were saved.");

		public static ConfigEntry<T> ConfigTransfer<T>(ConfigFile FromConfigFile, ConfigFile ToConfigFile, ConfigDefinition FromDefinition, ConfigDefinition ToDefinition, T DefaultValue, ConfigDescription Description)
		{
			ConfigEntry<T> configEntry = FromConfigFile.Bind(FromDefinition, DefaultValue);
			ConfigEntry<T> configEntry2 = ToConfigFile.Bind(ToDefinition, DefaultValue, Description);
			if (!configEntry.Value.Equals((T)configEntry.DefaultValue) && configEntry2.Value.Equals((T)configEntry2.DefaultValue))
			{
				configEntry2.Value = configEntry.Value;
				if (FromConfigFile != ToConfigFile)
				{
					ToConfigFile.Save();
				}
			}
			FromConfigFile.Remove(FromDefinition);
			FromConfigFile.Save();
			return configEntry2;
		}

		public static ConfigEntry<T> ConfigTransfer<T>(ConfigFile FromConfigFile, ConfigFile ToConfigFile, string FromCategory, string FromVariable, string ToCategory, string ToVariable, T DefaultValue, string Description)
		{
			return ConfigTransfer(FromConfigFile, ToConfigFile, new ConfigDefinition(FromCategory, FromVariable), new ConfigDefinition(ToCategory, ToVariable), DefaultValue, new ConfigDescription(Description, null));
		}

		public static ConfigEntry<T> ConfigTransfer<T>(ConfigFile ConfigFile, string FromCategory, string FromVariable, string ToCategory, string ToVariable, T DefaultValue, string Description)
		{
			return ConfigTransfer(ConfigFile, ConfigFile, new ConfigDefinition(FromCategory, FromVariable), new ConfigDefinition(ToCategory, ToVariable), DefaultValue, new ConfigDescription(Description, null));
		}

		public static ConfigEntry<T> ConfigTransfer<T>(ConfigFile ConfigFile, ConfigDefinition FromDefinition, ConfigDefinition ToDefinition, T DefaultValue, string Description)
		{
			return ConfigTransfer(ConfigFile, ConfigFile, FromDefinition, ToDefinition, DefaultValue, new ConfigDescription(Description, null));
		}

		public static ConfigEntry<T> ConfigTransfer<T>(ConfigFile ConfigFile, string Category, string FromVariable, string ToVariable, T DefaultValue, string Description)
		{
			return ConfigTransfer(ConfigFile, ConfigFile, new ConfigDefinition(Category, FromVariable), new ConfigDefinition(Category, ToVariable), DefaultValue, new ConfigDescription(Description, null));
		}

		private void Awake()
		{
			MLS = Logger.CreateLogSource("Kyxino.LethalUtils");
			bool flag = false;
			if (Directory.Exists(Paths.PluginPath + "\\kyxino-LethalUtilities\\config"))
			{
				Directory.Delete(Paths.PluginPath + "\\kyxino-LethalUtilities\\config", recursive: true);
			}
			MLS.LogInfo((object)"Loading all settings.");
			MLS.LogInfo((object)"YEEEEEEEET");
			if (GeneralSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(GeneralPatch));
			}
			if (RoundSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(RoundPatch));
			}
			if (CompanySettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(CompanyPatch));
			}
			if (HUDSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(HUDPatch));
			}
			if (CharacterSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(CharacterPatch));
			}
			if (TeleportSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(TeleportPatch));
			}
			if (GearSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(GearPatch));
			}
			if (MapSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(MapPatch));
			}
			if (WeatherSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(WeatherPatch));
			}
			if (MapSettings.ConfigEnabled.Value || WeatherSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(MultipliersPatch));
				if (MapSettings.SpawnModifiersEnabled.Value || WeatherSettings.SpawnModifiersEnabled.Value)
				{
					harmony.PatchAll(typeof(SpawnPatch));
				}
			}
			if (ShipSettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(ShipPatch));
			}
			if (LobbySettings.ConfigEnabled.Value)
			{
				harmony.PatchAll(typeof(LobbyPatch));
			}
			MLS.LogInfo((object)"All enabled patches have been executed.");
			GeneralConfig.Bind("Active Settings", "ModVersion", "1.2.14", "Version of the mod from which the configs were saved.").Value = "1.2.14";
			GeneralConfig.Save();
			MLS.LogInfo((object)"Saved mod version to GeneralConfig.");
		}
	}
}
namespace LethalUtilities.Configuration
{
	public sealed class SettingChangedEventArgs : EventArgs
	{
		public ConfigEntryBase ChangedSetting { get; }

		public SettingChangedEventArgs(ConfigEntryBase changedSetting)
		{
			ChangedSetting = changedSetting;
		}
	}
	public class ConfigDescription
	{
		public string Description { get; }

		public AcceptableValueBase AcceptableValues { get; }

		public object[] Tags { get; }

		public static ConfigDescription Empty { get; } = new ConfigDescription("", null);


		public ConfigDescription(string description, AcceptableValueBase acceptableValues = null, params object[] tags)
		{
			AcceptableValues = acceptableValues;
			Tags = tags;
			Description = description ?? throw new ArgumentNullException("description");
		}
	}
	public class ConfigDefinition : IEquatable<ConfigDefinition>
	{
		private static readonly char[] _invalidConfigChars = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' };

		public int Order { get; }

		public string Section { get; }

		public string Key { get; }

		public ConfigDefinition(string section, string key, int order = -1)
		{
			CheckInvalidConfigChars(section, "section");
			CheckInvalidConfigChars(key, "key");
			Order = order;
			Key = key;
			Section = section;
		}

		private static void CheckInvalidConfigChars(string val, string name)
		{
			if (val == null)
			{
				throw new ArgumentNullException(name);
			}
			if (val != val.Trim())
			{
				throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names", name);
			}
			if (val.Any((char c) => _invalidConfigChars.Contains(c)))
			{
				throw new ArgumentException("Cannot use any of the following characters in section and key names: = \\n \\t \\ \" ' [ ]", name);
			}
		}

		public bool Equals(ConfigDefinition other)
		{
			if (other == null)
			{
				return false;
			}
			if (string.Equals(Key, other.Key))
			{
				return string.Equals(Section, other.Section);
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (this == (ConfigDefinition)obj)
			{
				return true;
			}
			return Equals(obj as ConfigDefinition);
		}

		public override int GetHashCode()
		{
			return (((Key != null) ? Key.GetHashCode() : 0) * 397) ^ ((Section != null) ? Section.GetHashCode() : 0);
		}

		public static bool operator ==(ConfigDefinition left, ConfigDefinition right)
		{
			return object.Equals(left, right);
		}

		public static bool operator !=(ConfigDefinition left, ConfigDefinition right)
		{
			return !object.Equals(left, right);
		}

		public override string ToString()
		{
			return Section + "." + Key;
		}
	}
	public abstract class ConfigEntryBase
	{
		public ConfigFile ConfigFile { get; }

		public ConfigDefinition Definition { get; }

		public ConfigDescription Description { get; }

		public Type SettingType { get; }

		public object DefaultValue { get; }

		public abstract object BoxedValue { get; set; }

		internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue, ConfigDescription configDescription)
		{
			ConfigFile = configFile ?? throw new ArgumentNullException("configFile");
			Definition = definition ?? throw new ArgumentNullException("definition");
			SettingType = settingType ?? throw new ArgumentNullException("settingType");
			Description = configDescription ?? ConfigDescription.Empty;
			if (Description.AcceptableValues != null && !SettingType.IsAssignableFrom(Description.AcceptableValues.ValueType))
			{
				throw new ArgumentException("configDescription.AcceptableValues is for a different type than the type of this setting");
			}
			DefaultValue = defaultValue;
			BoxedValue = defaultValue;
		}

		public string GetSerializedValue()
		{
			return TomlTypeConverter.ConvertToString(BoxedValue, SettingType);
		}

		public void SetSerializedValue(string value)
		{
			try
			{
				object boxedValue = TomlTypeConverter.ConvertToValue(value, SettingType);
				BoxedValue = boxedValue;
			}
			catch (Exception ex)
			{
				UtilsMod.MLS.Log((LogLevel)4, (object)$"Config value of setting \"{Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
			}
		}

		protected T ClampValue<T>(T value)
		{
			if (Description.AcceptableValues != null)
			{
				return (T)Description.AcceptableValues.Clamp((object)value);
			}
			return value;
		}

		protected void OnSettingChanged(object sender)
		{
			ConfigFile.OnSettingChanged(sender, this);
		}

		public void WriteDescription(StreamWriter writer)
		{
			if (!string.IsNullOrEmpty(Description.Description))
			{
				writer.WriteLine("## " + Description.Description.Replace("\n", "\n## "));
			}
			string text = ((typeof(List<>).Name == SettingType.Name && SettingType.GenericTypeArguments.Length != 0) ? ("List<" + SettingType.GenericTypeArguments[0].Name + ">") : SettingType.Name);
			writer.WriteLine("# Setting type: " + text);
			writer.WriteLine("# Default value: " + TomlTypeConverter.ConvertToString(DefaultValue, SettingType));
			if (Description.AcceptableValues != null)
			{
				writer.WriteLine(Description.AcceptableValues.ToDescriptionString());
			}
			else if (SettingType.IsEnum)
			{
				writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(SettingType)));
				if (SettingType.GetCustomAttributes(typeof(FlagsAttribute), inherit: true).Any())
				{
					writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)");
				}
			}
		}
	}
	public sealed class ConfigEntry<T> : ConfigEntryBase
	{
		private T _typedValue;

		public T Value
		{
			get
			{
				return _typedValue;
			}
			set
			{
				value = ClampValue(value);
				if (!object.Equals(_typedValue, value))
				{
					_typedValue = value;
					OnSettingChanged(this);
				}
			}
		}

		public override object BoxedValue
		{
			get
			{
				return Value;
			}
			set
			{
				Value = (T)value;
			}
		}

		public event EventHandler SettingChanged;

		internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription configDescription)
			: base(configFile, definition, typeof(T), defaultValue, configDescription)
		{
			configFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args)
			{
				if (args.ChangedSetting == this)
				{
					this.SettingChanged?.Invoke(sender, args);
				}
			};
		}

		internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue, ConfigDescription configDescription)
			: base(configFile, definition, settingType, defaultValue, configDescription)
		{
			configFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args)
			{
				if (args.ChangedSetting == this)
				{
					this.SettingChanged?.Invoke(sender, args);
				}
			};
		}
	}
	public class ConfigFile : IDictionary<ConfigDefinition, ConfigEntryBase>, ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable
	{
		private readonly BepInPlugin _ownerMetadata;

		private readonly object _ioLock = new object();

		internal static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath, saveOnInit: true);


		protected Dictionary<ConfigDefinition, ConfigEntryBase> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntryBase>();


		private Dictionary<ConfigDefinition, string> OrphanedEntries { get; } = new Dictionary<ConfigDefinition, string>();


		public string ConfigFilePath { get; }

		public bool SaveOnConfigSet { get; set; } = true;


		public int Count
		{
			get
			{
				lock (_ioLock)
				{
					return Entries.Count;
				}
			}
		}

		public bool IsReadOnly => false;

		ConfigEntryBase IDictionary<ConfigDefinition, ConfigEntryBase>.this[ConfigDefinition key]
		{
			get
			{
				lock (_ioLock)
				{
					return Entries[key];
				}
			}
			set
			{
				throw new InvalidOperationException("Directly setting a config entry is not supported");
			}
		}

		public ConfigEntryBase this[ConfigDefinition key]
		{
			get
			{
				lock (_ioLock)
				{
					return Entries[key];
				}
			}
		}

		public ConfigEntryBase this[string section, string key] => this[new ConfigDefinition(section, key)];

		public ICollection<ConfigDefinition> Keys
		{
			get
			{
				lock (_ioLock)
				{
					return Entries.Keys.ToArray();
				}
			}
		}

		ICollection<ConfigEntryBase> IDictionary<ConfigDefinition, ConfigEntryBase>.Values
		{
			get
			{
				lock (_ioLock)
				{
					return Entries.Values.ToArray();
				}
			}
		}

		public event EventHandler ConfigReloaded;

		public event EventHandler<SettingChangedEventArgs> SettingChanged;

		public ConfigFile(string configPath, bool saveOnInit)
			: this(configPath, saveOnInit, null)
		{
		}

		public ConfigFile(string configPath, bool saveOnInit, BepInPlugin ownerMetadata)
		{
			_ownerMetadata = ownerMetadata;
			if (configPath == null)
			{
				throw new ArgumentNullException("configPath");
			}
			configPath = Path.GetFullPath(configPath);
			ConfigFilePath = configPath;
			if (File.Exists(ConfigFilePath))
			{
				Reload();
			}
			else if (saveOnInit)
			{
				Save();
			}
		}

		public void Reload()
		{
			lock (_ioLock)
			{
				OrphanedEntries.Clear();
				string section = string.Empty;
				string[] array = File.ReadAllLines(ConfigFilePath);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.StartsWith("#"))
					{
						continue;
					}
					if (text.StartsWith("[") && text.EndsWith("]"))
					{
						section = text.Substring(1, text.Length - 2);
						continue;
					}
					string[] array2 = text.Split(new char[1] { '=' }, 2);
					if (array2.Length == 2)
					{
						string key = array2[0].Trim();
						string text2 = array2[1].Trim();
						ConfigDefinition key2 = new ConfigDefinition(section, key);
						Entries.TryGetValue(key2, out var value);
						if (value != null)
						{
							value.SetSerializedValue(text2);
						}
						else
						{
							OrphanedEntries[key2] = text2;
						}
					}
				}
			}
			OnConfigReloaded();
		}

		public void Save()
		{
			lock (_ioLock)
			{
				string directoryName = Path.GetDirectoryName(ConfigFilePath);
				if (directoryName != null)
				{
					Directory.CreateDirectory(directoryName);
				}
				using StreamWriter streamWriter = new StreamWriter(ConfigFilePath, append: false, Utility.UTF8NoBom);
				if (_ownerMetadata != null)
				{
					streamWriter.WriteLine($"## Settings file was created by plugin {_ownerMetadata.Name} v{_ownerMetadata.Version}");
					streamWriter.WriteLine("## Plugin GUID: " + _ownerMetadata.GUID);
					streamWriter.WriteLine();
				}
				foreach (var item in from x in Entries.Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> x) => new
					{
						Key = x.Key,
						entry = x.Value,
						value = x.Value.GetSerializedValue()
					}).Concat(OrphanedEntries.Select((KeyValuePair<ConfigDefinition, string> x) => new
					{
						Key = x.Key,
						entry = (ConfigEntryBase)null,
						value = x.Value
					}))
					group x by (x.Key.Order, x.Key.Section) into x
					orderby x.Key.Order == -1, x.Key.Order, x.Key.Section
					select x)
				{
					streamWriter.WriteLine("[" + item.Key.Item2 + "]");
					foreach (var item2 in item)
					{
						streamWriter.WriteLine();
						item2.entry?.WriteDescription(streamWriter);
						streamWriter.WriteLine(item2.Key.Key + " = " + item2.value);
					}
					streamWriter.WriteLine();
				}
			}
		}

		public bool TryGetEntry<T>(ConfigDefinition configDefinition, out ConfigEntry<T> entry)
		{
			lock (_ioLock)
			{
				if (Entries.TryGetValue(configDefinition, out var value))
				{
					entry = (ConfigEntry<T>)value;
					return true;
				}
				entry = null;
				return false;
			}
		}

		public bool TryGetEntry<T>(string section, string key, out ConfigEntry<T> entry)
		{
			return TryGetEntry(new ConfigDefinition(section, key), out entry);
		}

		public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, Type settingType, T defaultValue, ConfigDescription configDescription = null)
		{
			if (!TomlTypeConverter.CanConvert(settingType))
			{
				throw new ArgumentException(string.Format("Type {0} is not supported by the config system. Supported types: {1}", settingType, string.Join(", ", (from x in TomlTypeConverter.GetSupportedTypes()
					select x.Name).ToArray())));
			}
			lock (_ioLock)
			{
				if (Entries.TryGetValue(configDefinition, out var value))
				{
					return (ConfigEntry<T>)value;
				}
				ConfigEntry<T> configEntry = new ConfigEntry<T>(this, configDefinition, settingType, defaultValue, configDescription);
				Entries[configDefinition] = configEntry;
				if (OrphanedEntries.TryGetValue(configDefinition, out var value2))
				{
					configEntry.SetSerializedValue(value2);
					OrphanedEntries.Remove(configDefinition);
				}
				if (SaveOnConfigSet)
				{
					Save();
				}
				return configEntry;
			}
		}

		public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null)
		{
			return Bind(configDefinition, typeof(T), defaultValue, configDescription);
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null, int order = -1)
		{
			return Bind(new ConfigDefinition(section, key, order), defaultValue, configDescription);
		}

		public ConfigEntry<T> Bind<T>(string section, string key, Type settingType, T defaultValue, ConfigDescription configDescription = null, int order = -1)
		{
			return Bind(new ConfigDefinition(section, key, order), settingType, defaultValue, configDescription);
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description, int order = -1)
		{
			return Bind(new ConfigDefinition(section, key, order), defaultValue, new ConfigDescription(description, null));
		}

		public ConfigEntry<T> Bind<T>(string section, string key, Type settingType, T defaultValue, string description, int order = -1)
		{
			return Bind(new ConfigDefinition(section, key, order), settingType, defaultValue, new ConfigDescription(description, null));
		}

		internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase)
		{
			if (changedEntryBase == null)
			{
				throw new ArgumentNullException("changedEntryBase");
			}
			if (SaveOnConfigSet)
			{
				Save();
			}
			EventHandler<SettingChangedEventArgs> settingChanged = this.SettingChanged;
			if (settingChanged == null)
			{
				return;
			}
			SettingChangedEventArgs e = new SettingChangedEventArgs(changedEntryBase);
			foreach (EventHandler<SettingChangedEventArgs> item in settingChanged.GetInvocationList().Cast<EventHandler<SettingChangedEventArgs>>())
			{
				try
				{
					item(sender, e);
				}
				catch (Exception ex)
				{
					UtilsMod.MLS.Log((LogLevel)2, (object)ex);
				}
			}
		}

		private void OnConfigReloaded()
		{
			EventHandler configReloaded = this.ConfigReloaded;
			if (configReloaded == null)
			{
				return;
			}
			foreach (EventHandler item in configReloaded.GetInvocationList().Cast<EventHandler>())
			{
				try
				{
					item(this, EventArgs.Empty);
				}
				catch (Exception ex)
				{
					UtilsMod.MLS.Log((LogLevel)2, (object)ex);
				}
			}
		}

		public IEnumerator<KeyValuePair<ConfigDefinition, ConfigEntryBase>> GetEnumerator()
		{
			return Entries.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Add(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
		{
			lock (_ioLock)
			{
				Entries.Add(item.Key, item.Value);
			}
		}

		public bool Contains(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
		{
			lock (_ioLock)
			{
				return ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).Contains(item);
			}
		}

		void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.CopyTo(KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array, int arrayIndex)
		{
			lock (_ioLock)
			{
				((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).CopyTo(array, arrayIndex);
			}
		}

		bool ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Remove(KeyValuePair<ConfigDefinition, ConfigEntryBase> item)
		{
			lock (_ioLock)
			{
				return Entries.Remove(item.Key);
			}
		}

		public bool ContainsKey(ConfigDefinition key)
		{
			lock (_ioLock)
			{
				return Entries.ContainsKey(key);
			}
		}

		public void Add(ConfigDefinition key, ConfigEntryBase value)
		{
			throw new InvalidOperationException("Directly adding a config entry is not supported");
		}

		public bool Remove(ConfigDefinition key)
		{
			lock (_ioLock)
			{
				return Entries.Remove(key);
			}
		}

		public void Clear()
		{
			lock (_ioLock)
			{
				Entries.Clear();
			}
		}

		bool IDictionary<ConfigDefinition, ConfigEntryBase>.TryGetValue(ConfigDefinition key, out ConfigEntryBase value)
		{
			lock (_ioLock)
			{
				return Entries.TryGetValue(key, out value);
			}
		}
	}
}

patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll

Decompiled 10 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.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.InlineRT;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod")]
[assembly: AssemblyTitle("MonoMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	[MonoMod__SafeToCopy__]
	public class MonoModAdded : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModConstructor : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomAttributeAttribute : Attribute
	{
		public MonoModCustomAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomMethodAttributeAttribute : Attribute
	{
		public MonoModCustomMethodAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModEnumReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCall : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCallvirt : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	[Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")]
	public class MonoModHook : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModHook(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModHook(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIfFlag : Attribute
	{
		public MonoModIfFlag(string key)
		{
		}

		public MonoModIfFlag(string key, bool fallback)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIgnore : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MonoModLinkFrom : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModLinkFrom(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModLinkFrom(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModLinkTo : Attribute
	{
		public MonoModLinkTo(string t)
		{
		}

		public MonoModLinkTo(Type t)
		{
		}

		public MonoModLinkTo(string t, string n)
		{
		}

		public MonoModLinkTo(Type t, string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModNoNew : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOnPlatform : Attribute
	{
		public MonoModOnPlatform(params Platform[] p)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginal : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginalName : Attribute
	{
		public MonoModOriginalName(string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPatch : Attribute
	{
		public MonoModPatch(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPublic : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModRemove : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModTargetModule : Attribute
	{
		public MonoModTargetModule(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	internal class MonoMod__SafeToCopy__ : Attribute
	{
	}
	public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri);
	public delegate void MethodRewriter(MonoModder modder, MethodDefinition method);
	public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri);
	public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName);
	public delegate void PostProcessor(MonoModder modder);
	public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod);
	public class RelinkMapEntry
	{
		public string Type;

		public string FindableID;

		public RelinkMapEntry()
		{
		}

		public RelinkMapEntry(string type, string findableID)
		{
			Type = type;
			FindableID = findableID;
		}
	}
	public enum DebugSymbolFormat
	{
		Auto,
		MDB,
		PDB
	}
	public class MonoModder : IDisposable
	{
		public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null;

		public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version;

		public Dictionary<string, object> SharedData = new Dictionary<string, object>();

		public Dictionary<string, object> RelinkMap = new Dictionary<string, object>();

		public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>();

		public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default);

		public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>();

		public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>();

		public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>();

		public ModReadEventHandler OnReadMod;

		public PostProcessor PostProcessors;

		public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { 
		{
			"MonoMod.MonoModPublic",
			delegate
			{
			}
		} };

		public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>();

		public MissingDependencyResolver MissingDependencyResolver;

		public MethodParser MethodParser;

		public MethodRewriter MethodRewriter;

		public MethodBodyRewriter MethodBodyRewriter;

		public Stream Input;

		public string InputPath;

		public Stream Output;

		public string OutputPath;

		public List<string> DependencyDirs = new List<string>();

		public ModuleDefinition Module;

		public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>();

		public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>();

		public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib;

		public bool LogVerboseEnabled;

		public bool CleanupEnabled;

		public bool PublicEverything;

		public List<ModuleReference> Mods = new List<ModuleReference>();

		public bool Strict;

		public bool MissingDependencyThrow;

		public bool RemovePatchReferences;

		public bool PreventInline;

		public bool? UpgradeMSCORLIB;

		public ReadingMode ReadingMode = (ReadingMode)1;

		public DebugSymbolFormat DebugSymbolOutputFormat;

		public int CurrentRID;

		protected IAssemblyResolver _assemblyResolver;

		protected ReaderParameters _readerParameters;

		protected WriterParameters _writerParameters;

		public bool GACEnabled;

		private string[] _GACPathsNone = new string[0];

		protected string[] _GACPaths;

		protected MethodDefinition _mmOriginalCtor;

		protected MethodDefinition _mmOriginalNameCtor;

		protected MethodDefinition _mmAddedCtor;

		protected MethodDefinition _mmPatchCtor;

		public virtual IAssemblyResolver AssemblyResolver
		{
			get
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				if (_assemblyResolver == null)
				{
					DefaultAssemblyResolver val = new DefaultAssemblyResolver();
					foreach (string dependencyDir in DependencyDirs)
					{
						((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir);
					}
					_assemblyResolver = (IAssemblyResolver)(object)val;
				}
				return _assemblyResolver;
			}
			set
			{
				_assemblyResolver = value;
			}
		}

		public virtual ReaderParameters ReaderParameters
		{
			get
			{
				//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)
				//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)
				//IL_002c: Expected O, but got Unknown
				if (_readerParameters == null)
				{
					_readerParameters = new ReaderParameters(ReadingMode)
					{
						AssemblyResolver = AssemblyResolver,
						ReadSymbols = true
					};
				}
				return _readerParameters;
			}
			set
			{
				_readerParameters = value;
			}
		}

		public virtual WriterParameters WriterParameters
		{
			get
			{
				//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_0043: 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_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Expected O, but got Unknown
				//IL_0067: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Expected O, but got Unknown
				if (_writerParameters == null)
				{
					bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB;
					bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB;
					if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto)
					{
						if ((PlatformHelper.Current & 0x25) == 37)
						{
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					WriterParameters val = new WriterParameters
					{
						WriteSymbols = true
					};
					object symbolWriterProvider;
					if (!flag)
					{
						if (!flag2)
						{
							symbolWriterProvider = null;
						}
						else
						{
							ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider();
							symbolWriterProvider = val2;
						}
					}
					else
					{
						ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider();
						symbolWriterProvider = val2;
					}
					val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider;
					_writerParameters = val;
				}
				return _writerParameters;
			}
			set
			{
				_writerParameters = value;
			}
		}

		public string[] GACPaths
		{
			get
			{
				if (!GACEnabled)
				{
					return _GACPathsNone;
				}
				if (_GACPaths != null)
				{
					return _GACPaths;
				}
				if (!IsMono)
				{
					string environmentVariable = Environment.GetEnvironmentVariable("windir");
					if (string.IsNullOrEmpty(environmentVariable))
					{
						return _GACPaths = _GACPathsNone;
					}
					environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET");
					environmentVariable = Path.Combine(environmentVariable, "assembly");
					_GACPaths = new string[3]
					{
						Path.Combine(environmentVariable, "GAC_32"),
						Path.Combine(environmentVariable, "GAC_64"),
						Path.Combine(environmentVariable, "GAC_MSIL")
					};
				}
				else
				{
					List<string> list = new List<string>();
					string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac");
					if (Directory.Exists(text))
					{
						list.Add(text);
					}
					string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
					if (!string.IsNullOrEmpty(environmentVariable2))
					{
						string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator });
						foreach (string text2 in array)
						{
							if (!string.IsNullOrEmpty(text2))
							{
								string path = text2;
								path = Path.Combine(path, "lib");
								path = Path.Combine(path, "mono");
								path = Path.Combine(path, "gac");
								if (Directory.Exists(path) && !list.Contains(path))
								{
									list.Add(path);
								}
							}
						}
					}
					_GACPaths = list.ToArray();
				}
				return _GACPaths;
			}
			set
			{
				GACEnabled = true;
				_GACPaths = value;
			}
		}

		public MonoModder()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			MethodParser = DefaultParser;
			MissingDependencyResolver = DefaultMissingDependencyResolver;
			PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor));
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS");
			if (!string.IsNullOrEmpty(environmentVariable))
			{
				foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator })
					select dir.Trim())
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(item);
					}
					DependencyDirs.Add(item);
				}
			}
			LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1";
			CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0";
			PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1";
			PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1";
			Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1";
			MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0";
			RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0";
			string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT");
			if (environmentVariable2 != null)
			{
				environmentVariable2 = environmentVariable2.ToLowerInvariant();
				if (environmentVariable2 == "pdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.PDB;
				}
				else if (environmentVariable2 == "mdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.MDB;
				}
			}
			string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE");
			UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0"));
			GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0";
			MonoModRulesManager.Register(this);
		}

		public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false)
		{
			if (all || shareable)
			{
				foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache)
				{
					item.Value.Dispose();
				}
				DependencyCache.Clear();
			}
			if (all || moduleSpecific)
			{
				RelinkMapCache.Clear();
				RelinkModuleMapCache.Clear();
			}
		}

		public virtual void Dispose()
		{
			//IL_004e: 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)
			ClearCaches(all: true);
			ModuleDefinition module = Module;
			if (module != null)
			{
				module.Dispose();
			}
			Module = null;
			((IDisposable)AssemblyResolver)?.Dispose();
			AssemblyResolver = null;
			foreach (ModuleDefinition mod in Mods)
			{
				if ((int)mod != 0)
				{
					mod.Dispose();
				}
			}
			foreach (List<ModuleDefinition> value in DependencyMap.Values)
			{
				foreach (ModuleDefinition item in value)
				{
					if (item != null)
					{
						item.Dispose();
					}
				}
			}
			DependencyMap.Clear();
			Input?.Dispose();
			Output?.Dispose();
		}

		public virtual void Log(object value)
		{
			Log(value.ToString());
		}

		public virtual void Log(string text)
		{
			Console.Write("[MonoMod] ");
			Console.WriteLine(text);
		}

		public virtual void LogVerbose(object value)
		{
			if (LogVerboseEnabled)
			{
				Log(value);
			}
		}

		public virtual void LogVerbose(string text)
		{
			if (LogVerboseEnabled)
			{
				Log(text);
			}
		}

		private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
					input.Seek(0L, SeekOrigin.Begin);
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		private static ModuleDefinition _ReadModule(string input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		public virtual void Read()
		{
			if (Module != null)
			{
				return;
			}
			if (Input != null)
			{
				Log("Reading input stream into module.");
				Module = _ReadModule(Input, GenReaderParameters(mainModule: true));
			}
			else if (InputPath != null)
			{
				Log("Reading input file into module.");
				IAssemblyResolver assemblyResolver = AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath));
				}
				DependencyDirs.Add(Path.GetDirectoryName(InputPath));
				Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath));
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				return;
			}
			foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator })
				select path.Trim())
			{
				ReadMod(item);
			}
		}

		public virtual void MapDependencies()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition main = mod;
				MapDependencies(main);
			}
			MapDependencies(Module);
		}

		public virtual void MapDependencies(ModuleDefinition main)
		{
			//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)
			if (DependencyMap.ContainsKey(main))
			{
				return;
			}
			DependencyMap[main] = new List<ModuleDefinition>();
			Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					AssemblyNameReference current = enumerator.Current;
					MapDependency(main, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef)
		{
			MapDependency(main, depRef.Name, depRef.FullName, depRef);
		}

		public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null)
		{
			if (!DependencyMap.TryGetValue(main, out var value))
			{
				value = (DependencyMap[main] = new List<ModuleDefinition>());
			}
			if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2)))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			string text = Path.GetExtension(name).ToLowerInvariant();
			bool flag = text == "pdb" || text == "mdb";
			string text2 = null;
			foreach (string dependencyDir in DependencyDirs)
			{
				text2 = Path.Combine(dependencyDir, name + ".dll");
				if (!File.Exists(text2))
				{
					text2 = Path.Combine(dependencyDir, name + ".exe");
				}
				if (!File.Exists(text2) && !flag)
				{
					text2 = Path.Combine(dependencyDir, name);
				}
				if (File.Exists(text2))
				{
					break;
				}
				text2 = null;
			}
			if (text2 == null && depRef != null)
			{
				try
				{
					AssemblyDefinition obj = AssemblyResolver.Resolve(depRef);
					value2 = ((obj != null) ? obj.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (text2 == null)
			{
				string[] gACPaths = GACPaths;
				for (int i = 0; i < gACPaths.Length; i++)
				{
					text2 = Path.Combine(gACPaths[i], name);
					if (Directory.Exists(text2))
					{
						string[] directories = Directory.GetDirectories(text2);
						int num = 0;
						int num2 = 0;
						for (int j = 0; j < directories.Length; j++)
						{
							string text3 = directories[j];
							if (text3.StartsWith(text2))
							{
								text3 = text3.Substring(text2.Length + 1);
							}
							Match match = Regex.Match(text3, "\\d+");
							if (match.Success)
							{
								int num3 = int.Parse(match.Value);
								if (num3 > num)
								{
									num = num3;
									num2 = j;
								}
							}
						}
						text2 = Path.Combine(directories[num2], name + ".dll");
						break;
					}
					text2 = null;
				}
			}
			if (text2 == null)
			{
				try
				{
					AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name));
					value2 = ((obj3 != null) ? obj3.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (value2 == null)
			{
				if (text2 != null && File.Exists(text2))
				{
					value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2));
				}
				else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null)
				{
					return;
				}
			}
			LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded");
			value.Add(value2);
			if (fullName == null)
			{
				fullName = value2.Assembly.FullName;
			}
			DependencyCache[fullName] = value2;
			DependencyCache[name] = value2;
			MapDependencies(value2);
		}

		public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0")
			{
				Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW");
				MissingDependencyThrow = false;
			}
			if (MissingDependencyThrow || Strict)
			{
				throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null);
			}
			return null;
		}

		public virtual void Write(Stream output = null, string outputPath = null)
		{
			output = output ?? Output;
			outputPath = outputPath ?? OutputPath;
			PatchRefsInType(PatchWasHere());
			if (output != null)
			{
				Log("[Write] Writing modded module into output stream.");
				Module.Write(output, WriterParameters);
			}
			else
			{
				Log("[Write] Writing modded module into output file.");
				Module.Write(outputPath, WriterParameters);
			}
		}

		public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null)
		{
			//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)
			//IL_0013: Expected O, but got Unknown
			ReaderParameters readerParameters = ReaderParameters;
			ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode);
			val.AssemblyResolver = readerParameters.AssemblyResolver;
			val.MetadataResolver = readerParameters.MetadataResolver;
			val.InMemory = readerParameters.InMemory;
			val.MetadataImporterProvider = readerParameters.MetadataImporterProvider;
			val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider;
			val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching;
			val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections;
			val.SymbolStream = readerParameters.SymbolStream;
			val.SymbolReaderProvider = readerParameters.SymbolReaderProvider;
			val.ReadSymbols = readerParameters.ReadSymbols;
			if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
			{
				val.ReadSymbols = false;
			}
			return val;
		}

		public virtual void ReadMod(string path)
		{
			if (Directory.Exists(path))
			{
				Log("[ReadMod] Loading mod dir: " + path);
				string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3);
				string value = text.Replace(" ", "");
				if (!DependencyDirs.Contains(path))
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(path);
					}
					DependencyDirs.Add(path);
				}
				string[] files = Directory.GetFiles(path);
				foreach (string text2 in files)
				{
					if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll"))
					{
						ReadMod(text2);
					}
				}
				return;
			}
			Log("[ReadMod] Loading mod: " + path);
			ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path));
			string directoryName = Path.GetDirectoryName(path);
			if (!DependencyDirs.Contains(directoryName))
			{
				IAssemblyResolver assemblyResolver2 = AssemblyResolver;
				IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null);
				if (obj2 != null)
				{
					((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName);
				}
				DependencyDirs.Add(directoryName);
			}
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ReadMod(Stream stream)
		{
			Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}");
			ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false));
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ParseRules(ModuleDefinition mod)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			TypeDefinition type = mod.GetType("MonoMod.MonoModRules");
			Type rulesTypeMMILRT = null;
			if (type != null)
			{
				rulesTypeMMILRT = this.ExecuteRules(type);
				mod.Types.Remove(type);
			}
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					ParseRulesInType(current, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: 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_025c: 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_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			Extensions.GetPatchFullName((MemberReference)(object)type);
			if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				return;
			}
			CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute");
			CustomAttributeArgument val;
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
				{
					method2.Invoke(self, args);
				};
			}
			customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute");
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext)))
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						//IL_0024: Unknown result type (might be due to invalid IL or missing references)
						//IL_002e: Expected O, but got Unknown
						//IL_0029: Unknown result type (might be due to invalid IL or missing references)
						//IL_0033: Expected O, but got Unknown
						//IL_0040: Unknown result type (might be due to invalid IL or missing references)
						//IL_004a: Expected O, but got Unknown
						ILContext il = new ILContext((MethodDefinition)args[0]);
						il.Invoke((Manipulator)delegate
						{
							method.Invoke(self, new object[2]
							{
								il,
								args[1]
							});
						});
						if (il.IsReadOnly)
						{
							il.Dispose();
						}
					};
				}
				else
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						method.Invoke(self, args);
					};
				}
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
			{
				ParseLinkTo((MemberReference)(object)type, val2);
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore"))
			{
				return;
			}
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current, val2);
						}
						if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call;
						}
						else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					FieldDefinition current2 = enumerator2.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current2, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					PropertyDefinition current3 = enumerator3.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current3, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					TypeDefinition current4 = enumerator4.Current;
					ParseRulesInType(current4, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
		}

		public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook)
		{
			//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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//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_005a: Expected O, but got Unknown
			//IL_006b: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			CustomAttributeArgument val = hook.ConstructorArguments[0];
			string key = (string)((CustomAttributeArgument)(ref val)).Value;
			object value;
			if (target is TypeReference)
			{
				value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target);
			}
			else if (target is MethodReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false));
			}
			else if (target is FieldReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name);
			}
			else
			{
				if (!(target is PropertyReference))
				{
					return;
				}
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name);
			}
			RelinkMap[key] = value;
		}

		public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook)
		{
			//IL_0063: 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_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_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)
			MemberReference obj = ((from is MethodReference) ? from : null);
			string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from);
			CustomAttributeArgument val;
			if (hook.ConstructorArguments.Count == 1)
			{
				Dictionary<string, object> relinkMap = RelinkMap;
				val = hook.ConstructorArguments[0];
				relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value;
			}
			else
			{
				Dictionary<string, object> relinkMap2 = RelinkMap;
				val = hook.ConstructorArguments[0];
				string type = (string)((CustomAttributeArgument)(ref val)).Value;
				val = hook.ConstructorArguments[1];
				relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value);
			}
		}

		public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (!cap.HasCustomAttributes)
			{
				return;
			}
			CustomAttribute[] array = cap.CustomAttributes.ToArray();
			foreach (CustomAttribute val in array)
			{
				if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value))
				{
					value?.Invoke(null, new object[2] { cap, val });
				}
				if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value))
				{
					value?.Invoke(null, new object[2]
					{
						(object)(MethodDefinition)cap,
						val
					});
				}
			}
		}

		public virtual void AutoPatch()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Log("[AutoPatch] Parsing rules in loaded mods");
			foreach (ModuleDefinition mod4 in Mods)
			{
				ModuleDefinition mod = mod4;
				ParseRules(mod);
			}
			Log("[AutoPatch] PrePatch pass");
			foreach (ModuleDefinition mod5 in Mods)
			{
				ModuleDefinition mod2 = mod5;
				PrePatchModule(mod2);
			}
			Log("[AutoPatch] Patch pass");
			foreach (ModuleDefinition mod6 in Mods)
			{
				ModuleDefinition mod3 = mod6;
				PatchModule(mod3);
			}
			Log("[AutoPatch] PatchRefs pass");
			PatchRefs();
			if (PostProcessors != null)
			{
				Delegate[] invocationList = PostProcessors.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Log($"[PostProcessor] PostProcessor pass #{i + 1}");
					((PostProcessor)invocationList[i])?.Invoke(this);
				}
			}
		}

		public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0027: 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)
			try
			{
				return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
			}
			catch (Exception ex)
			{
				throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context);
			}
		}

		public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null);
			if (val != null)
			{
				if (((MemberReference)val).Module == Module)
				{
					return (IMetadataTokenProvider)(object)val;
				}
				if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module))
				{
					return (IMetadataTokenProvider)(object)Module.ImportReference(val);
				}
				val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val));
				TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val));
				if (val2 == null)
				{
					if (RelinkMap.ContainsKey(((MemberReference)val).FullName))
					{
						return null;
					}
					throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(val2);
			}
			if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference)
			{
				return Extensions.ImportReference(Module, mtp);
			}
			throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			return ResolveRelinkTarget(mtp) ?? mtp;
		}

		public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true)
		{
			//IL_000b: 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_002f: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_004b: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			//IL_022f: 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_0237: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			string text2;
			if (mtp is TypeReference)
			{
				text2 = ((MemberReference)(TypeReference)mtp).FullName;
			}
			else if (mtp is MethodReference)
			{
				text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false);
				text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true);
			}
			else if (mtp is FieldReference)
			{
				text2 = ((MemberReference)(FieldReference)mtp).FullName;
			}
			else
			{
				if (!(mtp is PropertyReference))
				{
					return null;
				}
				text2 = ((MemberReference)(PropertyReference)mtp).FullName;
			}
			if (RelinkMapCache.TryGetValue(text2, out var value))
			{
				return value;
			}
			if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2))))
			{
				if (value2 is IMetadataTokenProvider)
				{
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is RelinkMapEntry)
				{
					string type = ((RelinkMapEntry)value2).Type;
					string findableID = ((RelinkMapEntry)value2).FindableID;
					TypeReference obj = FindTypeDeep(type);
					TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null);
					if (val2 == null)
					{
						return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule);
					}
					value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null));
					if (value2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is string && mtp is TypeReference)
				{
					IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2);
					if (val5 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5);
				}
				if (value2 is IMetadataTokenProvider)
				{
					Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache;
					string key = text2;
					IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2;
					IMetadataTokenProvider result = val6;
					relinkMapCache[key] = val6;
					return result;
				}
				throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})");
			}
			if (relinkModule && mtp is TypeReference)
			{
				if (RelinkModuleMapCache.TryGetValue(text2, out var value3))
				{
					return (IMetadataTokenProvider)(object)value3;
				}
				value3 = (TypeReference)mtp;
				if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4))
				{
					TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName);
					if (type2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2));
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(value3);
			}
			return null;
		}

		public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri)
		{
			return true;
		}

		public virtual TypeReference FindType(string name)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false);
		}

		public virtual TypeReference FindType(string name, bool runtimeName)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName);
		}

		protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled)
		{
			TypeReference type;
			if ((type = main.GetType(fullName, false)) != null)
			{
				return type;
			}
			if (fullName.StartsWith("<PrivateImplementationDetails>/"))
			{
				return null;
			}
			if (crawled.Contains(main))
			{
				return null;
			}
			crawled.Push(main);
			foreach (ModuleDefinition item in DependencyMap[main])
			{
				if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null)
				{
					return type;
				}
			}
			return null;
		}

		public virtual TypeReference FindTypeDeep(string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			TypeReference val = FindType(name, runtimeName: false);
			if (val != null)
			{
				return val;
			}
			Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>();
			val = null;
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition key = mod;
				foreach (ModuleDefinition item in DependencyMap[key])
				{
					if ((val = FindType(item, name, crawled)) != null)
					{
						IMetadataScope scope = val.Scope;
						AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null);
						if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name))
						{
							Module.AssemblyReferences.Add(dllRef);
						}
						return Module.ImportReference(val);
					}
				}
			}
			return null;
		}

		public virtual void PrePatchModule(ModuleDefinition mod)
		{
			//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_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)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PrePatchType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ModuleReference current2 = enumerator2.Current;
					if (!Module.ModuleReferences.Contains(current2))
					{
						Module.ModuleReferences.Add(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					Resource current3 = enumerator3.Current;
					if (current3 is EmbeddedResource)
					{
						Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData()));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
		}

		public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd))
			{
				return;
			}
			TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false));
			TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					if (val2.DeclaringType == null)
					{
						Module.Types.Remove(val2);
					}
					else
					{
						val2.DeclaringType.NestedTypes.Remove(val2);
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			else if (val != null)
			{
				PrePatchNested(type);
				return;
			}
			LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module.");
			TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType);
			Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					InterfaceImplementation current2 = enumerator2.Current;
					val3.Interfaces.Add(current2);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ClassSize = type.ClassSize;
			if (type.DeclaringType != null)
			{
				val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve();
				val3.DeclaringType.NestedTypes.Add(val3);
			}
			else
			{
				Module.Types.Add(val3);
			}
			val3.PackingSize = type.PackingSize;
			Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations);
			val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
			val = (TypeReference)(object)val3;
			PrePatchNested(type);
		}

		protected virtual void PrePatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PrePatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchModule(ModuleDefinition mod)
		{
			//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_0077: 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)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute")
					{
						PatchType(current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current2 = enumerator.Current;
					if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute"))
					{
						PatchType(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchType(TypeDefinition type)
		{
			//IL_0078: 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_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			TypeReference type2 = Module.GetType(patchFullName, false);
			if (type2 == null)
			{
				return;
			}
			TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null);
			Enumerator<CustomAttribute> enumerator;
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null)
				{
					enumerator = type.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				PatchNested(type);
				return;
			}
			if (patchFullName == ((MemberReference)type).FullName)
			{
				LogVerbose("[PatchType] Patching type " + patchFullName);
			}
			else
			{
				LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")");
			}
			enumerator = type.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName))
					{
						val.CustomAttributes.Add(Extensions.Clone(current2));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current3 = enumerator2.Current;
					PatchProperty(val, current3, hashSet);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current4 = enumerator3.Current;
					PatchEvent(val, current4, hashSet2);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current5 = enumerator4.Current;
					if (!hashSet.Contains(current5) && !hashSet2.Contains(current5))
					{
						PatchMethod(val, current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace"))
			{
				int num = 0;
				while (num < val.Fields.Count)
				{
					if (((MemberReference)val.Fields[num]).Name == "value__")
					{
						num++;
					}
					else
					{
						val.Fields.RemoveAt(num);
					}
				}
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current6 = enumerator5.Current;
					PatchField(val, current6);
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			PatchNested(type);
		}

		protected virtual void PatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_006e: 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_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: 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_0229: Expected O, but got Unknown
			//IL_022b: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_02b5: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module))
			{
				return;
			}
			((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop);
			PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name);
			string text = "<" + ((MemberReference)prop).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = prop.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (prop.GetMethod != null)
				{
					propMethods?.Add(prop.GetMethod);
				}
				if (prop.SetMethod != null)
				{
					propMethods?.Add(prop.SetMethod);
				}
				enumerator2 = prop.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Properties.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.GetMethod != null)
					{
						targetType.Methods.Remove(val.GetMethod);
					}
					if (val.SetMethod != null)
					{
						targetType.Methods.Remove(val.SetMethod);
					}
					enumerator2 = val.OtherMethods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current3 = enumerator2.Current;
							targetType.Methods.Remove(current3);
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType);
				val = val4;
				PropertyDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						ParameterDefinition current4 = enumerator3.Current;
						((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				val5.DeclaringType = targetType;
				targetType.Properties.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					val3 = val6;
					FieldDefinition val7 = val6;
					targetType.Fields.Add(val7);
				}
			}
			enumerator = prop.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current5 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current5));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition getMethod = prop.GetMethod;
			MethodDefinition getMethod2;
			if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null)
			{
				val.GetMethod = getMethod2;
				propMethods?.Add(getMethod);
			}
			MethodDefinition setMethod = prop.SetMethod;
			if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null)
			{
				val.SetMethod = getMethod2;
				propMethods?.Add(setMethod);
			}
			enumerator2 = prop.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current6 = enumerator2.Current;
					if ((getMethod2 = PatchMethod(targetType, current6)) != null)
					{
						val.OtherMethods.Add(getMethod2);
						propMethods?.Add(current6);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null)
		{
			//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_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: 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_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0252: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent);
			EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name);
			string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = srcEvent.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (srcEvent.AddMethod != null)
				{
					propMethods?.Add(srcEvent.AddMethod);
				}
				if (srcEvent.RemoveMethod != null)
				{
					propMethods?.Add(srcEvent.RemoveMethod);
				}
				if (srcEvent.InvokeMethod != null)
				{
					propMethods?.Add(srcEvent.InvokeMethod);
				}
				enumerator2 = srcEvent.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Events.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.AddMethod != null)
					{
						targetType.Methods.Remove(val.AddMethod);
					}
					if (val.RemoveMethod != null)
					{
						targetType.Methods.Remove(val.RemoveMethod);
					}
					if (val.InvokeMethod != null)
					{
						targetType.Methods.Remove(val.InvokeMethod);
					}
					if (val.OtherMethods != null)
					{
						enumerator2 = val.OtherMethods.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								MethodDefinition current3 = enumerator2.Current;
								targetType.Methods.Remove(current3);
							}
						}
						finally
						{
							((IDisposable)enumerator2).Dispose();
						}
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType);
				val = val4;
				EventDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val5.DeclaringType = targetType;
				targetType.Events.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					targetType.Fields.Add(val6);
				}
			}
			enumerator = srcEvent.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current4 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current4));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition addMethod = srcEvent.AddMethod;
			MethodDefinition addMethod2;
			if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null)
			{
				val.AddMethod = addMethod2;
				propMethods?.Add(addMethod);
			}
			MethodDefinition removeMethod = srcEvent.RemoveMethod;
			if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null)
			{
				val.RemoveMethod = addMethod2;
				propMethods?.Add(removeMethod);
			}
			MethodDefinition invokeMethod = srcEvent.InvokeMethod;
			if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null)
			{
				val.InvokeMethod = addMethod2;
				propMethods?.Add(invokeMethod);
			}
			enumerator2 = srcEvent.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current5 = enumerator2.Current;
					if ((addMethod2 = PatchMethod(targetType, current5)) != null)
					{
						val.OtherMethods.Add(addMethod2);
						propMethods?.Add(current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchField(TypeDefinition targetType, FieldDefinition field)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//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)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module))
			{
				return;
			}
			((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace"))
			{
				FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name);
				if (val != null)
				{
					targetType.Fields.Remove(val);
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name);
			Enumerator<CustomAttribute> enumerator;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null)
			{
				enumerator = field.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
						{
							val2.CustomAttributes.Add(Extensions.Clone(current));
						}
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (val2 == null)
			{
				val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType);
				val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val2.InitialValue = field.InitialValue;
				if (field.HasConstant)
				{
					val2.Constant = field.Constant;
				}
				targetType.Fields.Add(val2);
			}
			enumerator = field.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					val2.CustomAttributes.Add(Extensions.Clone(current2));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: 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_024b: 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_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: 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_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal"))
			{
				return null;
			}
			if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module))
			{
				return null;
			}
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType);
			if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false)))
			{
				return null;
			}
			((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName"))
				{
					CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor());
					val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name)));
					method.CustomAttributes.Add(val);
				}
				((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor");
				method.IsSpecialName = true;
				method.IsRuntimeSpecialName = true;
			}
			MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true);
			MethodDefinition obj = method;
			string text = patchFullName;
			MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore"))
			{
				if (val2 != null)
				{
					Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val2.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				return null;
			}
			if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew"))
			{
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					targetType.Methods.Remove(val2);
				}
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace"))
			{
				if (val2 != null)
				{
					val2.CustomAttributes.Clear();
					val2.Attributes = method.Attributes;
					val2.IsPInvokeImpl = method.IsPInvokeImpl;
					val2.ImplAttributes = method.ImplAttributes;
				}
			}
			else if (val2 != null && val3 == null)
			{
				val3 = Extensions.Clone(val2, (MethodDefinition)null);
				((MemberReference)val3).Name = method.GetOriginalName();
				val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF);
				((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296);
				val3.IsVirtual = false;
				val3.Overrides.Clear();
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current2 = enumerator2.Current;
						val3.Overrides.Add(current2);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor()));
				MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true);
				if (val4 != null)
				{
					Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current3 = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName))
							{
								val3.CustomAttributes.Add(Extensions.Clone(current3));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				targetType.Methods.Add(val3);
			}
			if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				Collection<Instruction> instructions = method.Body.Instructions;
				ILProcessor iLProcessor = method.Body.GetILProcessor();
				iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3));
			}
			if (val2 != null)
			{
				val2.Body = Extensions.Clone(method.Body, val2);
				val2.IsManaged = method.IsManaged;
				val2.IsIL = method.IsIL;
				val2.IsNative = method.IsNative;
				val2.PInvokeInfo = method.PInvokeInfo;
				val2.IsPreserveSig = method.IsPreserveSig;
				val2.IsInternalCall = method.IsInternalCall;
				val2.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current4 = enumerator.Current;
						val2.CustomAttributes.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				method = val2;
			}
			else
			{
				MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void);
				((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296);
				((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention;
				((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis;
				((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType;
				val5.Attributes = method.Attributes;
				val5.ImplAttributes = method.ImplAttributes;
				val5.SemanticsAttributes = method.SemanticsAttributes;
				val5.DeclaringType = targetType;
				((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType;
				val5.Body = Extensions.Clone(method.Body, val5);
				val5.PInvokeInfo = method.PInvokeInfo;
				val5.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						GenericParameter current5 = enumerator3.Current;
						((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						ParameterDefinition current6 = enumerator4.Current;
						((MethodReference)val5).Parameters.Add(Extensions.Clone(current6));
					}
				}
				finally
				{
					((IDisposable)enumerator4).Dispose();
				}
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current7 = enumerator.Current;
						val5.CustomAttributes.Add(Extensions.Clone(current7));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current8 = enumerator2.Current;
						val5.Overrides.Add(current8);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				targetType.Methods.Add(val5);
				method = val5;
			}
			if (val3 != null)
			{
				CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor());
				val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name));
				method.CustomAttributes.Add(val6);
			}
			return method;
		}

		public virtual void PatchRefs()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			if (!UpgradeMSCORLIB.HasValue)
			{
				Version fckUnity = new Version(2, 0, 5, 0);
				UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity);
			}
			if (UpgradeMSCORLIB.Value)
			{
				List<AssemblyNameReference> list = new List<AssemblyNameReference>();
				for (int i = 0; i < Module.AssemblyReferences.Count; i++)
				{
					AssemblyNameReference val = Module.AssemblyReferences[i];
					if (val.Name == "mscorlib")
					{
						list.Add(val);
					}
				}
				if (list.Count > 1)
				{
					AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First();
					if (DependencyCache.TryGetValue(val2.FullName, out var value))
					{
						for (int j = 0; j < Module.AssemblyReferences.Count; j++)
						{
							AssemblyNameReference val3 = Module.AssemblyReferences[j];
							if (val3.Name == "mscorlib" && val2.Version > val3.Version)
							{
								LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version);
								RelinkModuleMap[val3.FullName] = value;
								Module.AssemblyReferences.RemoveAt(j);
								j--;
							}
						}
					}
				}
			}
			Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefs(ModuleDefinition mod)
		{
			//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)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefsInType(TypeDefinition type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: 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_00dc: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_0205: 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_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_02a1: 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_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Expected O, but got Unknown
			LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}");
			if (type.BaseType != null)
			{
				type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++)
			{
				((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int j = 0; j < type.Interfaces.Count; j++)
			{
				InterfaceImplementation obj = type.Interfaces[j];
				InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
				Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				type.Interfaces[j] = val;
			}
			for (int k = 0; k < type.CustomAttributes.Count; k++)
			{
				type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current2 = enumerator2.Current;
					((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int l = 0; l < current2.CustomAttributes.Count; l++)
					{
						current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current3 = enumerator3.Current;
					((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int m = 0; m < current3.CustomAttributes.Count; m++)
					{
						current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current4 = enumerator4.Current;
					PatchRefsInMethod(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current5 = enumerator5.Current;
					((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int n = 0; n < current5.CustomAttributes.Count; n++)
					{
						current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			for (int num = 0; num < type.NestedTypes.Count; num++)
			{
				PatchRefsInType(type.NestedTypes[num]);
			}
		}

		public virtual void PatchRefsInMethod(MethodDefinition method)
		{
			//IL_0030: Unknown result t

patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

Decompiled 10 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BepInEx.Configuration;
using BepInEx.Logging;
using Mono.Cecil;
using MonoMod;
using MonoMod.RuntimeDetour.HookGen;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyDescription("Runtime HookGen for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HarbingerOfMe")]
[assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyCopyright("HarbingerOfMe-2022")]
[assembly: AssemblyTrademark("MIT")]
[assembly: ComVisible(false)]
[assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.2.1.0")]
namespace BepInEx.MonoMod.HookGenPatcher;

public static class HookGenPatcher
{
	internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher");

	private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg";

	private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true);

	private const char EntrySeparator = ',';

	private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} ");

	private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact.");

	private static bool skipHashing => !preciseHash.Value;

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];


	public static void Initialize()
	{
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Expected O, but got Unknown
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Expected O, but got Unknown
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Expected O, but got Unknown
		//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Expected O, but got Unknown
		string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' });
		string text = Path.Combine(Paths.PluginPath, "MMHOOK");
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = "MMHOOK_" + text2;
			string text4 = Path.Combine(Paths.ManagedPath, text2);
			string text5 = Path.Combine(text, text3);
			bool flag = true;
			string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories);
			foreach (string text6 in files)
			{
				if (Path.GetFileName(text6).Equals(text3))
				{
					text5 = text6;
					Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead.");
					flag = false;
					break;
				}
			}
			if (flag)
			{
				Directory.CreateDirectory(text);
			}
			FileInfo fileInfo = new FileInfo(text4);
			long length = fileInfo.Length;
			long num = 0L;
			if (File.Exists(text5))
			{
				try
				{
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5);
					try
					{
						if (val.MainModule.GetType("BepHookGen.size" + length) != null)
						{
							if (skipHashing)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
							num = fileInfo.makeHash();
							if (val.MainModule.GetType("BepHookGen.content" + num) != null)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch (BadImageFormatException)
				{
					Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one."));
				}
			}
			Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
			Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			MonoModder val2 = new MonoModder
			{
				InputPath = text4,
				OutputPath = text5,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				IAssemblyResolver assemblyResolver = val2.AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
				}
				val2.Read();
				val2.MapDependencies();
				if (File.Exists(text5))
				{
					Logger.LogDebug((object)("Clearing " + text5));
					File.Delete(text5);
				}
				Logger.LogInfo((object)"Starting HookGenerator");
				HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5));
				ModuleDefinition outputModule = val3.OutputModule;
				try
				{
					val3.Generate();
					outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object));
					if (!skipHashing)
					{
						outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object));
					}
					outputModule.Write(text5);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				Logger.LogInfo((object)"Done.");
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}

	public static void Patch(AssemblyDefinition _)
	{
	}

	private static long makeHash(this FileInfo fileInfo)
	{
		FileStream inputStream = fileInfo.OpenRead();
		byte[] value = null;
		using (MD5 mD = new MD5CryptoServiceProvider())
		{
			value = mD.ComputeHash(inputStream);
		}
		long num = BitConverter.ToInt64(value, 0);
		if (num == 0L)
		{
			return 1L;
		}
		return num;
	}
}

patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll

Decompiled 10 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault())
			{
				Start();
			}
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(str, value));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour.HookGen
{
	public class HookGenerator
	{
		private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

		private static readonly Regex NameVerifyRegex;

		private static readonly Dictionary<Type, string> ReflTypeNameMap;

		private static readonly Dictionary<string, string> TypeNameMap;

		public MonoModder Modder;

		public ModuleDefinition OutputModule;

		public string Namespace;

		public string NamespaceIL;

		public bool HookOrig;

		public bool HookPrivate;

		public string HookExtName;

		public ModuleDefinition module_RuntimeDetour;

		public ModuleDefinition module_Utils;

		public TypeReference t_MulticastDelegate;

		public TypeReference t_IAsyncResult;

		public TypeReference t_AsyncCallback;

		public TypeReference t_MethodBase;

		public TypeReference t_RuntimeMethodHandle;

		public TypeReference t_EditorBrowsableState;

		public MethodReference m_Object_ctor;

		public MethodReference m_ObsoleteAttribute_ctor;

		public MethodReference m_EditorBrowsableAttribute_ctor;

		public MethodReference m_GetMethodFromHandle;

		public MethodReference m_Add;

		public MethodReference m_Remove;

		public MethodReference m_Modify;

		public MethodReference m_Unmodify;

		public TypeReference t_ILManipulator;

		static HookGenerator()
		{
			NameVerifyRegex = new Regex("[^a-zA-Z]");
			ReflTypeNameMap = new Dictionary<Type, string>
			{
				{
					typeof(string),
					"string"
				},
				{
					typeof(object),
					"object"
				},
				{
					typeof(bool),
					"bool"
				},
				{
					typeof(byte),
					"byte"
				},
				{
					typeof(char),
					"char"
				},
				{
					typeof(decimal),
					"decimal"
				},
				{
					typeof(double),
					"double"
				},
				{
					typeof(short),
					"short"
				},
				{
					typeof(int),
					"int"
				},
				{
					typeof(long),
					"long"
				},
				{
					typeof(sbyte),
					"sbyte"
				},
				{
					typeof(float),
					"float"
				},
				{
					typeof(ushort),
					"ushort"
				},
				{
					typeof(uint),
					"uint"
				},
				{
					typeof(ulong),
					"ulong"
				},
				{
					typeof(void),
					"void"
				}
			};
			TypeNameMap = new Dictionary<string, string>();
			foreach (KeyValuePair<Type, string> item in ReflTypeNameMap)
			{
				TypeNameMap[item.Key.FullName] = item.Value;
			}
		}

		public HookGenerator(MonoModder modder, string name)
		{
			//IL_000f: 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_001b: 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_0036: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0326: Expected O, but got Unknown
			Modder = modder;
			OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters
			{
				Architecture = modder.Module.Architecture,
				AssemblyResolver = modder.Module.AssemblyResolver,
				Kind = (ModuleKind)0,
				Runtime = modder.Module.Runtime
			});
			modder.MapDependencies();
			Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences);
			modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);
			Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
			if (string.IsNullOrEmpty(Namespace))
			{
				Namespace = "On";
			}
			NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
			if (string.IsNullOrEmpty(NamespaceIL))
			{
				NamespaceIL = "IL";
			}
			HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
			HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";
			modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
			{
				throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");
			}
			modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
			{
				throw new FileNotFoundException("MonoMod.Utils not found!");
			}
			t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
			t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
			t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
			t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
			t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
			t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));
			TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");
			t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator"));
			m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true));
			m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true));
			m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true));
			ModuleDefinition outputModule = OutputModule;
			MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase);
			val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle));
			m_GetMethodFromHandle = outputModule.ImportReference(val);
			m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true));
			m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true));
			m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true));
			m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true));
		}

		public void Generate()
		{
			//IL_0010: 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)
			Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					GenerateFor(current, out var hookType, out var hookILType);
					if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested)
					{
						OutputModule.Types.Add(hookType);
						OutputModule.Types.Add(hookILType);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			hookType = (hookILType = null);
			if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic))
			{
				return;
			}
			Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName);
			hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			bool flag = false;
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					flag |= GenerateFor(hookType, hookILType, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					TypeDefinition current2 = enumerator2.Current;
					GenerateFor(current2, out var hookType2, out var hookILType2);
					if (hookType2 != null && hookILType2 != null)
					{
						flag = true;
						hookType.NestedTypes.Add(hookType2);
						hookILType.NestedTypes.Add(hookILType2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			if (!flag)
			{
				hookType = (hookILType = null);
			}
		}

		public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
		{
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Expected O, but got Unknown
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Expected O, but got Unknown
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Expected O, but got Unknown
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Expected O, but got Unknown
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0601: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0653: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Expected O, but got Unknown
			if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor))
			{
				return false;
			}
			if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_"))
			{
				return false;
			}
			if (!HookPrivate && method.IsPrivate)
			{
				return false;
			}
			string name = GetFriendlyName((MethodReference)(object)method);
			bool flag = true;
			if (((MethodReference)method).Parameters.Count == 0)
			{
				flag = false;
			}
			IEnumerable<MethodDefinition> source = null;
			if (flag)
			{
				source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method);
				if (source.Count() == 0)
				{
					flag = false;
				}
			}
			if (flag)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++)
				{
					ParameterDefinition param = ((MethodReference)method).Parameters[parami];
					if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false);
					}
					if (source.Any(delegate(MethodDefinition other)
					{
						ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami);
						return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace;
					}))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true);
					}
					stringBuilder.Append("_");
					stringBuilder.Append(typeName.Replace(".", "").Replace("`", ""));
				}
				name += stringBuilder.ToString();
			}
			if (Extensions.FindEvent(hookType, name) != null)
			{
				int num = 1;
				string text;
				while (Extensions.FindEvent(hookType, text = name + "_" + num) != null)
				{
					num++;
				}
				name = text;
			}
			TypeDefinition val = GenerateDelegateFor(method);
			((MemberReference)val).Name = "orig_" + name;
			val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val);
			TypeDefinition val2 = GenerateDelegateFor(method);
			((MemberReference)val2).Name = "hook_" + name;
			((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val2);
			MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method);
			MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val4.Body = new MethodBody(val4);
			ILProcessor iLProcessor = val4.Body.GetILProcessor();
			iLProcessor.Emit(OpCodes.Ldtoken, val3);
			iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor.Emit(OpCodes.Ldarg_0);
			GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor.Emit(OpCodes.Ret);
			hookType.Methods.Add(val4);
			MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val6.Body = new MethodBody(val6);
			ILProcessor iLProcessor2 = val6.Body.GetILProcessor();
			iLProcessor2.Emit(OpCodes.Ldtoken, val3);
			iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor2.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Remove);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor2.Emit(OpCodes.Ret);
			hookType.Methods.Add(val6);
			EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2)
			{
				AddMethod = val4,
				RemoveMethod = val6
			};
			hookType.Events.Add(val7);
			MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val8.Body = new MethodBody(val8);
			ILProcessor iLProcessor3 = val8.Body.GetILProcessor();
			iLProcessor3.Emit(OpCodes.Ldtoken, val3);
			iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor3.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Modify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor3.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val8);
			MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val9.Body = new MethodBody(val9);
			ILProcessor iLProcessor4 = val9.Body.GetILProcessor();
			iLProcessor4.Emit(OpCodes.Ldtoken, val3);
			iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor4.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Unmodify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor4.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val9);
			EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator)
			{
				AddMethod = val8,
				RemoveMethod = val9
			};
			hookILType.Events.Add(val10);
			return true;
		}

		public TypeDefinition GenerateDelegateFor(MethodDefinition method)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: 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)
			//IL_0101: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: 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_02b1: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			string name = GetFriendlyName((MethodReference)(object)method);
			int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method);
			if (num != 0)
			{
				string suffix = num.ToString();
				do
				{
					name = name + "_" + suffix;
				}
				while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix));
			}
			name = "d_" + name;
			TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate);
			MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
			val2.Body = new MethodBody(val2);
			val.Methods.Add(val2);
			MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType))
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			if (!method.IsStatic)
			{
				TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType);
				if (((TypeReference)method.DeclaringType).IsValueType)
				{
					val4 = (TypeReference)new ByReferenceType(val4);
				}
				((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4));
			}
			Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current = enumerator.Current;
					((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			val3.Body = new MethodBody(val3);
			val.Methods.Add(val3);
			MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			enumerator = ((MethodReference)val3).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current2 = enumerator.Current;
					((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback));
			((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object));
			val5.Body = new MethodBody(val5);
			val.Methods.Add(val5);
			MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult));
			val6.Body = new MethodBody(val6);
			val.Methods.Add(val6);
			return val;
		}

		private string GetFriendlyName(MethodReference method)
		{
			string text = ((MemberReference)method).Name;
			if (text.StartsWith("."))
			{
				text = text.Substring(1);
			}
			return text.Replace('.', '_');
		}

		private string GetFriendlyName(TypeReference type, bool full)
		{
			if (type is TypeSpecification)
			{
				StringBuilder stringBuilder = new StringBuilder();
				BuildFriendlyName(stringBuilder, type, full);
				return stringBuilder.ToString();
			}
			if (!full)
			{
				return ((MemberReference)type).Name;
			}
			return ((MemberReference)type).FullName;
		}

		private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!(type is TypeSpecification))
			{
				builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", ""));
				return;
			}
			if (type.IsByReference)
			{
				builder.Append("ref");
			}
			else if (type.IsPointer)
			{
				builder.Append("ptr");
			}
			BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full);
			if (type.IsArray)
			{
				builder.Append("Array");
			}
		}

		private bool IsPublic(TypeDefinition typeDef)
		{
			if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic))
			{
				return !typeDef.IsNotPublic;
			}
			return false;
		}

		private bool HasPublicArgs(GenericInstanceType typeGen)
		{
			//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)
			Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeReference current = enumerator.Current;
					if (current.IsGenericParameter)
					{
						return false;
					}
					GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null);
					if (val != null && !HasPublicArgs(val))
					{
						return false;
					}
					if (!IsPublic(Extensions.SafeResolve(current)))
					{
						return false;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return true;
		}

		private TypeReference ImportVisible(TypeReference typeRef)
		{
			for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null))
			{
				GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null);
				if (val2 == null || HasPublicArgs(val2))
				{
					TypeDefinition val3 = val;
					while (true)
					{
						if (val3 != null)
						{
							if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters))
							{
								val3 = val3.DeclaringType;
								continue;
							}
							if (!val.IsEnum)
							{
								break;
							}
							typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType;
						}
						try
						{
							return OutputModule.ImportReference(typeRef);
						}
						catch
						{
							return OutputModule.TypeSystem.Object;
						}
					}
				}
				typeRef = val.BaseType;
			}
			return OutputModule.TypeSystem.Object;
		}

		private CustomAttribute GenerateObsolete(string message, bool error)
		{
			//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_0022: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message));
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error));
			return val;
		}

		private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state)
		{
			//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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state));
			return val;
		}
	}
	internal class Program
	{
		private static void Main(string[] args)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version);
			if (args.Length == 0)
			{
				Console.WriteLine("No valid arguments (assembly path) passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			int num = 0;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] == "--namespace" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]);
					continue;
				}
				if (args[i] == "--namespace-il" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]);
					continue;
				}
				if (args[i] == "--orig")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1");
					continue;
				}
				if (args[i] == "--private")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
					continue;
				}
				num = i;
				break;
			}
			if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW")))
			{
				Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			}
			if (num >= args.Length)
			{
				Console.WriteLine("No assembly path passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			string text = args[num];
			string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null);
			text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll"));
			MonoModder val = new MonoModder
			{
				InputPath = text,
				OutputPath = text2,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				val.Read();
				val.MapDependencies();
				if (File.Exists(text2))
				{
					val.Log("[HookGen] Clearing " + text2);
					File.Delete(text2);
				}
				val.Log("[HookGen] Starting HookGenerator");
				HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2));
				ModuleDefinition outputModule = hookGenerator.OutputModule;
				try
				{
					hookGenerator.Generate();
					outputModule.Write(text2);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				val.Log("[HookGen] Done.");
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}
	}
}

plugins/Game Balance/boxofbiscuits97-QuotaRollover-2.1.0/QuotaRollover.dll

Decompiled 10 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using QuotaRollover.Patches;
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("QuotaRollover")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuotaRollover")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("bc931127-211b-4882-bb8e-44687a45d42b")]
[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 QuotaRollover
{
	[BepInPlugin("Boxofbiscuits97.QuotraRollover", "Quota Rollover", "2.1.0")]
	public class QuotaRolloverBase : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("Boxofbiscuits97.QuotraRollover");

		private static QuotaRolloverBase Instance;

		public static ManualLogSource logger;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = ((BaseUnityPlugin)this).Logger;
			logger.LogInfo((object)"Mod Boxofbiscuits97.QuotraRollover is loaded!");
			harmony.PatchAll(typeof(QuotaRolloverBase));
			harmony.PatchAll(typeof(TimeOfDayPatch));
		}
	}
}
namespace QuotaRollover.Patches
{
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		[HarmonyPatch("SetNewProfitQuota")]
		[HarmonyPrefix]
		private static bool GetQuotaFulfilledHost(ref int ___quotaFulfilled, ref int ___profitQuota, out int __state)
		{
			if (TimeOfDay.Instance.timeUntilDeadline <= 0f)
			{
				__state = ___quotaFulfilled - ___profitQuota;
				QuotaRolloverBase.logger.LogInfo((object)$"Host Got New Quota at: {__state} ful: {___quotaFulfilled}");
				return true;
			}
			__state = ___quotaFulfilled;
			return false;
		}

		[HarmonyPatch("SetNewProfitQuota")]
		[HarmonyPostfix]
		private static void SetQuotaFulfilledHost(ref int ___quotaFulfilled, int __state)
		{
			___quotaFulfilled = __state;
			QuotaRolloverBase.logger.LogInfo((object)$"Host Set New Quota at: {__state}");
		}

		[HarmonyPatch("SyncNewProfitQuotaClientRpc")]
		[HarmonyPrefix]
		private static void GetNewQuotaFulfilledClient(ref int ___quotaFulfilled, ref int ___profitQuota, out int __state)
		{
			__state = ___quotaFulfilled - ___profitQuota;
			QuotaRolloverBase.logger.LogInfo((object)$"Client Got New Quota at: {__state}");
		}

		[HarmonyPatch("SyncNewProfitQuotaClientRpc")]
		[HarmonyPostfix]
		private static void SetNewQuotaFulfiledClient(ref int ___quotaFulfilled, int __state)
		{
			if (___quotaFulfilled == 0)
			{
				___quotaFulfilled = __state;
				QuotaRolloverBase.logger.LogInfo((object)$"Client Set New Quota at: {__state}");
			}
		}
	}
}

plugins/Game Balance/malco-Lategame_Upgrades-2.8.8/MoreShipUpgrades.dll

Decompiled 10 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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using MoreShipUpgrades.Managers;
using MoreShipUpgrades.Misc;
using MoreShipUpgrades.UpgradeComponents;
using Newtonsoft.Json;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
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: AssemblyVersion("0.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace MoreShipUpgrades
{
	[BepInPlugin("com.malco.lethalcompany.moreshipupgrades", "More Ship Upgrades", "2.8.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("com.malco.lethalcompany.moreshipupgrades");

		public static Plugin instance;

		public static ManualLogSource mls;

		private AudioClip itemBreak;

		private AudioClip buttonPressed;

		private AudioClip error;

		public static PluginConfig cfg { get; private set; }

		private void Awake()
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			cfg = new PluginConfig(((BaseUnityPlugin)this).Config);
			cfg.InitBindings();
			mls = Logger.CreateLogSource("More Ship Upgrades");
			instance = this;
			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);
					}
				}
			}
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "shipupgrades");
			AssetBundle bundle = AssetBundle.LoadFromFile(text);
			GameObject val = new GameObject("UpgradeBus");
			val.AddComponent<UpgradeBus>();
			UpgradeBus.instance.version = "2.8.0";
			UpgradeBus.instance.UpgradeAssets = bundle;
			UpgradeBus.instance.internNames = AssetBundleHandler.GetInfoFromJSON("InternNames").Split(",");
			UpgradeBus.instance.internInterests = AssetBundleHandler.GetInfoFromJSON("InternInterests").Split(",");
			SetupModStore(ref bundle);
			SetupIntroScreen(ref bundle);
			SetupItems();
			SetupPerks();
			harmony.PatchAll();
			mls.LogDebug((object)"LGU has been patched");
		}

		public void sendModInfo()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				if (pluginInfo.Value.Metadata.GUID.Contains("ModSync"))
				{
					try
					{
						List<string> list = new List<string> { "malco", "LateGameUpgrades" };
						((Component)pluginInfo.Value.Instance).BroadcastMessage("getModInfo", (object)list, (SendMessageOptions)1);
						break;
					}
					catch (Exception)
					{
						mls.LogDebug((object)"Failed to send info to ModSync, go yell at Minx");
						break;
					}
				}
			}
		}

		private void SetupModStore(ref AssetBundle bundle)
		{
			GameObject val = AssetBundleHandler.TryLoadGameObjectAsset(ref bundle, "Assets/ShipUpgrades/LGUStore.prefab");
			if (!((Object)(object)val == (Object)null))
			{
				val.AddComponent<LGUStore>();
				NetworkPrefabs.RegisterNetworkPrefab(val);
				UpgradeBus.instance.modStorePrefab = val;
			}
		}

		private void SetupIntroScreen(ref AssetBundle bundle)
		{
			UpgradeBus.instance.introScreen = AssetBundleHandler.TryLoadGameObjectAsset(ref bundle, "Assets/ShipUpgrades/IntroScreen.prefab");
			if ((Object)(object)UpgradeBus.instance.introScreen != (Object)null)
			{
				UpgradeBus.instance.introScreen.AddComponent<IntroScreenScript>();
			}
		}

		private void SetupItems()
		{
			SetupTeleporterButtons();
			SetupNightVision();
			SetupMedkit();
			SetupPeeper();
			SetupSamples();
			SetupDivingKit();
		}

		private void SetupSamples()
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>
			{
				{ "centipede", cfg.SNARE_FLEA_SAMPLE_MINIMUM_VALUE },
				{ "bunker spider", cfg.BUNKER_SPIDER_SAMPLE_MINIMUM_VALUE },
				{ "hoarding bug", cfg.HOARDING_BUG_SAMPLE_MINIMUM_VALUE },
				{ "flowerman", cfg.BRACKEN_SAMPLE_MINIMUM_VALUE },
				{ "mouthdog", cfg.EYELESS_DOG_SAMPLE_MINIMUM_VALUE },
				{ "baboon hawk", cfg.BABOON_HAWK_SAMPLE_MINIMUM_VALUE },
				{ "crawler", cfg.THUMPER_SAMPLE_MINIMUM_VALUE }
			};
			Dictionary<string, int> dictionary2 = new Dictionary<string, int>
			{
				{ "centipede", cfg.SNARE_FLEA_SAMPLE_MAXIMUM_VALUE },
				{ "bunker spider", cfg.BUNKER_SPIDER_SAMPLE_MAXIMUM_VALUE },
				{ "hoarding bug", cfg.HOARDING_BUG_SAMPLE_MAXIMUM_VALUE },
				{ "flowerman", cfg.BRACKEN_SAMPLE_MAXIMUM_VALUE },
				{ "mouthdog", cfg.EYELESS_DOG_SAMPLE_MAXIMUM_VALUE },
				{ "baboon hawk", cfg.BABOON_HAWK_SAMPLE_MAXIMUM_VALUE },
				{ "crawler", cfg.THUMPER_SAMPLE_MAXIMUM_VALUE }
			};
			foreach (string key in AssetBundleHandler.samplePaths.Keys)
			{
				Item itemObject = AssetBundleHandler.GetItemObject(key);
				SampleItem sampleItem = itemObject.spawnPrefab.AddComponent<SampleItem>();
				((GrabbableObject)sampleItem).grabbable = true;
				((GrabbableObject)sampleItem).grabbableToEnemies = true;
				((GrabbableObject)sampleItem).itemProperties = itemObject;
				((GrabbableObject)sampleItem).itemProperties.minValue = dictionary[key];
				((GrabbableObject)sampleItem).itemProperties.maxValue = dictionary2[key];
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				UpgradeBus.instance.samplePrefabs.Add(key, itemObject.spawnPrefab);
			}
		}

		private void SetupTeleporterButtons()
		{
			itemBreak = AssetBundleHandler.GetAudioClip("Break");
			error = AssetBundleHandler.GetAudioClip("Error");
			buttonPressed = AssetBundleHandler.GetAudioClip("Button Press");
			if (!((Object)(object)itemBreak == (Object)null) && !((Object)(object)error == (Object)null) && !((Object)(object)buttonPressed == (Object)null))
			{
				SetupRegularTeleporterButton();
				SetupAdvancedTeleporterButton();
			}
		}

		private void SetupRegularTeleporterButton()
		{
			Item itemObject = AssetBundleHandler.GetItemObject("Portable Tele");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.itemName = "Portable Tele";
				itemObject.itemId = 492012;
				TPButtonScript tPButtonScript = itemObject.spawnPrefab.AddComponent<TPButtonScript>();
				((GrabbableObject)tPButtonScript).itemProperties = itemObject;
				((GrabbableObject)tPButtonScript).grabbable = true;
				((GrabbableObject)tPButtonScript).grabbableToEnemies = true;
				tPButtonScript.ItemBreak = itemBreak;
				((GrabbableObject)tPButtonScript).useCooldown = 2f;
				tPButtonScript.error = error;
				tPButtonScript.buttonPress = buttonPressed;
				itemObject.creditsWorth = cfg.WEAK_TELE_PRICE;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				if (cfg.WEAK_TELE_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					val.displayText = string.Format(AssetBundleHandler.GetInfoFromJSON("Portable Tele"), (int)(cfg.CHANCE_TO_BREAK * 100f));
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupAdvancedTeleporterButton()
		{
			Item itemObject = AssetBundleHandler.GetItemObject("Advanced Portable Tele");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.creditsWorth = cfg.ADVANCED_TELE_PRICE;
				itemObject.itemName = "Advanced Portable Tele";
				itemObject.itemId = 492013;
				AdvTPButtonScript advTPButtonScript = itemObject.spawnPrefab.AddComponent<AdvTPButtonScript>();
				((GrabbableObject)advTPButtonScript).itemProperties = itemObject;
				((GrabbableObject)advTPButtonScript).grabbable = true;
				((GrabbableObject)advTPButtonScript).useCooldown = 2f;
				((GrabbableObject)advTPButtonScript).grabbableToEnemies = true;
				advTPButtonScript.ItemBreak = itemBreak;
				advTPButtonScript.error = error;
				advTPButtonScript.buttonPress = buttonPressed;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				if (cfg.ADVANCED_TELE_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					val.displayText = string.Format(AssetBundleHandler.GetInfoFromJSON("Advanced Portable Tele"), (int)(cfg.ADV_CHANCE_TO_BREAK * 100f));
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupNightVision()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			Item itemObject = AssetBundleHandler.GetItemObject("Night Vision");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.creditsWorth = cfg.NIGHT_VISION_PRICE;
				itemObject.spawnPrefab.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
				itemObject.itemId = 492014;
				NightVisionItemScript nightVisionItemScript = itemObject.spawnPrefab.AddComponent<NightVisionItemScript>();
				((GrabbableObject)nightVisionItemScript).itemProperties = itemObject;
				((GrabbableObject)nightVisionItemScript).grabbable = true;
				((GrabbableObject)nightVisionItemScript).useCooldown = 2f;
				((GrabbableObject)nightVisionItemScript).grabbableToEnemies = true;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				UpgradeBus.instance.nightVisionPrefab = itemObject.spawnPrefab;
				if (cfg.NIGHT_VISION_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					string arg = ((cfg.NIGHT_VISION_INDIVIDUAL || UpgradeBus.instance.cfg.SHARED_UPGRADES) ? "one" : "all");
					string arg2 = (cfg.LOSE_NIGHT_VIS_ON_DEATH ? "be" : "not be");
					val.displayText = string.Format(AssetBundleHandler.GetInfoFromJSON("Night Vision"), arg, arg2);
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupDivingKit()
		{
			Item itemObject = AssetBundleHandler.GetItemObject("Diving Kit");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.creditsWorth = cfg.DIVEKIT_PRICE;
				itemObject.itemId = 492015;
				itemObject.twoHanded = cfg.DIVEKIT_TWO_HANDED;
				itemObject.weight = cfg.DIVEKIT_WEIGHT;
				itemObject.itemSpawnsOnGround = true;
				DivingKitScript divingKitScript = itemObject.spawnPrefab.AddComponent<DivingKitScript>();
				((GrabbableObject)divingKitScript).itemProperties = itemObject;
				((GrabbableObject)divingKitScript).grabbable = true;
				((GrabbableObject)divingKitScript).grabbableToEnemies = true;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				if (cfg.DIVEKIT_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					string arg = (cfg.DIVEKIT_TWO_HANDED ? "two" : "one");
					val.displayText = $"DIVING KIT - ${cfg.DIVEKIT_PRICE}\n\nBreath underwater.\nWeights {Mathf.RoundToInt((itemObject.weight - 1f) * 100f)} lbs and is {arg} handed.\n\n";
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupMedkit()
		{
			Item itemObject = AssetBundleHandler.GetItemObject("Medkit");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.creditsWorth = cfg.MEDKIT_PRICE;
				itemObject.itemSpawnsOnGround = true;
				itemObject.itemId = 492016;
				MedkitScript medkitScript = itemObject.spawnPrefab.AddComponent<MedkitScript>();
				((GrabbableObject)medkitScript).itemProperties = itemObject;
				((GrabbableObject)medkitScript).grabbable = true;
				((GrabbableObject)medkitScript).useCooldown = 2f;
				((GrabbableObject)medkitScript).grabbableToEnemies = true;
				medkitScript.error = error;
				medkitScript.use = buttonPressed;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				if (cfg.MEDKIT_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					val.displayText = $"MEDKIT - ${cfg.MEDKIT_PRICE}\n\nLeft click to heal yourself for {cfg.MEDKIT_HEAL_VALUE} health.\nCan be used {cfg.MEDKIT_USES} times.\n";
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupPeeper()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Item itemObject = AssetBundleHandler.GetItemObject("Peeper");
			if (!((Object)(object)itemObject == (Object)null))
			{
				itemObject.creditsWorth = cfg.PEEPER_PRICE;
				itemObject.twoHanded = false;
				itemObject.itemId = 492015;
				itemObject.twoHandedAnimation = false;
				itemObject.spawnPrefab.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
				coilHeadItem coilHeadItem = itemObject.spawnPrefab.AddComponent<coilHeadItem>();
				((GrabbableObject)coilHeadItem).itemProperties = itemObject;
				((GrabbableObject)coilHeadItem).grabbable = true;
				((GrabbableObject)coilHeadItem).grabbableToEnemies = true;
				NetworkPrefabs.RegisterNetworkPrefab(itemObject.spawnPrefab);
				if (cfg.PEEPER_ENABLED)
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					val.displayText = "Looks at coil heads, don't lose it\n";
					Items.RegisterShopItem(itemObject, (TerminalNode)null, (TerminalNode)null, val, itemObject.creditsWorth);
				}
			}
		}

		private void SetupPerks()
		{
			SetupBeekeeper();
			SetupProteinPowder();
			SetupBiggerLungs();
			SetupRunningShoes();
			SetupStrongLegs();
			SetupMalwareBroadcaster();
			SetupNightVisionBattery();
			SetupDiscombobulator();
			SetupBetterScanner();
			SetupWalkieGPS();
			SetupBackMuscles();
			SetupInterns();
			SetupPager();
			SetupLightningRod();
			SetupLocksmith();
			SetupPlayerHealth();
			SetupHunter();
			SetupExtendDeadline();
		}

		private void SetupBeekeeper()
		{
			SetupGenericPerk<beekeeperScript>(beekeeperScript.UPGRADE_NAME);
		}

		private void SetupHunter()
		{
			SetupGenericPerk<hunterScript>(hunterScript.UPGRADE_NAME);
		}

		private void SetupProteinPowder()
		{
			SetupGenericPerk<proteinPowderScript>(proteinPowderScript.UPGRADE_NAME);
		}

		private void SetupBiggerLungs()
		{
			SetupGenericPerk<biggerLungScript>(biggerLungScript.UPGRADE_NAME);
		}

		private void SetupRunningShoes()
		{
			SetupGenericPerk<runningShoeScript>(runningShoeScript.UPGRADE_NAME);
		}

		private void SetupStrongLegs()
		{
			SetupGenericPerk<strongLegsScript>(strongLegsScript.UPGRADE_NAME);
		}

		private void SetupMalwareBroadcaster()
		{
			SetupGenericPerk<trapDestroyerScript>(trapDestroyerScript.UPGRADE_NAME);
		}

		private void SetupNightVisionBattery()
		{
			SetupGenericPerk<nightVisionScript>(nightVisionScript.UPGRADE_NAME);
		}

		private void SetupDiscombobulator()
		{
			AudioClip audioClip = AssetBundleHandler.GetAudioClip("Flashbang");
			if ((Object)(object)audioClip != (Object)null)
			{
				UpgradeBus.instance.flashNoise = audioClip;
			}
			SetupGenericPerk<terminalFlashScript>(terminalFlashScript.UPGRADE_NAME);
		}

		private void SetupBetterScanner()
		{
			SetupGenericPerk<strongerScannerScript>(strongerScannerScript.UPGRADE_NAME);
		}

		private void SetupWalkieGPS()
		{
			SetupGenericPerk<walkieScript>(walkieScript.UPGRADE_NAME);
		}

		private void SetupBackMuscles()
		{
			SetupGenericPerk<exoskeletonScript>(exoskeletonScript.UPGRADE_NAME);
		}

		private void SetupInterns()
		{
			SetupGenericPerk<defibScript>(defibScript.UPGRADE_NAME);
		}

		private void SetupPager()
		{
			SetupGenericPerk<pagerScript>(pagerScript.UPGRADE_NAME);
		}

		private void SetupLightningRod()
		{
			SetupGenericPerk<lightningRodScript>(lightningRodScript.UPGRADE_NAME);
		}

		private void SetupLocksmith()
		{
			SetupGenericPerk<lockSmithScript>(lockSmithScript.UPGRADE_NAME);
		}

		private void SetupPlayerHealth()
		{
			SetupGenericPerk<playerHealthScript>(playerHealthScript.UPGRADE_NAME);
		}

		private void SetupExtendDeadline()
		{
			SetupGenericPerk<ExtendDeadlineScript>(ExtendDeadlineScript.UPGRADE_NAME);
		}

		private void SetupGenericPerk<T>(string upgradeName) where T : Component
		{
			GameObject perkGameObject = AssetBundleHandler.GetPerkGameObject(upgradeName);
			if (Object.op_Implicit((Object)(object)perkGameObject))
			{
				perkGameObject.AddComponent<T>();
				NetworkPrefabs.RegisterNetworkPrefab(perkGameObject);
			}
		}
	}
}
namespace MoreShipUpgrades.UpgradeComponents
{
	internal class AdvTPButtonScript : GrabbableObject
	{
		public AudioClip ItemBreak;

		public AudioClip error;

		public AudioClip buttonPress;

		private AudioSource audio;

		public override void Start()
		{
			((GrabbableObject)this).Start();
			audio = ((Component)this).GetComponent<AudioSource>();
		}

		public override void DiscardItem()
		{
			base.playerHeldBy.activatingItem = false;
			((GrabbableObject)this).DiscardItem();
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (!Mouse.current.leftButton.isPressed)
			{
				return;
			}
			audio.PlayOneShot(buttonPress);
			if (base.itemUsedUp)
			{
				audio.PlayOneShot(error);
				return;
			}
			ShipTeleporter[] array = Object.FindObjectsOfType<ShipTeleporter>();
			ShipTeleporter val = null;
			ShipTeleporter[] array2 = array;
			foreach (ShipTeleporter val2 in array2)
			{
				if (!val2.isInverseTeleporter)
				{
					val = val2;
					break;
				}
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				audio.PlayOneShot(error);
				return;
			}
			int num = -1;
			for (int j = 0; j < StartOfRound.Instance.mapScreen.radarTargets.Count(); j++)
			{
				if (!((Object)(object)((Component)StartOfRound.Instance.mapScreen.radarTargets[j].transform).gameObject.GetComponent<PlayerControllerB>() != (Object)(object)base.playerHeldBy))
				{
					num = j;
					break;
				}
			}
			if (num == -1)
			{
				StartOfRound.Instance.mapScreen.targetedPlayer = base.playerHeldBy;
				UpgradeBus.instance.TPButtonPressed = true;
				val.PressTeleportButtonOnLocalClient();
			}
			else
			{
				StartOfRound.Instance.mapScreen.SwitchRadarTargetAndSync(num);
				((MonoBehaviour)this).StartCoroutine(WaitToTP(val));
			}
		}

		private IEnumerator WaitToTP(ShipTeleporter tele)
		{
			yield return (object)new WaitForSeconds(0.15f);
			if (UpgradeBus.instance.cfg.ADV_KEEP_ITEMS_ON_TELE)
			{
				ReqUpdateTpDropStatusServerRpc();
			}
			tele.PressTeleportButtonOnLocalClient();
			if (Random.Range(0f, 1f) < UpgradeBus.instance.cfg.ADV_CHANCE_TO_BREAK)
			{
				audio.PlayOneShot(ItemBreak);
				base.itemUsedUp = true;
				HUDManager.Instance.DisplayTip("TELEPORTER BROKE!", "The teleporter button has suffered irreparable damage and destroyed itself!", true, false, "LC_Tip1");
				base.playerHeldBy.DespawnHeldObject();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ReqUpdateTpDropStatusServerRpc()
		{
			//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(3988692149u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3988692149u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ChangeTPButtonPressedClientRpc();
				}
			}
		}

		[ClientRpc]
		private void ChangeTPButtonPressedClientRpc()
		{
			//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(2793166939u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2793166939u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					UpgradeBus.instance.TPButtonPressed = true;
				}
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_AdvTPButtonScript()
		{
			//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(3988692149u, new RpcReceiveHandler(__rpc_handler_3988692149));
			NetworkManager.__rpc_func_table.Add(2793166939u, new RpcReceiveHandler(__rpc_handler_2793166939));
		}

		private static void __rpc_handler_3988692149(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;
				((AdvTPButtonScript)(object)target).ReqUpdateTpDropStatusServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2793166939(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;
				((AdvTPButtonScript)(object)target).ChangeTPButtonPressedClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "AdvTPButtonScript";
		}
	}
	internal class beekeeperScript : BaseUpgrade
	{
		private static LGULogger logger = new LGULogger(UPGRADE_NAME);

		public static string UPGRADE_NAME = "Beekeeper";

		public static string PRICES_DEFAULT = "225,280,340";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			UpgradeBus.instance.beeLevel++;
			if (UpgradeBus.instance.beeLevel == UpgradeBus.instance.cfg.BEEKEEPER_UPGRADE_PRICES.Split(',').Length)
			{
				LGUStore.instance.ToggleIncreaseHivePriceServerRpc();
			}
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.beekeeper = true;
		}

		public override void Register()
		{
			base.Register();
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.beeLevel = 0;
			UpgradeBus.instance.beekeeper = false;
		}

		public static int CalculateBeeDamage(int damageNumber)
		{
			if (!UpgradeBus.instance.beekeeper)
			{
				return damageNumber;
			}
			return Mathf.Clamp((int)((float)damageNumber * (UpgradeBus.instance.cfg.BEEKEEPER_DAMAGE_MULTIPLIER - (float)UpgradeBus.instance.beeLevel * UpgradeBus.instance.cfg.BEEKEEPER_DAMAGE_MULTIPLIER_INCREMENT)), 0, damageNumber);
		}

		public static int GetHiveScrapValue(int originalValue)
		{
			if (!UpgradeBus.instance.increaseHivePrice)
			{
				return originalValue;
			}
			return (int)((float)originalValue * UpgradeBus.instance.cfg.BEEKEEPER_HIVE_VALUE_INCREASE);
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "beekeeperScript";
		}
	}
	internal class biggerLungScript : BaseUpgrade
	{
		private static LGULogger logger;

		public static string UPGRADE_NAME = "Bigger Lungs";

		public static string PRICES_DEFAULT = "350,450,550";

		private int currentLevel = 0;

		private static bool active = false;

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			logger = new LGULogger(UPGRADE_NAME);
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			localPlayer.sprintTime += UpgradeBus.instance.cfg.SPRINT_TIME_INCREMENT;
			logger.LogDebug($"Adding {UpgradeBus.instance.cfg.SPRINT_TIME_INCREMENT} to the player's sprint time...");
			UpgradeBus.instance.lungLevel++;
			currentLevel++;
		}

		public override void load()
		{
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			if (!active)
			{
				logger.LogDebug($"Adding {UpgradeBus.instance.cfg.SPRINT_TIME_INCREASE_UNLOCK} to the player's sprint time...");
				localPlayer.sprintTime += UpgradeBus.instance.cfg.SPRINT_TIME_INCREASE_UNLOCK;
			}
			UpgradeBus.instance.biggerLungs = true;
			active = true;
			base.load();
			float num = 0f;
			for (int i = 1; i < UpgradeBus.instance.lungLevel + 1; i++)
			{
				if (i > currentLevel)
				{
					logger.LogDebug($"Adding {UpgradeBus.instance.cfg.SPRINT_TIME_INCREMENT} to the player's sprint time...");
					num += UpgradeBus.instance.cfg.SPRINT_TIME_INCREMENT;
				}
			}
			localPlayer.sprintTime += num;
			currentLevel = UpgradeBus.instance.lungLevel;
		}

		public override void Unwind()
		{
			PlayerControllerB player = UpgradeBus.instance.GetLocalPlayer();
			if (active)
			{
				ResetBiggerLungsBuff(ref player);
			}
			base.Unwind();
			UpgradeBus.instance.biggerLungs = false;
			UpgradeBus.instance.lungLevel = 0;
			active = false;
			currentLevel = 0;
		}

		public override void Register()
		{
			base.Register();
		}

		public static void ResetBiggerLungsBuff(ref PlayerControllerB player)
		{
			float num = UpgradeBus.instance.cfg.SPRINT_TIME_INCREASE_UNLOCK;
			for (int i = 0; i < UpgradeBus.instance.lungLevel; i++)
			{
				num += UpgradeBus.instance.cfg.SPRINT_TIME_INCREMENT;
			}
			logger.LogDebug($"Removing {player.playerUsername}'s sprint time boost ({player.sprintTime}) with a boost of {num}");
			PlayerControllerB obj = player;
			obj.sprintTime -= num;
			logger.LogDebug("Upgrade reset on " + player.playerUsername);
			active = false;
		}

		public static float ApplyPossibleIncreasedStaminaRegen(float regenValue)
		{
			if (!UpgradeBus.instance.biggerLungs || UpgradeBus.instance.lungLevel < 0)
			{
				return regenValue;
			}
			return regenValue * UpgradeBus.instance.cfg.BIGGER_LUNGS_STAMINA_REGEN_INCREASE;
		}

		public static float ApplyPossibleReducedJumpStaminaCost(float jumpCost)
		{
			if (!UpgradeBus.instance.biggerLungs || UpgradeBus.instance.lungLevel < 1)
			{
				return jumpCost;
			}
			return jumpCost * UpgradeBus.instance.cfg.BIGGER_LUNGS_JUMP_STAMINA_COST_DECREASE;
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "biggerLungScript";
		}
	}
	public class coilHeadItem : GrabbableObject
	{
		private bool Active;

		private Animator anim;

		public override void Start()
		{
			((GrabbableObject)this).Start();
			anim = ((Component)this).GetComponent<Animator>();
			UpgradeBus.instance.coilHeadItems.Add(this);
		}

		public override void Update()
		{
			((GrabbableObject)this).Update();
			SetActive(!base.isHeld && !base.isHeldByEnemy);
		}

		private void SetActive(bool enable)
		{
			Active = enable;
			anim.SetBool("Grounded", enable);
		}

		public bool HasLineOfSightToPosition(Vector3 pos, int range = 60)
		{
			//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_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)
			if (!Active)
			{
				return false;
			}
			float num = Vector3.Distance(((Component)this).transform.position, pos);
			return num < (float)range && !Physics.Linecast(((Component)this).transform.position, pos, StartOfRound.Instance.collidersRoomDefaultAndFoliage, (QueryTriggerInteraction)1);
		}

		public static bool HasLineOfSightToPeepers(Vector3 springPosition)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			foreach (coilHeadItem coilHeadItem in UpgradeBus.instance.coilHeadItems)
			{
				if ((Object)(object)coilHeadItem == (Object)null)
				{
					UpgradeBus.instance.coilHeadItems.Remove(coilHeadItem);
				}
				else if (coilHeadItem.HasLineOfSightToPosition(springPosition))
				{
					return true;
				}
			}
			return false;
		}

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

		protected internal override string __getTypeName()
		{
			return "coilHeadItem";
		}
	}
	public class defibScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Interns";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
			UpgradeBus.instance.internScript = this;
		}

		public override void Register()
		{
			base.Register();
		}

		[ServerRpc(RequireOwnership = false)]
		public void ReviveTargetedPlayerServerRpc()
		{
			//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)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: 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_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			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(1556828106u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1556828106u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ReviveTargetedPlayerClientRpc();
					Vector3 position = RoundManager.Instance.insideAINodes[Random.Range(0, RoundManager.Instance.insideAINodes.Length)].transform.position;
					position = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(position, 10f, default(NavMeshHit));
					NetworkBehaviourReference netRef = default(NetworkBehaviourReference);
					((NetworkBehaviourReference)(ref netRef))..ctor((NetworkBehaviour)(object)StartOfRound.Instance.mapScreen.targetedPlayer);
					TelePlayerClientRpc(position, netRef);
				}
			}
		}

		[ClientRpc]
		private void TelePlayerClientRpc(Vector3 vector, NetworkBehaviourReference netRef)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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)
			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(52528808u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref vector);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netRef, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 52528808u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkBehaviour val3 = default(NetworkBehaviour);
				((NetworkBehaviourReference)(ref netRef)).TryGet(ref val3, (NetworkManager)null);
				if ((Object)(object)val3 != (Object)null)
				{
					((Component)((Component)val3).transform).GetComponent<PlayerControllerB>().TeleportPlayer(vector, false, 0f, false, true);
				}
			}
		}

		[ClientRpc]
		private void ReviveTargetedPlayerClientRpc()
		{
			//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)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1174848284u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1174848284u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			PlayerControllerB targetedPlayer = StartOfRound.Instance.mapScreen.targetedPlayer;
			int num = (UpgradeBus.instance.playerHPs.ContainsKey(targetedPlayer.playerSteamId) ? UpgradeBus.instance.playerHPs[targetedPlayer.playerSteamId] : 100);
			targetedPlayer.ResetPlayerBloodObjects(targetedPlayer.isPlayerDead);
			if (targetedPlayer.isPlayerDead || targetedPlayer.isPlayerControlled)
			{
				targetedPlayer.isClimbingLadder = false;
				targetedPlayer.ResetZAndXRotation();
				((Collider)targetedPlayer.thisController).enabled = true;
				targetedPlayer.health = num;
				targetedPlayer.disableLookInput = false;
				if (targetedPlayer.isPlayerDead)
				{
					targetedPlayer.isPlayerDead = false;
					targetedPlayer.isPlayerControlled = true;
					targetedPlayer.isInElevator = false;
					targetedPlayer.isInHangarShipRoom = false;
					targetedPlayer.isInsideFactory = true;
					targetedPlayer.wasInElevatorLastFrame = false;
					StartOfRound.Instance.SetPlayerObjectExtrapolate(false);
					targetedPlayer.setPositionOfDeadPlayer = false;
					((Behaviour)targetedPlayer.helmetLight).enabled = false;
					targetedPlayer.Crouch(false);
					targetedPlayer.criticallyInjured = false;
					if ((Object)(object)targetedPlayer.playerBodyAnimator != (Object)null)
					{
						targetedPlayer.playerBodyAnimator.SetBool("Limp", false);
					}
					targetedPlayer.bleedingHeavily = false;
					targetedPlayer.activatingItem = false;
					targetedPlayer.twoHanded = false;
					targetedPlayer.inSpecialInteractAnimation = false;
					targetedPlayer.disableSyncInAnimation = false;
					targetedPlayer.inAnimationWithEnemy = null;
					targetedPlayer.holdingWalkieTalkie = false;
					targetedPlayer.speakingToWalkieTalkie = false;
					targetedPlayer.isSinking = false;
					targetedPlayer.isUnderwater = false;
					targetedPlayer.sinkingValue = 0f;
					targetedPlayer.statusEffectAudio.Stop();
					targetedPlayer.DisableJetpackControlsLocally();
					targetedPlayer.health = num;
					targetedPlayer.mapRadarDotAnimator.SetBool("dead", false);
					targetedPlayer.deadBody = null;
					if ((Object)(object)targetedPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)
					{
						HUDManager.Instance.gasHelmetAnimator.SetBool("gasEmitting", false);
						targetedPlayer.hasBegunSpectating = false;
						HUDManager.Instance.RemoveSpectateUI();
						HUDManager.Instance.gameOverAnimator.SetTrigger("revive");
						targetedPlayer.hinderedMultiplier = 1f;
						targetedPlayer.isMovementHindered = 0;
						targetedPlayer.sourcesCausingSinking = 0;
						HUDManager.Instance.HideHUD(false);
					}
				}
				SoundManager.Instance.earsRingingTimer = 0f;
				targetedPlayer.voiceMuffledByEnemy = false;
				if ((Object)(object)targetedPlayer.currentVoiceChatIngameSettings == (Object)null)
				{
					StartOfRound.Instance.RefreshPlayerVoicePlaybackObjects();
				}
				if ((Object)(object)targetedPlayer.currentVoiceChatIngameSettings != (Object)null)
				{
					if ((Object)(object)targetedPlayer.currentVoiceChatIngameSettings.voiceAudio == (Object)null)
					{
						targetedPlayer.currentVoiceChatIngameSettings.InitializeComponents();
					}
					if ((Object)(object)targetedPlayer.currentVoiceChatIngameSettings.voiceAudio == (Object)null)
					{
						return;
					}
					((Component)targetedPlayer.currentVoiceChatIngameSettings.voiceAudio).GetComponent<OccludeAudio>().overridingLowPass = false;
				}
			}
			StartOfRound instance = StartOfRound.Instance;
			instance.livingPlayers++;
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)targetedPlayer)
			{
				targetedPlayer.bleedingHeavily = false;
				targetedPlayer.criticallyInjured = false;
				targetedPlayer.playerBodyAnimator.SetBool("Limp", false);
				targetedPlayer.health = num;
				HUDManager.Instance.UpdateHealthUI(num, false);
				targetedPlayer.spectatedPlayerScript = null;
				((Behaviour)HUDManager.Instance.audioListenerLowPass).enabled = false;
				StartOfRound.Instance.SetSpectateCameraToGameOverMode(false, targetedPlayer);
				TimeOfDay.Instance.DisableAllWeather(false);
				StartOfRound.Instance.UpdatePlayerVoiceEffects();
				((Renderer)targetedPlayer.thisPlayerModel).enabled = true;
			}
			else
			{
				((Renderer)targetedPlayer.thisPlayerModel).enabled = true;
				((Renderer)targetedPlayer.thisPlayerModelLOD1).enabled = true;
				((Renderer)targetedPlayer.thisPlayerModelLOD2).enabled = true;
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_defibScript()
		{
			//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(1556828106u, new RpcReceiveHandler(__rpc_handler_1556828106));
			NetworkManager.__rpc_func_table.Add(52528808u, new RpcReceiveHandler(__rpc_handler_52528808));
			NetworkManager.__rpc_func_table.Add(1174848284u, new RpcReceiveHandler(__rpc_handler_1174848284));
		}

		private static void __rpc_handler_1556828106(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;
				((defibScript)(object)target).ReviveTargetedPlayerServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_52528808(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//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)
			//IL_0051: 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)
			//IL_0060: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 vector = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref vector);
				NetworkBehaviourReference netRef = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netRef, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((defibScript)(object)target).TelePlayerClientRpc(vector, netRef);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1174848284(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;
				((defibScript)(object)target).ReviveTargetedPlayerClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "defibScript";
		}
	}
	internal class DivingKitScript : GrabbableObject
	{
		public override void Update()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null && (Object)(object)base.playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				StartOfRound.Instance.drowningTimer = 1f;
			}
			((GrabbableObject)this).Update();
		}

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

		protected internal override string __getTypeName()
		{
			return "DivingKitScript";
		}
	}
	internal class exoskeletonScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Back Muscles";

		public static string PRICES_DEFAULT = "600,700,800";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			UpgradeBus.instance.backLevel++;
			UpdatePlayerWeight();
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.exoskeleton = true;
			UpdatePlayerWeight();
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.exoskeleton = false;
			UpgradeBus.instance.backLevel = 0;
			UpdatePlayerWeight();
		}

		public override void Register()
		{
			base.Register();
		}

		public static float DecreasePossibleWeight(float defaultWeight)
		{
			if (!UpgradeBus.instance.exoskeleton)
			{
				return defaultWeight;
			}
			return defaultWeight * (UpgradeBus.instance.cfg.CARRY_WEIGHT_REDUCTION - (float)UpgradeBus.instance.backLevel * UpgradeBus.instance.cfg.CARRY_WEIGHT_INCREMENT);
		}

		public static void UpdatePlayerWeight()
		{
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (localPlayerController.ItemSlots.Length == 0)
			{
				return;
			}
			UpgradeBus.instance.alteredWeight = 1f;
			for (int i = 0; i < localPlayerController.ItemSlots.Length; i++)
			{
				GrabbableObject val = localPlayerController.ItemSlots[i];
				if (!((Object)(object)val == (Object)null))
				{
					UpgradeBus.instance.alteredWeight += Mathf.Clamp(DecreasePossibleWeight(val.itemProperties.weight - 1f), 0f, 10f);
				}
			}
			localPlayerController.carryWeight = UpgradeBus.instance.alteredWeight;
			if (localPlayerController.carryWeight < 1f)
			{
				localPlayerController.carryWeight = 1f;
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "exoskeletonScript";
		}
	}
	public class ExtendDeadlineScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Extend Deadline";

		public static string ENABLED_SECTION = "Enable " + UPGRADE_NAME;

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
			UpgradeBus.instance.extendScript = this;
		}

		public override void Register()
		{
			base.Register();
		}

		[ClientRpc]
		public void ExtendDeadlineClientRpc(int days)
		{
			//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(1474935373u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, days);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1474935373u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					TimeOfDay instance = TimeOfDay.Instance;
					instance.timeUntilDeadline += TimeOfDay.Instance.totalTime * (float)days;
					TimeOfDay.Instance.UpdateProfitQuotaCurrentTime();
					TimeOfDay.Instance.SyncTimeClientRpc(TimeOfDay.Instance.globalTime, (int)TimeOfDay.Instance.timeUntilDeadline);
				}
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_ExtendDeadlineScript()
		{
			//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(1474935373u, new RpcReceiveHandler(__rpc_handler_1474935373));
		}

		private static void __rpc_handler_1474935373(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 days = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref days);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((ExtendDeadlineScript)(object)target).ExtendDeadlineClientRpc(days);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "ExtendDeadlineScript";
		}
	}
	internal class hunterScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Hunter";

		private static LGULogger logger = new LGULogger(UPGRADE_NAME);

		private static Dictionary<string, string> monsterNames = new Dictionary<string, string>
		{
			{ "hoarding", "Hoarding Bug" },
			{ "hoarding bug", "Hoarding Bug" },
			{ "snare", "Snare Flea" },
			{ "flea", "Snare Flea" },
			{ "snare flea", "Snare Flea" },
			{ "centipede", "Snare Flea" },
			{ "bunker spider", "Bunker Spider" },
			{ "bunker", "Bunker Spider" },
			{ "bunk", "Bunker Spider" },
			{ "spider", "Bunker Spider" },
			{ "baboon hawk", "Baboon Hawk" },
			{ "baboon", "Baboon Hawk" },
			{ "hawk", "Baboon Hawk" },
			{ "flowerman", "Bracken" },
			{ "bracken", "Bracken" },
			{ "crawler", "Half/Thumper" },
			{ "half", "Half/Thumper" },
			{ "thumper", "Half/Thumper" },
			{ "mouthdog", "Eyeless Dog" },
			{ "eyeless dog", "Eyeless Dog" },
			{ "eyeless", "Eyeless Dog" },
			{ "dog", "Eyeless Dog" }
		};

		public static Dictionary<int, string[]> tiers;

		public static void SetupTierList()
		{
			logger = new LGULogger(UPGRADE_NAME);
			tiers = new Dictionary<int, string[]>();
			string[] array = UpgradeBus.instance.cfg.HUNTER_SAMPLE_TIERS.ToLower().Split('-');
			tiers[0] = (from x in array[0].Split(",")
				select x.Trim()).ToArray();
			for (int i = 1; i < array.Length; i++)
			{
				tiers[i] = tiers[i - 1].Concat(from x in array[i].Split(",")
					select x.Trim()).ToArray();
			}
		}

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			UpgradeBus.instance.huntLevel++;
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.hunter = true;
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.hunter = false;
			UpgradeBus.instance.huntLevel = 0;
		}

		public override void Register()
		{
			base.Register();
		}

		public static string GetHunterInfo(int level, int price)
		{
			string text = ((level == 1) ? string.Join(", ", tiers[level - 1]) : string.Join(", ", tiers[level - 1].Except(tiers[level - 2]).ToArray()));
			string text2 = "";
			string[] array = text.Split(", ");
			foreach (string text3 in array)
			{
				logger.LogDebug(text3.Trim().ToLower());
				logger.LogDebug(monsterNames[text3.Trim().ToLower()]);
				text2 = text2 + monsterNames[text3.Trim().ToLower()] + ", ";
			}
			text2 = text2.Substring(0, text2.Length - 2);
			text2 += "\n";
			return string.Format(AssetBundleHandler.GetInfoFromJSON(UPGRADE_NAME), level, price, text2);
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "hunterScript";
		}
	}
	internal class lightningRodScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Lightning Rod";

		public static lightningRodScript instance;

		private static LGULogger logger;

		public static string ENABLED_SECTION = "Enable " + UPGRADE_NAME + " Upgrade";

		public static bool ENABLED_DEFAULT = true;

		public static string ENABLED_DESCRIPTION = "A device which redirects lightning bolts to the ship.";

		public static string PRICE_SECTION = UPGRADE_NAME + " Price";

		public static int PRICE_DEFAULT = 1000;

		public static string ACTIVE_SECTION = "Active on Purchase";

		public static bool ACTIVE_DEFAULT = true;

		public static string ACTIVE_DESCRIPTION = "If true: " + UPGRADE_NAME + " will be active on purchase.";

		private static string LOAD_COLOUR = "#FF0000";

		private static string LOAD_MESSAGE = "\n<color=" + LOAD_COLOUR + ">" + UPGRADE_NAME + " is active!</color>";

		private static string UNLOAD_COLOUR = LOAD_COLOUR;

		private static string UNLOAD_MESSAGE = "\n<color=" + UNLOAD_COLOUR + ">" + UPGRADE_NAME + " has been disabled</color>";

		public static string ACCESS_DENIED_MESSAGE = "You don't have access to this command yet. Purchase the '" + UPGRADE_NAME + "'.\n";

		public static string TOGGLE_ON_MESSAGE = UPGRADE_NAME + " has been enabled. Lightning bolts will now be redirected to the ship.\n";

		public static string TOGGLE_OFF_MESSAGE = UPGRADE_NAME + " has been disabled. Lightning bolts will no longer be redirected to the ship.\n";

		public static string DIST_SECTION = "Effective Distance of " + UPGRADE_NAME + ".";

		public static float DIST_DEFAULT = 175f;

		public static string DIST_DESCRIPTION = "The closer you are the more likely the rod will reroute lightning.";

		public bool CanTryInterceptLightning { get; internal set; }

		public bool LightningIntercepted { get; internal set; }

		private void Awake()
		{
			instance = this;
			logger = new LGULogger(UPGRADE_NAME);
		}

		private void Start()
		{
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			UpgradeBus.instance.UpgradeObjects.Add(UPGRADE_NAME, ((Component)this).gameObject);
		}

		public override void Increment()
		{
		}

		public override void load()
		{
			UpgradeBus.instance.lightningRod = true;
			UpgradeBus.instance.lightningRodActive = UpgradeBus.instance.cfg.LIGHTNING_ROD_ACTIVE;
			TextMeshProUGUI chatText = HUDManager.Instance.chatText;
			((TMP_Text)chatText).text = ((TMP_Text)chatText).text + LOAD_MESSAGE;
		}

		public override void Register()
		{
			if (!UpgradeBus.instance.UpgradeObjects.ContainsKey(UPGRADE_NAME))
			{
				UpgradeBus.instance.UpgradeObjects.Add(UPGRADE_NAME, ((Component)this).gameObject);
			}
		}

		public override void Unwind()
		{
			UpgradeBus.instance.lightningRod = false;
			UpgradeBus.instance.lightningRodActive = false;
			TextMeshProUGUI chatText = HUDManager.Instance.chatText;
			((TMP_Text)chatText).text = ((TMP_Text)chatText).text + UNLOAD_MESSAGE;
		}

		public static void TryInterceptLightning(ref StormyWeather __instance, ref GrabbableObject ___targetingMetalObject)
		{
			//IL_0037: 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)
			if (!instance.CanTryInterceptLightning)
			{
				return;
			}
			instance.CanTryInterceptLightning = false;
			Terminal terminal = UpgradeBus.instance.GetTerminal();
			float num = Vector3.Distance(((Component)___targetingMetalObject).transform.position, ((Component)terminal).transform.position);
			logger.LogDebug($"Distance from ship: {num}");
			logger.LogDebug($"Effective distance of the lightning rod: {UpgradeBus.instance.cfg.LIGHTNING_ROD_DIST}");
			if (!(num > UpgradeBus.instance.cfg.LIGHTNING_ROD_DIST))
			{
				num /= UpgradeBus.instance.cfg.LIGHTNING_ROD_DIST;
				float num2 = 1f - num;
				float value = Random.value;
				logger.LogDebug($"Number to beat: {num2}");
				logger.LogDebug($"Number: {value}");
				if (value < num2)
				{
					logger.LogDebug("Planning interception...");
					__instance.staticElectricityParticle.Stop();
					instance.LightningIntercepted = true;
					LGUStore.instance.CoordinateInterceptionClientRpc();
				}
			}
		}

		public static void RerouteLightningBolt(ref Vector3 strikePosition, ref StormyWeather __instance)
		{
			//IL_0023: 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)
			logger.LogDebug("Intercepted Lightning Strike...");
			Terminal terminal = UpgradeBus.instance.GetTerminal();
			strikePosition = ((Component)terminal).transform.position;
			instance.LightningIntercepted = false;
			((Component)__instance.staticElectricityParticle).gameObject.SetActive(true);
		}

		public static void ToggleLightningRod(ref TerminalNode __result)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			UpgradeBus.instance.lightningRodActive = !UpgradeBus.instance.lightningRodActive;
			TerminalNode val = new TerminalNode();
			val.displayText = (UpgradeBus.instance.lightningRodActive ? TOGGLE_ON_MESSAGE : TOGGLE_OFF_MESSAGE);
			val.clearPreviousText = true;
			__result = val;
		}

		public static void AccessDeniedMessage(ref TerminalNode __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			TerminalNode val = new TerminalNode();
			val.displayText = ACCESS_DENIED_MESSAGE;
			val.clearPreviousText = true;
			__result = val;
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "lightningRodScript";
		}
	}
	public class lockSmithScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Locksmith";

		private GameObject pin1;

		private GameObject pin2;

		private GameObject pin3;

		private GameObject pin4;

		private GameObject pin5;

		private List<GameObject> pins;

		private List<int> order = new List<int> { 0, 1, 2, 3, 4 };

		private int currentPin = 0;

		public DoorLock currentDoor = null;

		private bool canPick = false;

		public int timesStruck;

		private void Start()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
			Transform child = ((Component)this).transform.GetChild(0).GetChild(0).GetChild(0);
			pin1 = ((Component)child.GetChild(0)).gameObject;
			pin2 = ((Component)child.GetChild(1)).gameObject;
			pin3 = ((Component)child.GetChild(2)).gameObject;
			pin4 = ((Component)child.GetChild(3)).gameObject;
			pin5 = ((Component)child.GetChild(4)).gameObject;
			((UnityEvent)((Component)pin1.transform.GetChild(0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StrikePin(0);
			});
			((UnityEvent)((Component)pin2.transform.GetChild(0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StrikePin(1);
			});
			((UnityEvent)((Component)pin3.transform.GetChild(0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StrikePin(2);
			});
			((UnityEvent)((Component)pin4.transform.GetChild(0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StrikePin(3);
			});
			((UnityEvent)((Component)pin5.transform.GetChild(0)).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StrikePin(4);
			});
			pins = new List<GameObject> { pin1, pin2, pin3, pin4, pin5 };
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.lockSmith = true;
			UpgradeBus.instance.lockScript = this;
		}

		public override void Register()
		{
			base.Register();
		}

		private void Update()
		{
			if (((ButtonControl)Keyboard.current[(Key)60]).wasPressedThisFrame && ((Component)((Component)this).transform.GetChild(0)).gameObject.activeInHierarchy)
			{
				((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(false);
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
			}
		}

		public void BeginLockPick()
		{
			//IL_006c: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(true);
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)0;
			canPick = false;
			currentPin = 0;
			for (int i = 0; i < pins.Count; i++)
			{
				float num = Random.Range(40f, 90f);
				pins[i].transform.localPosition = new Vector3(pins[i].transform.localPosition.x, num, pins[i].transform.localPosition.z);
			}
			RandomizeListOrder(order);
			((MonoBehaviour)this).StartCoroutine(CommunicateOrder(order));
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.lockSmith = false;
		}

		public void StrikePin(int i)
		{
			//IL_00a7: 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: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			if (!canPick)
			{
				return;
			}
			timesStruck++;
			if (i != order[currentPin])
			{
				BeginLockPick();
				RoundManager.Instance.PlayAudibleNoise(((Component)currentDoor).transform.position, 30f, 0.65f, timesStruck, false, 0);
				return;
			}
			currentPin++;
			pins[i].transform.localPosition = new Vector3(pins[i].transform.localPosition.x, 35f, pins[i].transform.localPosition.z);
			if (currentPin == 5)
			{
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
				((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(false);
				currentDoor.UnlockDoorSyncWithServer();
			}
			RoundManager.Instance.PlayAudibleNoise(((Component)currentDoor).transform.position, 10f, 0.65f, timesStruck, false, 0);
		}

		private void RandomizeListOrder<T>(List<T> list)
		{
			int num = list.Count;
			Random random = new Random();
			while (num > 1)
			{
				num--;
				int index = random.Next(num + 1);
				T value = list[index];
				list[index] = list[num];
				list[num] = value;
			}
		}

		private IEnumerator CommunicateOrder(List<int> lst)
		{
			yield return (object)new WaitForSeconds(0.75f);
			for (int i = 0; i < lst.Count; i++)
			{
				((Graphic)pins[lst[i]].GetComponent<Image>()).color = Color.green;
				yield return (object)new WaitForSeconds(0.25f);
				((Graphic)pins[lst[i]].GetComponent<Image>()).color = Color.white;
			}
			canPick = true;
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "lockSmithScript";
		}
	}
	internal class MedkitScript : GrabbableObject
	{
		public AudioClip error;

		public AudioClip use;

		private AudioSource audio;

		private int uses = 0;

		public override void Start()
		{
			audio = ((Component)this).GetComponent<AudioSource>();
			((GrabbableObject)this).Start();
		}

		public override void DiscardItem()
		{
			base.playerHeldBy.activatingItem = false;
			((GrabbableObject)this).DiscardItem();
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (base.itemUsedUp)
			{
				HUDManager.Instance.DisplayTip("NO MORE USES!", "This medkit doesn't have anymore supplies!", true, false, "LC_Tip1");
			}
			else
			{
				if (!Mouse.current.leftButton.isPressed)
				{
					return;
				}
				int num = (UpgradeBus.instance.playerHPs.ContainsKey(base.playerHeldBy.playerSteamId) ? UpgradeBus.instance.playerHPs[base.playerHeldBy.playerSteamId] : 100);
				if (base.playerHeldBy.health >= num)
				{
					audio.PlayOneShot(error);
					Debug.Log((object)"LGU: Can't use medkit - full health");
					return;
				}
				audio.PlayOneShot(use);
				uses++;
				int num2 = UpgradeBus.instance.cfg.MEDKIT_HEAL_VALUE;
				int num3 = base.playerHeldBy.health + num2;
				if (num3 > num)
				{
					num2 -= num3 - num;
				}
				base.playerHeldBy.DamagePlayer(-num2, false, true, (CauseOfDeath)0, 0, false, Vector3.zero);
				if (uses >= UpgradeBus.instance.cfg.MEDKIT_USES)
				{
					base.itemUsedUp = true;
					HUDManager.Instance.DisplayTip("NO MORE USES!", "This medkit doesn't have anymore supplies!", true, false, "LC_Tip1");
				}
				if (base.playerHeldBy.health >= 20)
				{
					base.playerHeldBy.MakeCriticallyInjured(false);
				}
			}
		}

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

		protected internal override string __getTypeName()
		{
			return "MedkitScript";
		}
	}
	internal class NightVisionItemScript : GrabbableObject
	{
		public override void DiscardItem()
		{
			base.playerHeldBy.activatingItem = false;
			((GrabbableObject)this).DiscardItem();
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (!Mouse.current.leftButton.isPressed)
			{
				return;
			}
			if (UpgradeBus.instance.nightVision)
			{
				TextMeshProUGUI chatText = HUDManager.Instance.chatText;
				((TMP_Text)chatText).text = ((TMP_Text)chatText).text + "<color=#FF0000>Night vision is already active!</color>";
				return;
			}
			if (!UpgradeBus.instance.IndividualUpgrades[nightVisionScript.UPGRADE_NAME])
			{
				LGUStore.instance.EnableNightVisionServerRpc();
			}
			else
			{
				UpgradeBus.instance.UpgradeObjects[nightVisionScript.UPGRADE_NAME].GetComponent<nightVisionScript>().EnableOnClient();
			}
			base.playerHeldBy.DespawnHeldObject();
		}

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

		protected internal override string __getTypeName()
		{
			return "NightVisionItemScript";
		}
	}
	internal class nightVisionScript : BaseUpgrade
	{
		private float nightBattery;

		private Transform batteryBar;

		private PlayerControllerB client;

		private bool batteryExhaustion;

		private Key toggleKey;

		public static string UPGRADE_NAME = "NV Headset Batteries";

		public static string PRICES_DEFAULT = "300,400,500";

		private static LGULogger logger = new LGULogger(UPGRADE_NAME);

		private void Start()
		{
			//IL_008d: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
			batteryBar = ((Component)((Component)this).transform.GetChild(0).GetChild(0)).transform;
			((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(false);
			if (Enum.TryParse<Key>(UpgradeBus.instance.cfg.TOGGLE_NIGHT_VISION_KEY, out Key result))
			{
				toggleKey = result;
				return;
			}
			logger.LogWarning("Error parsing the key for toggle night vision, defaulted to LeftAlt");
			toggleKey = (Key)53;
		}

		public override void Register()
		{
			base.Register();
		}

		private void LateUpdate()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)client == (Object)null)
			{
				return;
			}
			if (((ButtonControl)Keyboard.current[toggleKey]).wasPressedThisFrame && !batteryExhaustion)
			{
				Toggle();
			}
			float num = UpgradeBus.instance.cfg.NIGHT_BATTERY_MAX + (float)UpgradeBus.instance.nightVisionLevel * UpgradeBus.instance.cfg.NIGHT_VIS_BATTERY_INCREMENT;
			if (UpgradeBus.instance.nightVisionActive)
			{
				nightBattery -= Time.deltaTime * (UpgradeBus.instance.cfg.NIGHT_VIS_DRAIN_SPEED - (float)UpgradeBus.instance.nightVisionLevel * UpgradeBus.instance.cfg.NIGHT_VIS_DRAIN_INCREMENT);
				nightBattery = Mathf.Clamp(nightBattery, 0f, num);
				((Component)batteryBar.parent).gameObject.SetActive(true);
				if (nightBattery <= 0f)
				{
					TurnOff(exhaust: true);
				}
			}
			else if (!batteryExhaustion)
			{
				nightBattery += Time.deltaTime * (UpgradeBus.instance.cfg.NIGHT_VIS_REGEN_SPEED + (float)UpgradeBus.instance.nightVisionLevel * UpgradeBus.instance.cfg.NIGHT_VIS_REGEN_INCREMENT);
				nightBattery = Mathf.Clamp(nightBattery, 0f, num);
				if (nightBattery >= num)
				{
					((Component)batteryBar.parent).gameObject.SetActive(false);
				}
				else
				{
					((Component)batteryBar.parent).gameObject.SetActive(true);
				}
			}
			if (client.isInsideFactory || UpgradeBus.instance.nightVisionActive)
			{
				((Behaviour)client.nightVision).enabled = true;
			}
			else
			{
				((Behaviour)client.nightVision).enabled = false;
			}
			float num2 = nightBattery / num;
			batteryBar.localScale = new Vector3(num2, 1f, 1f);
		}

		private void Toggle()
		{
			UpgradeBus.instance.nightVisionActive = !UpgradeBus.instance.nightVisionActive;
			if (UpgradeBus.instance.nightVisionActive)
			{
				TurnOn();
			}
			else
			{
				TurnOff();
			}
		}

		private void TurnOff(bool exhaust = false)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			UpgradeBus.instance.nightVisionActive = false;
			client.nightVision.color = UpgradeBus.instance.nightVisColor;
			client.nightVision.range = UpgradeBus.instance.nightVisRange;
			client.nightVision.intensity = UpgradeBus.instance.nightVisIntensity;
			if (exhaust)
			{
				batteryExhaustion = true;
				((MonoBehaviour)this).StartCoroutine(BatteryRecovery());
			}
		}

		private void TurnOn()
		{
			//IL_0011: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			UpgradeBus.instance.nightVisColor = client.nightVision.color;
			UpgradeBus.instance.nightVisRange = client.nightVision.range;
			UpgradeBus.instance.nightVisIntensity = client.nightVision.intensity;
			client.nightVision.color = UpgradeBus.instance.cfg.NIGHT_VIS_COLOR;
			client.nightVision.range = UpgradeBus.instance.cfg.NIGHT_VIS_RANGE + (float)UpgradeBus.instance.nightVisionLevel * UpgradeBus.instance.cfg.NIGHT_VIS_RANGE_INCREMENT;
			client.nightVision.intensity = UpgradeBus.instance.cfg.NIGHT_VIS_INTENSITY + (float)UpgradeBus.instance.nightVisionLevel * UpgradeBus.instance.cfg.NIGHT_VIS_INTENSITY_INCREMENT;
			nightBattery -= UpgradeBus.instance.cfg.NIGHT_VIS_STARTUP;
		}

		private IEnumerator BatteryRecovery()
		{
			yield return (object)new WaitForSeconds(UpgradeBus.instance.cfg.NIGHT_VIS_EXHAUST);
			batteryExhaustion = false;
		}

		public override void Increment()
		{
			UpgradeBus.instance.nightVisionLevel++;
			LGUStore.instance.UpdateLGUSaveServerRpc(GameNetworkManager.Instance.localPlayerController.playerSteamId, JsonConvert.SerializeObject((object)new SaveInfo()));
		}

		public override void load()
		{
			EnableOnClient(save: false);
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.nightVision = false;
			UpgradeBus.instance.nightVisionLevel = 0;
			DisableOnClient();
		}

		public void EnableOnClient(bool save = true)
		{
			if ((Object)(object)client == (Object)null)
			{
				client = GameNetworkManager.Instance.localPlayerController;
			}
			((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(true);
			UpgradeBus.instance.nightVision = true;
			if (save)
			{
				LGUStore.instance.UpdateLGUSaveServerRpc(client.playerSteamId, JsonConvert.SerializeObject((object)new SaveInfo()));
			}
			TextMeshProUGUI chatText = HUDManager.Instance.chatText;
			((TMP_Text)chatText).text = ((TMP_Text)chatText).text + "\n<color=#FF0000>Press " + UpgradeBus.instance.cfg.TOGGLE_NIGHT_VISION_KEY + " to toggle Night Vision!!!</color>";
		}

		public void DisableOnClient()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			UpgradeBus.instance.nightVisionActive = false;
			client.nightVision.color = UpgradeBus.instance.nightVisColor;
			client.nightVision.range = UpgradeBus.instance.nightVisRange;
			client.nightVision.intensity = UpgradeBus.instance.nightVisIntensity;
			((Component)((Component)this).transform.GetChild(0)).gameObject.SetActive(false);
			UpgradeBus.instance.nightVision = false;
			LGUStore.instance.UpdateLGUSaveServerRpc(client.playerSteamId, JsonConvert.SerializeObject((object)new SaveInfo()));
			client = null;
		}

		public static string GetNightVisionInfo(int level, int price)
		{
			if (level == 1)
			{
				float num = (UpgradeBus.instance.cfg.NIGHT_BATTERY_MAX - UpgradeBus.instance.cfg.NIGHT_BATTERY_MAX * UpgradeBus.instance.cfg.NIGHT_VIS_STARTUP) / UpgradeBus.instance.cfg.NIGHT_VIS_DRAIN_SPEED;
				float num2 = UpgradeBus.instance.cfg.NIGHT_BATTERY_MAX / UpgradeBus.instance.cfg.NIGHT_VIS_REGEN_SPEED;
				return string.Format(AssetBundleHandler.GetInfoFromJSON(UPGRADE_NAME), level, price, num, num2);
			}
			float num3 = Mathf.Clamp(UpgradeBus.instance.cfg.NIGHT_VIS_REGEN_SPEED + UpgradeBus.instance.cfg.NIGHT_VIS_REGEN_INCREMENT * (float)(level - 1), 0f, 1000f);
			float num4 = Mathf.Clamp(UpgradeBus.instance.cfg.NIGHT_VIS_DRAIN_SPEED - UpgradeBus.instance.cfg.NIGHT_VIS_DRAIN_INCREMENT * (float)(level - 1), 0f, 1000f);
			float num5 = UpgradeBus.instance.cfg.NIGHT_BATTERY_MAX + UpgradeBus.instance.cfg.NIGHT_VIS_BATTERY_INCREMENT * (float)(level - 1);
			string text = "infinite";
			if (num4 != 0f)
			{
				text = ((num5 - num5 * UpgradeBus.instance.cfg.NIGHT_VIS_STARTUP) / num4).ToString("F2");
			}
			string text2 = "infinite";
			if (num3 != 0f)
			{
				text2 = (num5 / num3).ToString("F2");
			}
			return string.Format(AssetBundleHandler.GetInfoFromJSON(UPGRADE_NAME), level, price, text, text2);
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "nightVisionScript";
		}
	}
	public class pagerScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Fast Encryption";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.pager = true;
			UpgradeBus.instance.pageScript = this;
		}

		public override void Register()
		{
			base.Register();
		}

		[ServerRpc(RequireOwnership = false)]
		public void ReqBroadcastChatServerRpc(string msg)
		{
			//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(797180313u, val, (RpcDelivery)0);
				bool flag = msg != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(msg, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 797180313u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ReceiveChatClientRpc(msg);
			}
		}

		[ClientRpc]
		public void ReceiveChatClientRpc(string msg)
		{
			//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(58640511u, val, (RpcDelivery)0);
				bool flag = msg != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(msg, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 58640511u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				SignalTranslator val3 = Object.FindObjectOfType<SignalTranslator>();
				if ((Object)(object)val3 != (Object)null)
				{
					HUDManager.Instance.UIAudio.PlayOneShot(val3.startTransmissionSFX);
				}
				TextMeshProUGUI chatText = HUDManager.Instance.chatText;
				((TMP_Text)chatText).text = ((TMP_Text)chatText).text + "\n<color=#FF0000>Terminal</color><color=#0000FF>:</color> <color=#FF00FF>" + msg + "</color>";
				HUDManager.Instance.PingHUDElement(HUDManager.Instance.Chat, 4f, 1f, 0.2f);
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_pagerScript()
		{
			//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(797180313u, new RpcReceiveHandler(__rpc_handler_797180313));
			NetworkManager.__rpc_func_table.Add(58640511u, new RpcReceiveHandler(__rpc_handler_58640511));
		}

		private static void __rpc_handler_797180313(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 msg = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref msg, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((pagerScript)(object)target).ReqBroadcastChatServerRpc(msg);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_58640511(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 msg = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref msg, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((pagerScript)(object)target).ReceiveChatClientRpc(msg);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "pagerScript";
		}
	}
	internal class playerHealthScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Stimpack";

		private static int DEFAULT_HEALTH = 100;

		public static string ENABLED_SECTION = "Enable " + UPGRADE_NAME + " Upgrade";

		public static bool ENABLED_DEFAULT = true;

		public static string ENABLED_DESCRIPTION = "Increases player's health.";

		public static string PRICE_SECTION = UPGRADE_NAME + " Price";

		public static int PRICE_DEFAULT = 600;

		public static string PRICES_DEFAULT = "300, 450, 600";

		public static string ADDITIONAL_HEALTH_UNLOCK_SECTION = "Initial health boost";

		public static int ADDITIONAL_HEALTH_UNLOCK_DEFAULT = 20;

		public static string ADDITIONAL_HEALTH_UNLOCK_DESCRIPTION = "Amount of health gained when unlocking the upgrade";

		public static string ADDITIONAL_HEALTH_INCREMENT_SECTION = "Additional health boost";

		public static int ADDITIONAL_HEALTH_INCREMENT_DEFAULT = 20;

		public static string ADDITIONAL_HEALTH_INCREMENT_DESCRIPTION = "Every time " + UPGRADE_NAME + " is upgraded this value will be added to the value above.";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			UpgradeBus.instance.UpgradeObjects.Add(UPGRADE_NAME, ((Component)this).gameObject);
		}

		public override void Increment()
		{
			UpgradeBus.instance.playerHealthLevel++;
			LGUStore.instance.UpdatePlayerNewHealthsServerRpc(GameNetworkManager.Instance.localPlayerController.playerSteamId, DEFAULT_HEALTH + UpgradeBus.instance.cfg.PLAYER_HEALTH_ADDITIONAL_HEALTH_UNLOCK + UpgradeBus.instance.playerHealthLevel * UpgradeBus.instance.cfg.PLAYER_HEALTH_ADDITIONAL_HEALTH_INCREMENT);
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.playerHealth = true;
			LGUStore.instance.UpdatePlayerNewHealthsServerRpc(GameNetworkManager.Instance.localPlayerController.playerSteamId, DEFAULT_HEALTH + UpgradeBus.instance.cfg.PLAYER_HEALTH_ADDITIONAL_HEALTH_UNLOCK + UpgradeBus.instance.playerHealthLevel * UpgradeBus.instance.cfg.PLAYER_HEALTH_ADDITIONAL_HEALTH_INCREMENT);
		}

		public override void Register()
		{
			base.Register();
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.playerHealthLevel = 0;
			UpgradeBus.instance.playerHealth = false;
			LGUStore.instance.UpdatePlayerNewHealthsServerRpc(GameNetworkManager.Instance.localPlayerController.playerSteamId, DEFAULT_HEALTH);
		}

		public static void CheckAdditionalHealth(StartOfRound __instance)
		{
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			PlayerControllerB[] array = allPlayerScripts;
			foreach (PlayerControllerB player in array)
			{
				UpdateMaxHealth(player);
			}
		}

		public static int CheckForAdditionalHealth()
		{
			if (UpgradeBus.instance.playerHPs.ContainsKey(GameNetworkManager.Instance.localPlayerController.playerSteamId))
			{
				return UpgradeBus.instance.playerHPs[GameNetworkManager.Instance.localPlayerController.playerSteamId];
			}
			return DEFAULT_HEALTH;
		}

		public static void UpdateMaxHealth(PlayerControllerB player)
		{
			if (UpgradeBus.instance.playerHPs.ContainsKey(player.playerSteamId))
			{
				player.health = UpgradeBus.instance.playerHPs[player.playerSteamId];
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "playerHealthScript";
		}
	}
	internal class proteinPowderScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Protein Powder";

		private static int CRIT_DAMAGE_VALUE = 100;

		public static string ENABLED_SECTION = "Enable " + UPGRADE_NAME + " Upgrade";

		public static bool ENABLED_DEFAULT = true;

		public static string ENABLED_DESCRIPTION = "Do more damage with shovels";

		public static string PRICE_SECTION = "Price of " + UPGRADE_NAME + " Upgrade";

		public static int PRICE_DEFAULT = 1000;

		public static string UNLOCK_FORCE_SECTION = "Initial additional hit force";

		public static int UNLOCK_FORCE_DEFAULT = 1;

		public static string UNLOCK_FORCE_DESCRIPTION = "The value added to hit force on initial unlock.";

		public static string INCREMENT_FORCE_SECTION = "Additional hit force per level";

		public static int INCREMENT_FORCE_DEFAULT = 1;

		public static string INCREMENT_FORCE_DESCRIPTION = "Every time " + UPGRADE_NAME + " is upgraded this value will be added to the value above.";

		public static string PRICES_DEFAULT = "700";

		public static string CRIT_CHANCE_SECTION = "Chance of dealing a crit which will instakill the enemy.";

		public static float CRIT_CHANCE_DEFAULT = 0.01f;

		public static string CRIT_CHANCE_DESCRIPTION = "This value is only valid when maxed out " + UPGRADE_NAME + ". Any previous levels will not apply crit.";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			UpgradeBus.instance.proteinLevel++;
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.proteinPowder = true;
		}

		public override void Register()
		{
			base.Register();
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.proteinLevel = 0;
			UpgradeBus.instance.proteinPowder = false;
		}

		public static int GetShovelHitForce(int force)
		{
			return (!UpgradeBus.instance.proteinPowder) ? force : (TryToCritEnemy() ? CRIT_DAMAGE_VALUE : (UpgradeBus.instance.cfg.PROTEIN_INCREMENT * UpgradeBus.instance.proteinLevel + UpgradeBus.instance.cfg.PROTEIN_UNLOCK_FORCE + force));
		}

		private static bool TryToCritEnemy()
		{
			int num = UpgradeBus.instance.cfg.PROTEIN_UPGRADE_PRICES.Split(',').Length;
			int proteinLevel = UpgradeBus.instance.proteinLevel;
			if (proteinLevel != num)
			{
				return false;
			}
			return Random.value < UpgradeBus.instance.cfg.PROTEIN_CRIT_CHANCE;
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "proteinPowderScript";
		}
	}
	internal class runningShoeScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Running Shoes";

		private static LGULogger logger;

		public static string PRICES_DEFAULT = "500,750,1000";

		private int currentLevel = 0;

		private static bool active = false;

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			logger = new LGULogger(UPGRADE_NAME);
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			localPlayer.movementSpeed += UpgradeBus.instance.cfg.MOVEMENT_INCREMENT;
			logger.LogDebug($"Adding {UpgradeBus.instance.cfg.MOVEMENT_INCREMENT} to the player's movement speed...");
			UpgradeBus.instance.runningLevel++;
			currentLevel++;
		}

		public override void Unwind()
		{
			base.Unwind();
			PlayerControllerB player = UpgradeBus.instance.GetLocalPlayer();
			if (UpgradeBus.instance.runningShoes)
			{
				ResetRunningShoesBuff(ref player);
			}
			UpgradeBus.instance.runningShoes = false;
			UpgradeBus.instance.runningLevel = 0;
			active = false;
			currentLevel = 0;
		}

		public override void Register()
		{
			base.Register();
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.runningShoes = true;
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			if (!active)
			{
				logger.LogDebug($"Adding {UpgradeBus.instance.cfg.MOVEMENT_SPEED_UNLOCK} to the player's movement speed...");
				localPlayer.movementSpeed += UpgradeBus.instance.cfg.MOVEMENT_SPEED_UNLOCK;
			}
			float num = 0f;
			for (int i = 1; i < UpgradeBus.instance.runningLevel + 1; i++)
			{
				if (i > currentLevel)
				{
					logger.LogDebug($"Adding {UpgradeBus.instance.cfg.MOVEMENT_INCREMENT} to the player's movement speed...");
					num += UpgradeBus.instance.cfg.MOVEMENT_INCREMENT;
				}
			}
			logger.LogDebug($"Adding player's movement speed ({localPlayer.movementSpeed}) with {num}");
			localPlayer.movementSpeed += num;
			active = true;
			currentLevel = UpgradeBus.instance.runningLevel;
		}

		public static void ResetRunningShoesBuff(ref PlayerControllerB player)
		{
			float num = UpgradeBus.instance.cfg.MOVEMENT_SPEED_UNLOCK;
			for (int i = 0; i < UpgradeBus.instance.runningLevel; i++)
			{
				num += UpgradeBus.instance.cfg.MOVEMENT_INCREMENT;
			}
			logger.LogDebug($"Removing {player.playerUsername}'s movement speed boost ({player.movementSpeed}) with a boost of {num}");
			PlayerControllerB obj = player;
			obj.movementSpeed -= num;
			logger.LogDebug("Upgrade reset on " + player.playerUsername);
			active = false;
		}

		public static float ApplyPossibleReducedNoiseRange(float defaultValue)
		{
			if (!UpgradeBus.instance.runningShoes || UpgradeBus.instance.runningLevel != UpgradeBus.instance.cfg.RUNNING_SHOES_UPGRADE_PRICES.Split(',').Length)
			{
				return defaultValue;
			}
			return Mathf.Clamp(defaultValue - UpgradeBus.instance.cfg.NOISE_REDUCTION, 0f, defaultValue);
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "runningShoeScript";
		}
	}
	internal class SampleItem : PhysicsProp
	{
		public override void EquipItem()
		{
			ParticleSystem componentInChildren = ((Component)this).GetComponentInChildren<ParticleSystem>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.Play();
			}
			((PhysicsProp)this).EquipItem();
		}

		public override void DiscardItem()
		{
			ParticleSystem componentInChildren = ((Component)this).GetComponentInChildren<ParticleSystem>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.Play();
			}
			((GrabbableObject)this).DiscardItem();
		}

		public override void PocketItem()
		{
			ParticleSystem componentInChildren = ((Component)this).GetComponentInChildren<ParticleSystem>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.Stop();
				componentInChildren.Clear();
			}
			((GrabbableObject)this).PocketItem();
		}

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

		protected internal override string __getTypeName()
		{
			return "SampleItem";
		}
	}
	internal class strongerScannerScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Better Scanner";

		private static LGULogger logger;

		private void Awake()
		{
			logger = new LGULogger(UPGRADE_NAME);
		}

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			UpgradeBus.instance.scanLevel++;
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.scannerUpgrade = true;
		}

		public override void Unwind()
		{
			base.Unwind();
			UpgradeBus.instance.scannerUpgrade = false;
			UpgradeBus.instance.scanLevel = 0;
		}

		public override void Register()
		{
			base.Register();
		}

		public static void AddScannerNodeToValve(ref SteamValveHazard steamValveHazard)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (UpgradeBus.instance.scannerUpgrade)
			{
				logger.LogDebug("Inserting a Scan Node on a broken steam valve...");
				GameObject val = Object.Instantiate<GameObject>(GameObject.Find("ScanNode"), ((Component)steamValveHazard).transform.position, Quaternion.Euler(Vector3.zero), ((Component)steamValveHazard).transform);
				ScanNodeProperties component = val.GetComponent<ScanNodeProperties>();
				component.headerText = "Bursted Steam Valve";
				component.subText = "Fix it to get rid of the steam";
				component.nodeType = 0;
				component.creatureScanID = -1;
			}
		}

		public static void RemoveScannerNodeFromValve(ref SteamValveHazard steamValveHazard)
		{
			logger.LogDebug("Removing the Scan Node from a fixed steam valve...");
			Object.Destroy((Object)(object)((Component)steamValveHazard).gameObject.GetComponentInChildren<ScanNodeProperties>());
		}

		public static string GetBetterScannerInfo(int level, int price)
		{
			switch (level)
			{
			case 1:
				return string.Format(AssetBundleHandler.GetInfoFromJSON("Better Scanner1"), level, price, UpgradeBus.instance.cfg.NODE_DISTANCE_INCREASE, UpgradeBus.instance.cfg.SHIP_AND_ENTRANCE_DISTANCE_INCREASE);
			case 2:
				return string.Format(AssetBundleHandler.GetInfoFromJSON("Better Scanner2"), level, price);
			case 3:
			{
				string text = string.Format(AssetBundleHandler.GetInfoFromJSON("Better Scanner3"), level, price, UpgradeBus.instance.cfg.BETTER_SCANNER_ENEMIES ? " and enemies" : "");
				return text + "hives and scrap command display the location of the most valuable hives and scrap on the map.\n";
			}
			default:
				return "";
			}
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "strongerScannerScript";
		}
	}
	internal class strongLegsScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Strong Legs";

		private static LGULogger logger;

		public static string PRICES_DEFAULT = "150,190,250";

		private int currentLevel = 0;

		private static bool active = false;

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			logger = new LGULogger(UPGRADE_NAME);
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		public override void Increment()
		{
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			localPlayer.jumpForce += UpgradeBus.instance.cfg.JUMP_FORCE_INCREMENT;
			UpgradeBus.instance.legLevel++;
			currentLevel++;
		}

		public override void Unwind()
		{
			base.Unwind();
			PlayerControllerB player = UpgradeBus.instance.GetLocalPlayer();
			logger.LogDebug($"Adding {UpgradeBus.instance.cfg.JUMP_FORCE_INCREMENT} to the player's jump force...");
			if (UpgradeBus.instance.strongLegs)
			{
				ResetStrongLegsBuff(ref player);
			}
			UpgradeBus.instance.strongLegs = false;
			UpgradeBus.instance.legLevel = 0;
			active = false;
			currentLevel = 0;
		}

		public override void Register()
		{
			base.Register();
		}

		public override void load()
		{
			base.load();
			UpgradeBus.instance.strongLegs = true;
			PlayerControllerB localPlayer = UpgradeBus.instance.GetLocalPlayer();
			if (!active)
			{
				logger.LogDebug($"Adding {UpgradeBus.instance.cfg.JUMP_FORCE_UNLOCK} to the player's jump force...");
				localPlayer.jumpForce += UpgradeBus.instance.cfg.JUMP_FORCE_UNLOCK;
			}
			float num = 0f;
			for (int i = 1; i < UpgradeBus.instance.legLevel + 1; i++)
			{
				if (i > currentLevel)
				{
					logger.LogDebug($"Adding {UpgradeBus.instance.cfg.JUMP_FORCE_INCREMENT} to the player's jump force...");
					num += UpgradeBus.instance.cfg.JUMP_FORCE_INCREMENT;
				}
			}
			localPlayer.jumpForce += num;
			active = true;
			currentLevel = UpgradeBus.instance.legLevel;
		}

		public static void ResetStrongLegsBuff(ref PlayerControllerB player)
		{
			float num = UpgradeBus.instance.cfg.JUMP_FORCE_UNLOCK;
			for (int i = 0; i < UpgradeBus.instance.legLevel; i++)
			{
				num += UpgradeBus.instance.cfg.JUMP_FORCE_INCREMENT;
			}
			logger.LogDebug($"Removing {player.playerUsername}'s jump force boost ({player.jumpForce}) with a boost of {num}");
			PlayerControllerB obj = player;
			obj.jumpForce -= num;
			logger.LogDebug("Upgrade reset on " + player.playerUsername);
			active = false;
		}

		public static int ReduceFallDamage(int defaultValue)
		{
			if (!UpgradeBus.instance.strongLegs || UpgradeBus.instance.legLevel != UpgradeBus.instance.cfg.STRONG_LEGS_UPGRADE_PRICES.Split(',').Length)
			{
				return defaultValue;
			}
			return (int)((float)defaultValue * (1f - UpgradeBus.instance.cfg.STRONG_LEGS_REDUCE_FALL_DAMAGE_MULTIPLIER));
		}

		protected override void __initializeVariables()
		{
			base.__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "strongLegsScript";
		}
	}
	public class terminalFlashScript : BaseUpgrade
	{
		public static string UPGRADE_NAME = "Discombobulator";

		public static string PRICES_DEFAULT = "330,460,620";

		private void Start()
		{
			upgradeName = UPGRADE_NAME;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Register();
		}

		private void Update()
		{
			if (UpgradeBus.instance.flashCooldown > 0f)
			{
				UpgradeBus.instance.flashCooldown -= Time.deltaTime;
			}
		}

		public override void load()
		{
			UpgradeBus.instance.terminalFlash = true;
			UpgradeBus.instance.flashS