Decompiled source of BoonPack v1.0.1

AlwaysHearWalkie.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 BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LCAlwaysHearWalkieMod.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AlwaysHearWalkie")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.4.4.0")]
[assembly: AssemblyInformationalVersion("1.4.4+29502bb52bcbc33187ec0645d5c274b3ffd1bc79")]
[assembly: AssemblyProduct("Always Hear Active Walkies")]
[assembly: AssemblyTitle("AlwaysHearWalkie")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.4.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx5.PluginTemplate
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AlwaysHearWalkie";

		public const string PLUGIN_NAME = "Always Hear Active Walkies";

		public const string PLUGIN_VERSION = "1.4.4";
	}
}
namespace LCAlwaysHearWalkieMod
{
	public static class PluginInfo
	{
		public const string modGUID = "suskitech.LCAlwaysHearActiveWalkie";

		public const string modName = "LC Always Hear Active Walkies";

		public const string modVersion = "1.4.4";
	}
	[BepInPlugin("suskitech.LCAlwaysHearActiveWalkie", "LC Always Hear Active Walkies", "1.4.4")]
	public class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<float> configAudibleDistance;

		public static float AudibleDistance;

		private ConfigEntry<float> configWalkieRecordingRange;

		public static float WalkieRecordingRange;

		private ConfigEntry<float> configPlayerToPlayerSpatialHearingRange;

		public static float PlayerToPlayerSpatialHearingRange;

		public static ManualLogSource Log;

		private static Plugin Instance;

		public void Awake()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configAudibleDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "AudibleDistance", 12f, "");
			AudibleDistance = configAudibleDistance.Value;
			configWalkieRecordingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "WalkieRecordingRange", 20f, "");
			WalkieRecordingRange = configWalkieRecordingRange.Value;
			configPlayerToPlayerSpatialHearingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "PlayerToPlayerSpatialHearingRange", 20f, "");
			PlayerToPlayerSpatialHearingRange = configPlayerToPlayerSpatialHearingRange.Value;
			Log = Logger.CreateLogSource("suskitech.LCAlwaysHearActiveWalkie");
			Harmony val = new Harmony("suskitech.LCAlwaysHearActiveWalkie");
			val.PatchAll(typeof(Plugin));
			val.PatchAll(typeof(PlayerControllerBPatch));
			val.PatchAll(typeof(WalkieTalkiePatch));
			Log.LogInfo((object)"\\ /");
			Log.LogInfo((object)"/|\\");
			Log.LogInfo((object)" |----|");
			Log.LogInfo((object)" |[__]| Always Hear Active Walkies");
			Log.LogInfo((object)" |.  .| Version 1.4.4 Loaded");
			Log.LogInfo((object)" |____|");
			Log.LogInfo((object)"");
			Log.LogInfo((object)("AudibleDistance: " + AudibleDistance));
			Log.LogInfo((object)("WalkieRecordingRange: " + WalkieRecordingRange));
			Log.LogInfo((object)("PlayerToPlayerSpatialHearingRange: " + PlayerToPlayerSpatialHearingRange));
		}
	}
}
namespace LCAlwaysHearWalkieMod.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		private static readonly float throttleInterval = 0.35f;

		private static float throttle = 0f;

		private static readonly float AverageDistanceToHeldWalkie = 2f;

		private static readonly float AudibleDistance = Plugin.AudibleDistance;

		private static readonly float WalkieRecordingRange = Plugin.WalkieRecordingRange;

		private static readonly float PlayerToPlayerSpatialHearingRange = Plugin.PlayerToPlayerSpatialHearingRange;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void alwaysHearWalkieTalkiesPatch(ref bool ___holdingWalkieTalkie, ref PlayerControllerB __instance)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			throttle += Time.deltaTime;
			if (throttle < throttleInterval)
			{
				return;
			}
			throttle = 0f;
			if ((Object)(object)__instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				List<WalkieTalkie> list = new List<WalkieTalkie>();
				List<WalkieTalkie> list2 = new List<WalkieTalkie>();
				for (int i = 0; i < WalkieTalkie.allWalkieTalkies.Count; i++)
				{
					float num = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[i]).transform.position, ((Component)__instance).transform.position);
					if (num <= AudibleDistance)
					{
						if (((GrabbableObject)WalkieTalkie.allWalkieTalkies[i]).isBeingUsed)
						{
							list.Add(WalkieTalkie.allWalkieTalkies[i]);
						}
					}
					else
					{
						list2.Add(WalkieTalkie.allWalkieTalkies[i]);
					}
				}
				bool flag = list.Count > 0;
				if (flag != __instance.holdingWalkieTalkie)
				{
					___holdingWalkieTalkie = flag;
					for (int j = 0; j < list2.Count; j++)
					{
						if (j < list.Count)
						{
							list2[j].thisAudio.Stop();
						}
					}
				}
				if (!flag)
				{
					return;
				}
			}
			PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript);
			for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
			{
				PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[k];
				if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController || val2.isPlayerDead || !val2.holdingWalkieTalkie)
				{
					continue;
				}
				float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position);
				float num3 = float.MaxValue;
				float num4 = float.MaxValue;
				for (int l = 0; l < WalkieTalkie.allWalkieTalkies.Count; l++)
				{
					if (!((GrabbableObject)WalkieTalkie.allWalkieTalkies[l]).isBeingUsed)
					{
						continue;
					}
					float num5 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l].target).transform.position, ((Component)val).transform.position);
					if (num5 < num4)
					{
						num4 = num5;
					}
					if (!WalkieTalkie.allWalkieTalkies[l].speakingIntoWalkieTalkie)
					{
						float num6 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l]).transform.position, ((Component)val2).transform.position);
						if (num6 < num3)
						{
							num3 = num6;
						}
					}
				}
				float num7 = Mathf.Min(1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num3), 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num4));
				float num8 = 1f - Mathf.InverseLerp(0f, PlayerToPlayerSpatialHearingRange, num2);
				val2.voicePlayerState.Volume = Mathf.Max(num7, num8);
				if (val2.speakingToWalkieTalkie && num7 > num8)
				{
					makePlayerSoundWalkieTalkie(val2);
				}
				else
				{
					makePlayerSoundSpatial(val2);
				}
			}
			static void makePlayerSoundSpatial(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
				OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
				((Behaviour)component2).enabled = false;
				((Behaviour)component).enabled = true;
				component3.overridingLowPass = playerController.voiceMuffledByEnemy;
				currentVoiceChatAudioSource.spatialBlend = 1f;
				playerController.currentVoiceChatIngameSettings.set2D = false;
				currentVoiceChatAudioSource.bypassListenerEffects = false;
				currentVoiceChatAudioSource.bypassEffects = false;
				currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				component.lowpassResonanceQ = 1f;
			}
			static void makePlayerSoundWalkieTalkie(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource2 = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component4 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component5 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioHighPassFilter>();
				OccludeAudio component6 = ((Component)currentVoiceChatAudioSource2).GetComponent<OccludeAudio>();
				((Behaviour)component5).enabled = true;
				((Behaviour)component4).enabled = true;
				component6.overridingLowPass = true;
				currentVoiceChatAudioSource2.spatialBlend = 0f;
				playerController.currentVoiceChatIngameSettings.set2D = true;
				currentVoiceChatAudioSource2.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				currentVoiceChatAudioSource2.bypassListenerEffects = false;
				currentVoiceChatAudioSource2.bypassEffects = false;
				currentVoiceChatAudioSource2.panStereo = (GameNetworkManager.Instance.localPlayerController.isPlayerDead ? 0f : 0.4f);
				component6.lowPassOverride = 4000f;
				component4.lowpassResonanceQ = 3f;
			}
		}
	}
	[HarmonyPatch(typeof(WalkieTalkie))]
	internal class WalkieTalkiePatch
	{
		[HarmonyPatch("EnableWalkieTalkieListening")]
		[HarmonyPrefix]
		private static bool alwaysHearWalkieTalkiesEnableWalkieTalkieListeningPatch(bool enable)
		{
			if (!enable)
			{
				return false;
			}
			return true;
		}
	}
}

BepInEx/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;
	}
}

BepInEx/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

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

BepInEx/plugins/CustomSounds.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 CustomSounds.Networking;
using CustomSounds.Patches;
using HarmonyLib;
using LCSoundTool;
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("CustomSounds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomSounds")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9e086160-a7fd-4721-ba09-3e8534cb7011")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace CustomSounds
{
	[BepInPlugin("CustomSounds", "Custom Sounds", "2.3.2")]
	public class Plugin : BaseUnityPlugin
	{
		public struct SoundData
		{
			public string SoundName;

			public float? RandomPercentage;

			public string CustomName;

			public string FilePath;

			public string FileExtension;

			public string PackName;

			public string AudioSource;

			public string DirectoryPath;

			public string RelativeDirectoryPath;
		}

		public class FolderTree
		{
			public Dictionary<string, FolderTree> SubFolders { get; set; }

			public List<SoundData> Files { get; set; }

			public FolderTree()
			{
				SubFolders = new Dictionary<string, FolderTree>();
				Files = new List<SoundData>();
			}
		}

		public static class SoundDataProcessor
		{
			public static FolderTree BuildFolderTree(List<SoundData> soundDataList)
			{
				FolderTree folderTree = new FolderTree();
				foreach (SoundData soundData in soundDataList)
				{
					string relativeDirectoryPath = soundData.RelativeDirectoryPath;
					string[] array = relativeDirectoryPath.Split(Path.DirectorySeparatorChar, '\u0001');
					FolderTree folderTree2 = folderTree;
					string[] array2 = array;
					foreach (string key in array2)
					{
						if (!folderTree2.SubFolders.ContainsKey(key))
						{
							folderTree2.SubFolders[key] = new FolderTree();
						}
						folderTree2 = folderTree2.SubFolders[key];
					}
					folderTree2.Files.Add(soundData);
				}
				return folderTree;
			}

			public static string DisplayTree(bool isListing, FolderTree tree, int indent = 0, bool isRoot = true, int soundCount = 0)
			{
				StringBuilder stringBuilder = new StringBuilder();
				if (isRoot)
				{
					soundCount = CountSounds(tree);
					string text = (isListing ? "Listing all currently loaded custom sounds:" : "Customsounds reloaded.");
					stringBuilder.AppendLine(text + $" ({soundCount} sounds)");
				}
				foreach (KeyValuePair<string, FolderTree> subFolder in tree.SubFolders)
				{
					if (isRoot)
					{
						stringBuilder.Append("\n");
					}
					string text2 = subFolder.Key;
					if (text2.EndsWith("-AS"))
					{
						text2 = subFolder.Key.Substring(0, subFolder.Key.Length - 3) + " (AudioSource)";
					}
					stringBuilder.AppendLine(new string(' ', indent * 2) + ((indent > 0) ? "∟ " : "") + text2 + " :");
					stringBuilder.Append(DisplayTree(isListing, subFolder.Value, indent + 1, isRoot: false));
				}
				foreach (SoundData file in tree.Files)
				{
					string text3 = ((!file.RandomPercentage.HasValue) ? "" : $" (Random: {file.RandomPercentage * 100f}%)");
					string text4 = ((file.CustomName == "") ? "" : (" [" + file.CustomName + "]"));
					stringBuilder.AppendLine(new string(' ', indent * 2) + "- " + file.SoundName + text3 + text4 + " [" + file.FileExtension.ToUpper() + "]");
				}
				return stringBuilder.ToString();
			}

			private static int CountSounds(FolderTree tree)
			{
				int num = tree.Files.Count;
				foreach (KeyValuePair<string, FolderTree> subFolder in tree.SubFolders)
				{
					num += CountSounds(subFolder.Value);
				}
				return num;
			}
		}

		private const string PLUGIN_GUID = "CustomSounds";

		private const string PLUGIN_NAME = "Custom Sounds";

		private const string PLUGIN_VERSION = "2.3.2";

		public static Plugin Instance;

		internal ManualLogSource logger;

		private Harmony harmony;

		public HashSet<string> currentSounds = new HashSet<string>();

		public HashSet<string> oldSounds = new HashSet<string>();

		public HashSet<string> modifiedSounds = new HashSet<string>();

		public Dictionary<string, string> soundHashes = new Dictionary<string, string>();

		public Dictionary<string, string> soundPacks = new Dictionary<string, string>();

		public static bool hasAcceptedSync = false;

		public static List<SoundData> soundDataList = new List<SoundData>();

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (!((Object)(object)Instance == (Object)null))
			{
				return;
			}
			Instance = this;
			logger = Logger.CreateLogSource("CustomSounds");
			harmony = new Harmony("CustomSounds");
			harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch));
			modifiedSounds = new HashSet<string>();
			string customSoundsFolderPath = GetCustomSoundsFolderPath();
			if (!Directory.Exists(customSoundsFolderPath))
			{
				logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now.");
				string path = Path.Combine(customSoundsFolderPath, "YourOwnSoundPack");
				Directory.CreateDirectory(path);
				string contents = "If you're interested in creating your own sound pack, please refer to the 'For Sound Packs Creator' section on the CustomSounds Thunderstore page. If you simply wish to replace a few sounds on your own, you can drop the desired sounds into the 'YourOwnSoundPack' folder.";
				File.WriteAllText(Path.Combine(customSoundsFolderPath, "READ-ME-PLEASE.txt"), contents);
			}
			string path2 = Path.Combine(Paths.BepInExConfigPath);
			try
			{
				List<string> list = File.ReadAllLines(path2).ToList();
				int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject"));
				if (num != -1 && list[num].Contains("false"))
				{
					logger.LogInfo((object)"\"HideManagerGameObject\" value not correctly set. Fixing it now.");
					list[num] = "HideManagerGameObject = true";
					File.WriteAllLines(path2, list);
					harmony.PatchAll(typeof(MenuPatcher));
				}
				else if (num != -1)
				{
					logger.LogInfo((object)"\"HideManagerGameObject\" is correctly set to true.");
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error modifying config file: " + ex.Message));
			}
			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);
					}
				}
			}
			logger.LogInfo((object)"Plugin CustomSounds is loaded!");
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			if (!Initialized)
			{
				Initialized = true;
				ReloadSounds();
			}
		}

		private void OnApplicationQuit()
		{
		}

		public GameObject LoadNetworkPrefabFromEmbeddedResource()
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = "CustomSounds.Bundle.audionetworkhandler";
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			if (stream == null)
			{
				Debug.LogError((object)"Asset bundle not found in embedded resources.");
				return null;
			}
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			AssetBundle val = AssetBundle.LoadFromMemory(array);
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Failed to load AssetBundle from memory.");
				return null;
			}
			return val.LoadAsset<GameObject>("audionetworkhandler");
		}

		public string GetCustomSoundsFolderPath()
		{
			return Path.Combine(Paths.PluginPath, "CustomSounds");
		}

		public void RevertSounds()
		{
			if (currentSounds == null || currentSounds.Count == 0)
			{
				logger.LogInfo((object)"No sounds to revert.");
				return;
			}
			HashSet<string> hashSet = new HashSet<string>();
			foreach (string currentSound in currentSounds)
			{
				string text = currentSound;
				if (currentSound.Contains("-"))
				{
					text = currentSound.Substring(0, currentSound.IndexOf("-"));
				}
				if (!hashSet.Contains(text))
				{
					logger.LogInfo((object)(text + " restored."));
					SoundTool.RestoreAudioClip(text);
					hashSet.Add(text);
				}
			}
			logger.LogInfo((object)"Original game sounds restored.");
		}

		public void ReloadSounds()
		{
			oldSounds = new HashSet<string>(currentSounds);
			currentSounds.Clear();
			modifiedSounds.Clear();
			soundDataList.Clear();
			string directoryName = Path.GetDirectoryName(Paths.PluginPath);
			ProcessDirectory(directoryName);
		}

		private string GetRelativePathToCustomSounds(string filePath)
		{
			Debug.Log((object)("FilePath: " + filePath));
			string[] array = filePath.Split(new char[1] { Path.DirectorySeparatorChar });
			int num = Array.IndexOf(array, "CustomSounds");
			if (num == -1 || num == array.Length - 1)
			{
				return "";
			}
			string[] paths = array.Skip(num + 1).ToArray();
			return Path.Combine(paths);
		}

		private void ProcessDirectory(string directoryPath)
		{
			string[] directories = Directory.GetDirectories(directoryPath, "*", SearchOption.AllDirectories);
			foreach (string text in directories)
			{
				string fileName = Path.GetFileName(text);
				ProcessSoundFiles(text, fileName);
			}
		}

		private void ProcessSoundFiles(string directoryPath, string packName)
		{
			string[] array = new string[3] { "*.wav", "*.ogg", "*.mp3" };
			string[] array2 = array;
			foreach (string searchPattern in array2)
			{
				string[] files = Directory.GetFiles(directoryPath, searchPattern);
				foreach (string text in files)
				{
					if (text.Contains("CustomSounds"))
					{
						ProcessSingleFile(text, packName);
					}
				}
			}
		}

		private void ProcessSingleFile(string file, string packName)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
			(string soundName, float? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension);
			string item = tuple.soundName;
			float? item2 = tuple.percentage;
			string item3 = tuple.customName;
			string fileExtension = Path.GetExtension(file).TrimStart(new char[1] { '.' }).ToLower();
			string relativePathToCustomSounds = GetRelativePathToCustomSounds(file);
			string fileName = Path.GetFileName(Path.GetDirectoryName(file));
			string text = (fileName.EndsWith("-AS") ? fileName.Substring(0, fileName.Length - 3) : null);
			SoundData soundData = default(SoundData);
			soundData.SoundName = item;
			soundData.RandomPercentage = item2;
			soundData.CustomName = item3;
			soundData.FilePath = file;
			soundData.FileExtension = fileExtension;
			soundData.PackName = packName;
			soundData.AudioSource = text;
			soundData.DirectoryPath = Path.GetDirectoryName(file);
			soundData.RelativeDirectoryPath = Path.GetDirectoryName(relativePathToCustomSounds);
			SoundData item4 = soundData;
			soundDataList.Add(item4);
			string text2 = "Sound replaced: " + item;
			if (item4.RandomPercentage.HasValue)
			{
				text2 += $" (Percentage = {item4.RandomPercentage.Value * 100f}%)";
			}
			if (!string.IsNullOrEmpty(item4.CustomName))
			{
				text2 = text2 + " (Custom Name = " + item4.CustomName + ")";
			}
			text2 = text2 + " (File Extension = " + item4.FileExtension + ")";
			Debug.Log((object)text2);
			AudioClip audioClip = SoundTool.GetAudioClip(Path.GetDirectoryName(file), file);
			((Object)audioClip).name = fileNameWithoutExtension;
			currentSounds.Add(item4.SoundName);
			if (item4.RandomPercentage.HasValue)
			{
				if (item4.AudioSource != null)
				{
					SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.RandomPercentage.Value, item4.AudioSource);
				}
				else
				{
					SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.RandomPercentage.Value);
				}
			}
			else if (text != null)
			{
				SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.AudioSource);
			}
			else
			{
				SoundTool.ReplaceAudioClip(item4.SoundName, audioClip);
			}
		}

		private (string soundName, float? percentage, string customName) ParseSoundFileName(string fullSoundName)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullSoundName);
			string[] array = fileNameWithoutExtension.Split(new char[1] { '-' });
			string s = array[^1];
			if (int.TryParse(s, out var result))
			{
				string item = array[0];
				string item2 = string.Join(" ", array.Skip(1).Take(array.Length - 2));
				float value = (float)result / 100f;
				return (item, value, item2);
			}
			return (array[0], null, string.Join(" ", array.Skip(1)));
		}
	}
}
namespace CustomSounds.Patches
{
	[HarmonyPatch]
	public class NetworkObjectManager
	{
		private static GameObject networkPrefab;

		private static GameObject networkHandlerHost;

		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPrefix]
		public static void Init()
		{
			if (!((Object)(object)networkPrefab != (Object)null))
			{
				networkPrefab = Plugin.Instance.LoadNetworkPrefabFromEmbeddedResource();
				networkPrefab.AddComponent<AudioNetworkHandler>();
				NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				Plugin.Instance.logger.LogInfo((object)"Created AudioNetworkHandler prefab");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		private static void SpawnNetworkHandler()
		{
			//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)
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Spawning network handler");
					networkHandlerHost = Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity);
					if (networkHandlerHost.GetComponent<NetworkObject>().IsSpawned)
					{
						Debug.Log((object)"NetworkObject is spawned and active.");
					}
					else
					{
						Debug.Log((object)"Failed to spawn NetworkObject.");
					}
					networkHandlerHost.GetComponent<NetworkObject>().Spawn(true);
					if ((Object)(object)AudioNetworkHandler.Instance != (Object)null)
					{
						Debug.Log((object)"Successfully accessed AudioNetworkHandler instance.");
					}
					else
					{
						Debug.Log((object)"AudioNetworkHandler instance is null.");
					}
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to spawned network handler");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		private static void DestroyNetworkHandler()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Destroying network handler");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to destroy network handler");
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager))]
	internal class MenuPatcher
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(MenuManager __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(DelayedMainMenuModification());
		}

		private static IEnumerator DelayedMainMenuModification()
		{
			yield return (object)new WaitForSeconds(0f);
			ChangeHostButtonFromMainMenu();
		}

		private static void ChangeHostButtonFromMainMenu()
		{
			Debug.Log((object)"Attempting to add a description to the Host button...");
			GameObject val = GameObject.Find("MenuContainer");
			Transform val2 = ((val != null) ? val.transform.Find("MainButtons") : null);
			object obj;
			if (val2 == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val2.Find("HostButton");
				obj = ((obj2 != null) ? ((Component)obj2).gameObject : null);
			}
			GameObject val3 = (GameObject)obj;
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && !((Object)(object)val3 == (Object)null))
			{
				string text = ((TMP_Text)val3.GetComponentInChildren<TextMeshProUGUI>()).text;
				((TMP_Text)val3.GetComponentInChildren<TextMeshProUGUI>()).text = "<line-height=0.28em>" + text + "\n<size=8><color=#B0B0B0>     Please restart the game for <color=#E6B800>CustomSounds</color> to work properly!</color></size></line-height>";
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public static class TerminalParsePlayerSentencePatch
	{
		public static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			string[] array = __instance.screenText.text.Split(new char[1] { '\n' });
			if (array.Length == 0)
			{
				return true;
			}
			string[] array2 = array.Last().Trim().ToLower()
				.Split(new char[1] { ' ' });
			if (array2.Length == 0 || (array2[0] != "customsounds" && array2[0] != "cs"))
			{
				return true;
			}
			Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array2)));
			if (array2.Length > 1 && (array2[0] == "customsounds" || array2[0] == "cs"))
			{
				switch (array2[1])
				{
				case "reload":
				case "rl":
					Plugin.Instance.RevertSounds();
					Plugin.Instance.ReloadSounds();
					__result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: false, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList)));
					return false;
				case "revert":
				case "rv":
					Plugin.Instance.RevertSounds();
					__result = CreateTerminalNode("Game sounds reverted to original.\n\n");
					return false;
				case "list":
				case "l":
					__result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: true, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList)));
					return false;
				case "help":
				case "h":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n");
					}
					else
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n");
					}
					return false;
				case "sync":
				case "s":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				case "unsync":
				case "u":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				case "fu":
				case "force-unsync":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				default:
					__result = CreateTerminalNode("Unknown customsounds command.\n\n");
					return false;
				}
			}
			return true;
		}

		private static TerminalNode CreateTerminalNode(string message)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.displayText = message;
			val.clearPreviousText = true;
			return val;
		}
	}
}
namespace CustomSounds.Networking
{
	public class AudioNetworkHandler : NetworkBehaviour
	{
		public static AudioNetworkHandler Instance { get; private set; }

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

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

BepInEx/plugins/HelmetCamera.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HelmetCamera")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelmetCamera")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b99c4d46-5f13-47b3-a5af-5e3f37772e77")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HelmetCamera
{
	[BepInPlugin("RickArg.lethalcompany.helmetcameras", "Helmet_Cameras", "2.1.5")]
	public class PluginInit : BaseUnityPlugin
	{
		public static Harmony _harmony;

		public static ConfigEntry<int> config_isHighQuality;

		public static ConfigEntry<int> config_renderDistance;

		public static ConfigEntry<int> config_cameraFps;

		private void Awake()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			config_isHighQuality = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "monitorResolution", 0, "Low FPS affection. High Quality mode. 0 - vanilla (48x48), 1 - vanilla+ (128x128), 2 - mid quality (256x256), 3 - high quality (512x512), 4 - Very High Quality (1024x1024)");
			config_renderDistance = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "renderDistance", 20, "Low FPS affection. Render distance for helmet camera.");
			config_cameraFps = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "cameraFps", 30, "Very high FPS affection. FPS for helmet camera. To increase YOUR fps, you should low cameraFps value.");
			_harmony = new Harmony("HelmetCamera");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Helmet_Cameras is loaded with version 2.1.5!");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"--------Helmet camera patch done.---------");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "RickArg.lethalcompany.helmetcameras";

		public const string PLUGIN_NAME = "Helmet_Cameras";

		public const string PLUGIN_VERSION = "2.1.5";
	}
	public class Plugin : MonoBehaviour
	{
		private RenderTexture renderTexture;

		private bool isMonitorChanged = false;

		private GameObject helmetCameraNew;

		private bool isSceneLoaded = false;

		private bool isCoroutineStarted = false;

		private int currentTransformIndex;

		private int resolution = 0;

		private int renderDistance = 50;

		private float cameraFps = 30f;

		private float elapsed;

		private void Awake()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			resolution = PluginInit.config_isHighQuality.Value;
			renderDistance = PluginInit.config_renderDistance.Value;
			cameraFps = PluginInit.config_cameraFps.Value;
			switch (resolution)
			{
			case 0:
				renderTexture = new RenderTexture(48, 48, 24);
				break;
			case 1:
				renderTexture = new RenderTexture(128, 128, 24);
				break;
			case 2:
				renderTexture = new RenderTexture(256, 256, 24);
				break;
			case 3:
				renderTexture = new RenderTexture(512, 512, 24);
				break;
			case 4:
				renderTexture = new RenderTexture(1024, 1024, 24);
				break;
			}
		}

		public void Start()
		{
			//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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			isCoroutineStarted = false;
			while ((Object)(object)helmetCameraNew == (Object)null)
			{
				helmetCameraNew = new GameObject("HelmetCamera");
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != "MainMenu")
			{
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name != "InitScene")
				{
					activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).name != "InitSceneLaunchOptions")
					{
						isSceneLoaded = true;
						Debug.Log((object)"[HELMET_CAMERAS] Starting coroutine...");
						((MonoBehaviour)this).StartCoroutine(LoadSceneEnter());
						return;
					}
				}
			}
			isSceneLoaded = false;
			isMonitorChanged = false;
		}

		private IEnumerator LoadSceneEnter()
		{
			Debug.Log((object)"[HELMET_CAMERAS] 5 seconds for init mode... Please wait...");
			yield return (object)new WaitForSeconds(5f);
			isCoroutineStarted = true;
			if ((Object)(object)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera") != (Object)null)
			{
				Debug.Log((object)"[HELMET_CAMERAS] Ship camera founded...");
				if (!isMonitorChanged)
				{
					((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube").GetComponent<MeshRenderer>()).materials[2].mainTexture = ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture;
					((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture = (Texture)(object)renderTexture;
					helmetCameraNew.AddComponent<Camera>();
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = false;
					helmetCameraNew.GetComponent<Camera>().targetTexture = renderTexture;
					helmetCameraNew.GetComponent<Camera>().cullingMask = 20649983;
					helmetCameraNew.GetComponent<Camera>().farClipPlane = renderDistance;
					helmetCameraNew.GetComponent<Camera>().nearClipPlane = 0.55f;
					isMonitorChanged = true;
					Debug.Log((object)"[HELMET_CAMERAS] Monitors were changed...");
					Debug.Log((object)"[HELMET_CAMERAS] Turning off vanilla internal ship camera");
					((Behaviour)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").GetComponent<Camera>()).enabled = false;
				}
			}
		}

		public void Update()
		{
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: 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_0268: 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_0114: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: 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)
			bool flag = isSceneLoaded && isCoroutineStarted;
			if (flag && StartOfRound.Instance.localPlayerController.isInHangarShipRoom)
			{
				helmetCameraNew.SetActive(true);
				elapsed += Time.deltaTime;
				if (elapsed > 1f / cameraFps)
				{
					elapsed = 0f;
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = true;
				}
				else
				{
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = false;
				}
				GameObject val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript");
				currentTransformIndex = val.GetComponent<ManualCameraRenderer>().targetTransformIndex;
				TransformAndName val2 = val.GetComponent<ManualCameraRenderer>().radarTargets[currentTransformIndex];
				if (!val2.isNonPlayer)
				{
					try
					{
						helmetCameraNew.transform.SetPositionAndRotation(val2.transform.Find("ScavengerModel/metarig/CameraContainer/MainCamera/HelmetLights").position + new Vector3(0f, 0f, 0f), val2.transform.Find("ScavengerModel/metarig/CameraContainer/MainCamera/HelmetLights").rotation * Quaternion.Euler(0f, 0f, 0f));
						DeadBodyInfo[] array = Object.FindObjectsOfType<DeadBodyInfo>();
						for (int i = 0; i < array.Length; i++)
						{
							if (array[i].playerScript.playerUsername == val2.name)
							{
								helmetCameraNew.transform.SetPositionAndRotation(((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003").position, ((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003").rotation * Quaternion.Euler(0f, 0f, 0f));
							}
						}
						return;
					}
					catch (NullReferenceException)
					{
						Debug.Log((object)"[HELMET_CAMERAS] ERROR NULL REFERENCE");
						return;
					}
				}
				helmetCameraNew.transform.SetPositionAndRotation(val2.transform.position + new Vector3(0f, 1.6f, 0f), val2.transform.rotation * Quaternion.Euler(0f, -90f, 0f));
			}
			else if (flag && !StartOfRound.Instance.localPlayerController.isInHangarShipRoom)
			{
				helmetCameraNew.SetActive(false);
			}
		}
	}
}
namespace HelmetCamera.Patches
{
	[HarmonyPatch]
	internal class HelmetCamera
	{
		public static void InitCameras()
		{
			GameObject val = GameObject.Find("Environment/HangarShip/Cameras/ShipCamera");
			val.AddComponent<Plugin>();
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		public static void InitCamera(ref ManualCameraRenderer __instance)
		{
			InitCameras();
		}
	}
}

BepInEx/plugins/LC_SoundTool.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.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LCSoundTool.Networking;
using LCSoundTool.Patches;
using LCSoundTool.Resources;
using LCSoundTool.Utilities;
using LCSoundToolMod.Properties;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LC_SoundTool")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
[assembly: AssemblyProduct("LC_SoundTool")]
[assembly: AssemblyTitle("LC_SoundTool")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.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 LCSoundToolMod
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LC_SoundTool";

		public const string PLUGIN_NAME = "LC_SoundTool";

		public const string PLUGIN_VERSION = "1.5.0";
	}
}
namespace LCSoundToolMod.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("LCSoundToolMod.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[] soundtool
		{
			get
			{
				object @object = ResourceManager.GetObject("soundtool", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace LCSoundTool
{
	public class AudioSourceExtension : MonoBehaviour
	{
		public AudioSource audioSource;

		public bool playOnAwake = false;

		public bool loop = false;

		private bool updateHasBeenLogged = false;

		private bool hasPlayed = false;

		private void OnEnable()
		{
			if (!((Object)(object)audioSource == (Object)null) && !audioSource.isPlaying)
			{
				if (playOnAwake)
				{
					audioSource.Play();
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in OnEnable function!");
				}
				updateHasBeenLogged = false;
				hasPlayed = false;
			}
		}

		private void OnDisable()
		{
			if (!((Object)(object)audioSource == (Object)null) && audioSource.isPlaying)
			{
				if (playOnAwake)
				{
					audioSource.Stop();
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Stopped playback of {audioSource} with clip {audioSource.clip} in OnDisable function!");
				}
				updateHasBeenLogged = false;
				hasPlayed = false;
			}
		}

		private void Update()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if ((Object)(object)audioSource.clip == (Object)null)
			{
				hasPlayed = false;
			}
			if (audioSource.isPlaying)
			{
				updateHasBeenLogged = false;
			}
			else if (!((Behaviour)audioSource).isActiveAndEnabled)
			{
				hasPlayed = false;
			}
			else
			{
				if (!playOnAwake)
				{
					return;
				}
				if ((Object)(object)audioSource.clip != (Object)null && !hasPlayed)
				{
					audioSource.Play();
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in Update function!");
					}
					updateHasBeenLogged = false;
					hasPlayed = true;
				}
				else if (!updateHasBeenLogged)
				{
					updateHasBeenLogged = true;
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Can not start playback of {audioSource} with missing clip in Update function!");
					}
				}
			}
		}
	}
	public class RandomAudioClip
	{
		public AudioClip clip;

		[Range(0f, 1f)]
		public float chance = 1f;

		public RandomAudioClip(AudioClip clip, float chance)
		{
			this.clip = clip;
			this.chance = chance;
		}
	}
	public class ReplacementAudioClip
	{
		public List<RandomAudioClip> clips;

		public string source = string.Empty;

		public bool canPlay = true;

		private bool initialized = false;

		public ReplacementAudioClip(AudioClip clip, float chance, string source)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip randomAudioClip = new RandomAudioClip(clip, chance);
			if (!clips.ContainsThisRandomAudioClip(randomAudioClip))
			{
				clips.Add(randomAudioClip);
				this.source = source;
			}
			else if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"RandomAudioClip {randomAudioClip.clip.GetName()} ({Mathf.RoundToInt(chance * 100f)}%) already exists withing this AudioClipContainer!");
				SoundTool.Instance.logger.LogDebug((object)"- This AudioClipContainer contains the following clip(s):");
				for (int i = 0; i < clips.Count; i++)
				{
					SoundTool.Instance.logger.LogDebug((object)$"-- Clip {i + 1} - {clips[i].clip.GetName()} with a chance of {Mathf.RoundToInt(clips[i].chance * 100f)}");
				}
			}
		}

		public ReplacementAudioClip(string source)
		{
			Initialize();
			this.source = source;
		}

		public ReplacementAudioClip()
		{
			Initialize();
			source = string.Empty;
		}

		public void AddClip(AudioClip clip, float chance)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip randomAudioClip = new RandomAudioClip(clip, chance);
			if (!clips.ContainsThisRandomAudioClip(randomAudioClip))
			{
				clips.Add(randomAudioClip);
			}
			else if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"RandomAudioClip {randomAudioClip.clip.GetName()} ({Mathf.RoundToInt(chance * 100f)}%) already exists withing this AudioClipContainer!");
				SoundTool.Instance.logger.LogDebug((object)"- This AudioClipContainer contains the following clip(s):");
				for (int i = 0; i < clips.Count; i++)
				{
					SoundTool.Instance.logger.LogDebug((object)$"-- Clip {i + 1} - {clips[i].clip.GetName()} with a chance of {Mathf.RoundToInt(clips[i].chance * 100f)}");
				}
			}
		}

		public bool Full()
		{
			if (!initialized)
			{
				Initialize();
			}
			float num = 0f;
			for (int i = 0; i < clips.Count; i++)
			{
				num += clips[i].chance;
			}
			return num >= 1f;
		}

		public bool ContainsClip(AudioClip clip, float chance)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip thisClip = new RandomAudioClip(clip, chance);
			return clips.ContainsThisRandomAudioClip(thisClip);
		}

		private void Initialize()
		{
			clips = new List<RandomAudioClip>();
			initialized = true;
		}
	}
	[BepInPlugin("LCSoundTool", "LC Sound Tool", "1.5.0")]
	public class SoundTool : BaseUnityPlugin
	{
		public enum AudioType
		{
			wav,
			ogg,
			mp3
		}

		private const string PLUGIN_GUID = "LCSoundTool";

		private const string PLUGIN_NAME = "LC Sound Tool";

		private ConfigEntry<bool> configUseNetworking;

		private ConfigEntry<bool> configSyncRandomSeed;

		private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay;

		private ConfigEntry<bool> configPrintInfoByDefault;

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

		public static SoundTool Instance;

		internal ManualLogSource logger;

		public KeyboardShortcut toggleAudioSourceDebugLog;

		public KeyboardShortcut toggleIndepthDebugLog;

		public KeyboardShortcut toggleInformationalDebugLog;

		public KeyboardShortcut printAllSoundsDebugLog;

		public bool wasKeyDown;

		public bool wasKeyDown2;

		public bool wasKeyDown3;

		public bool wasKeyDown4;

		public static bool debugAudioSources;

		public static bool indepthDebugging;

		public static bool infoDebugging;

		public static bool networkingInitialized { get; private set; }

		public static bool networkingAvailable { get; private set; }

		public static Dictionary<string, ReplacementAudioClip> replacedClips { get; private set; }

		public static Dictionary<string, AudioClip> networkedClips => NetworkHandler.networkedAudioClips;

		public static Dictionary<string, AudioType> clipTypes { get; private set; }

		public static event Action ClientNetworkedAudioChanged
		{
			add
			{
				NetworkHandler.ClientNetworkedAudioChanged += value;
			}
			remove
			{
				NetworkHandler.ClientNetworkedAudioChanged -= value;
			}
		}

		public static event Action HostNetworkedAudioChanged
		{
			add
			{
				NetworkHandler.HostNetworkedAudioChanged += value;
			}
			remove
			{
				NetworkHandler.HostNetworkedAudioChanged -= value;
			}
		}

		public static bool IsDebuggingOn()
		{
			if (debugAudioSources || indepthDebugging || infoDebugging)
			{
				return true;
			}
			return false;
		}

		private void Awake()
		{
			//IL_014f: 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_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_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_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			networkingAvailable = true;
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join.");
			configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene.");
			configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources.");
			configPrintInfoByDefault = ((BaseUnityPlugin)this).Config.Bind<bool>("Logging", "PrintInfoByDefault", false, "Whether or not to print additional information logs created by this mod by default. If set to false, informational logs may be toggled on any time with LeftAlt + F5.");
			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);
					}
				}
			}
			logger = Logger.CreateLogSource("LCSoundTool");
			logger.LogInfo((object)"Plugin LCSoundTool is loaded!");
			toggleAudioSourceDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]);
			toggleIndepthDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 });
			toggleInformationalDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 });
			printAllSoundsDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 });
			debugAudioSources = false;
			indepthDebugging = false;
			if (configPrintInfoByDefault.Value)
			{
				infoDebugging = true;
			}
			else
			{
				infoDebugging = false;
			}
			replacedClips = new Dictionary<string, ReplacementAudioClip>();
			clipTypes = new Dictionary<string, AudioType>();
		}

		private void Start()
		{
			if (!configUseNetworking.Value)
			{
				networkingAvailable = false;
				Instance.logger.LogWarning((object)"Networking disabled. Mod in fully client side mode, but no networked actions can take place! You can safely ignore this if you want the mod to run fully client side.");
			}
			else
			{
				networkingAvailable = true;
			}
			if (configUseNetworking.Value)
			{
				logger.LogDebug((object)"Loading SoundTool AssetBundle...");
				Assets.bundle = AssetBundle.LoadFromMemory(LCSoundToolMod.Properties.Resources.soundtool);
				if ((Object)(object)Assets.bundle == (Object)null)
				{
					logger.LogError((object)"Failed to load SoundTool AssetBundle!");
				}
				else
				{
					logger.LogDebug((object)"Finished loading SoundTool AssetBundle!");
				}
			}
			harmony.PatchAll(typeof(AudioSourcePatch));
			if (configUseNetworking.Value)
			{
				harmony.PatchAll(typeof(GameNetworkManagerPatch));
				harmony.PatchAll(typeof(StartOfRoundPatch));
			}
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private void Update()
		{
			if (configUseNetworking.Value)
			{
				if (!networkingInitialized)
				{
					if ((Object)(object)NetworkHandler.Instance != (Object)null)
					{
						networkingInitialized = true;
					}
				}
				else if ((Object)(object)NetworkHandler.Instance == (Object)null)
				{
					networkingInitialized = false;
				}
			}
			else
			{
				networkingInitialized = false;
			}
			if (((KeyboardShortcut)(ref printAllSoundsDebugLog)).IsDown() && !wasKeyDown4)
			{
				wasKeyDown4 = true;
			}
			if (((KeyboardShortcut)(ref printAllSoundsDebugLog)).IsUp() && wasKeyDown4)
			{
				wasKeyDown4 = false;
				Instance.logger.LogDebug((object)"Printing all currently replaced sounds...");
				Instance.logger.LogDebug((object)" ");
				string[] array = replacedClips.Keys.ToArray();
				for (int i = 0; i < replacedClips.Count; i++)
				{
					ReplacementAudioClip replacementAudioClip = replacedClips[array[i]];
					Instance.logger.LogDebug((object)$"Clip named {array[i]} with {replacementAudioClip.clips.Count} replacement clip(s)");
					Instance.logger.LogDebug((object)$"- Clip can play? {replacementAudioClip.canPlay}");
					Instance.logger.LogDebug((object)("- Clip audio source(s)? " + replacementAudioClip.source));
					Instance.logger.LogDebug((object)$"- All {replacementAudioClip.clips.Count} clip(s):");
					for (int j = 0; j < replacementAudioClip.clips.Count; j++)
					{
						Instance.logger.LogDebug((object)$"-- Clip {j + 1} - {replacementAudioClip.clips[j].clip.GetName()} with chance of {Mathf.RoundToInt(replacementAudioClip.clips[j].chance * 100f)}%");
					}
				}
				Instance.logger.LogDebug((object)" ");
				Instance.logger.LogDebug((object)"Finished printing all currently replaced sounds!");
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsDown() && !wasKeyDown3)
			{
				wasKeyDown3 = true;
				wasKeyDown2 = false;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsUp() && wasKeyDown3)
			{
				wasKeyDown3 = false;
				wasKeyDown2 = false;
				wasKeyDown = false;
				infoDebugging = !infoDebugging;
				Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!");
				return;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && !wasKeyDown2)
			{
				wasKeyDown2 = true;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsUp() && wasKeyDown2)
			{
				wasKeyDown2 = false;
				wasKeyDown = false;
				debugAudioSources = !debugAudioSources;
				indepthDebugging = debugAudioSources;
				infoDebugging = debugAudioSources;
				Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!");
				return;
			}
			if (!wasKeyDown2 && !((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && ((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsDown() && !wasKeyDown)
			{
				wasKeyDown = true;
				wasKeyDown2 = false;
			}
			if (((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsUp() && wasKeyDown)
			{
				wasKeyDown = false;
				wasKeyDown2 = false;
				debugAudioSources = !debugAudioSources;
				if (indepthDebugging && !debugAudioSources)
				{
					indepthDebugging = false;
				}
				Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!");
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Instance == (Object)null))
			{
				PatchPlayOnAwakeAudio(scene);
				OnSceneLoadedNetworking();
				if (((Scene)(ref scene)).name.ToLower().Contains("level"))
				{
					((MonoBehaviour)this).StopAllCoroutines();
					((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, 1f));
				}
			}
		}

		private IEnumerator PatchPlayOnAwakeDelayed(Scene scene, float wait)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (infoDebugging)
			{
				logger.LogDebug((object)$"Started playOnAwake patch coroutine with delay of {wait} seconds");
			}
			yield return (object)new WaitForSecondsRealtime(wait);
			if (infoDebugging)
			{
				logger.LogDebug((object)"Running playOnAwake patch coroutine!");
			}
			PatchPlayOnAwakeAudio(scene);
			float repeatWait = configPlayOnAwakePatchRepeatDelay.Value;
			if (repeatWait != 0f)
			{
				if (repeatWait < 10f)
				{
					repeatWait = 10f;
				}
				if (repeatWait > 600f)
				{
					repeatWait = 600f;
				}
				((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, repeatWait));
			}
		}

		private void PatchPlayOnAwakeAudio(Scene scene)
		{
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)("Grabbing all playOnAwake AudioSources for loaded scene " + ((Scene)(ref scene)).name));
			}
			AudioSource[] allPlayOnAwakeAudioSources = GetAllPlayOnAwakeAudioSources();
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)$"Found a total of {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)!");
				Instance.logger.LogDebug((object)$"Starting setup on {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)...");
			}
			AudioSource[] array = allPlayOnAwakeAudioSources;
			AudioSourceExtension audioSourceExtension = default(AudioSourceExtension);
			foreach (AudioSource val in array)
			{
				val.Stop();
				if (((Component)((Component)val).transform).TryGetComponent<AudioSourceExtension>(ref audioSourceExtension))
				{
					audioSourceExtension.audioSource = val;
					audioSourceExtension.playOnAwake = true;
					audioSourceExtension.loop = val.loop;
					val.playOnAwake = false;
					if (infoDebugging)
					{
						Instance.logger.LogDebug((object)$"-Set- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!");
					}
					continue;
				}
				AudioSourceExtension audioSourceExtension2 = ((Component)val).gameObject.AddComponent<AudioSourceExtension>();
				audioSourceExtension2.audioSource = val;
				audioSourceExtension2.playOnAwake = true;
				audioSourceExtension2.loop = val.loop;
				val.playOnAwake = false;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"-Add- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!");
				}
			}
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)$"Done setting up {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSources!");
			}
		}

		private void OnSceneLoadedNetworking()
		{
			if (networkingAvailable && networkingInitialized && configSyncRandomSeed.Value)
			{
				int num = (int)DateTime.Now.Ticks;
				Random.InitState(num);
				SendUnityRandomSeed(num);
			}
		}

		public AudioSource[] GetAllPlayOnAwakeAudioSources()
		{
			AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
			List<AudioSource> list = new List<AudioSource>();
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].playOnAwake)
				{
					list.Add(array[i]);
				}
			}
			return list.ToArray();
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			string text = originalName;
			string name = newClip.GetName();
			string text2 = string.Empty;
			float num = 100f;
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text3 = array[^2];
						if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
						{
							text2 = text3.Substring(1);
						}
					}
					string text4 = array[^1];
					if (int.TryParse(text4, out var result))
					{
						num = (float)result * 0.01f;
					}
					else if (!string.IsNullOrEmpty(text4) && text4.StartsWith("_"))
					{
						text2 = text4.Substring(1);
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(text2))
			{
				text = originalName + "#" + text2;
			}
			if (replacedClips.ContainsKey(text) && num >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			num = Mathf.Clamp01(num);
			if (replacedClips.ContainsKey(text))
			{
				replacedClips[text].AddClip(newClip, num);
			}
			else
			{
				replacedClips.Add(text, new ReplacementAudioClip(newClip, num, text2));
			}
			float num2 = 0f;
			for (int i = 0; i < replacedClips[text].clips.Count(); i++)
			{
				num2 += replacedClips[text].clips[i].chance;
			}
			int num3 = Mathf.RoundToInt(num2 * 100f);
			if ((num3 < 100 || num3 > 100) && replacedClips[text].clips.Count() > 1)
			{
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} does not equal 100%. Currently {num3}% (at least yet?)");
				}
			}
			else if (num3 == 100 && replacedClips[text].clips.Count() > 1 && infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			string text = originalName;
			string name = newClip.GetName();
			string text2 = string.Empty;
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text3 = array[^2];
						if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
						{
							text2 = text3.Substring(1);
						}
					}
					string text4 = array[^1];
					if (int.TryParse(text4, out var result))
					{
						Instance.logger.LogDebug((object)$"Clip {name} contains random chance specified in it's name ({result}%) but you're using the manually function to assign it's chance. ({Mathf.RoundToInt(chance * 100f)}%) The file name will be ignored.");
					}
					else if (!string.IsNullOrEmpty(text4) && text4.StartsWith("_"))
					{
						text2 = text4.Substring(1);
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(text2))
			{
				text = originalName + "#" + text2;
			}
			if (replacedClips.ContainsKey(text) && chance >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			chance = Mathf.Clamp01(chance);
			if (replacedClips.ContainsKey(text))
			{
				replacedClips[text].AddClip(newClip, chance);
			}
			else
			{
				replacedClips.Add(text, new ReplacementAudioClip(newClip, chance, text2));
			}
			float num = 0f;
			for (int i = 0; i < replacedClips[text].clips.Count(); i++)
			{
				num += replacedClips[text].clips[i].chance;
			}
			int num2 = Mathf.RoundToInt(num * 100f);
			if ((num2 < 100 || num2 > 100) && replacedClips[text].clips.Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} does not equal 100% (at least yet?)");
			}
			else if (num2 == 100 && replacedClips[text].clips.Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, chance);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, string source)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (string.IsNullOrEmpty(source))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without allowed audio source specified! This is not allowed.");
				return;
			}
			string text = originalName;
			string name = newClip.GetName();
			float num = 100f;
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text2 = array[^2];
						if (!string.IsNullOrEmpty(text2) && text2.StartsWith("_"))
						{
							Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text2.Substring(1) + ") but you're using the manual function to assign it's source. (" + source + ") The file name will be ignored."));
						}
					}
					string text3 = array[^1];
					if (int.TryParse(text3, out var result))
					{
						num = (float)result * 0.01f;
					}
					else if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
					{
						Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text3.Substring(1) + ") but you're using the manual function to assign it's source. (" + source + ") The file name will be ignored."));
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(source))
			{
				text = originalName + "#" + source;
			}
			if (replacedClips.ContainsKey(text) && num >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			num = Mathf.Clamp01(num);
			if (replacedClips.ContainsKey(text))
			{
				replacedClips[text].AddClip(newClip, num);
			}
			else
			{
				replacedClips.Add(text, new ReplacementAudioClip(newClip, num, source));
			}
			float num2 = 0f;
			for (int i = 0; i < replacedClips[text].clips.Count(); i++)
			{
				num2 += replacedClips[text].clips[i].chance;
			}
			int num3 = Mathf.RoundToInt(num2 * 100f);
			if ((num3 < 100 || num3 > 100) && replacedClips[text].clips.Count() > 1)
			{
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} does not equal 100%. Currently {num3}% (at least yet?)");
				}
			}
			else if (num3 == 100 && replacedClips[text].clips.Count() > 1 && infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, string source)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, source);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, string[] source)
		{
			string text = string.Empty;
			if (source != null && source.Length != 0)
			{
				for (int i = 0; i < source.Length; i++)
				{
					if (!string.IsNullOrEmpty(source[i]))
					{
						text = text + "," + source[i];
					}
				}
			}
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without allowed audio source specified! This is not allowed.");
				return;
			}
			string text2 = originalName;
			string name = newClip.GetName();
			float num = 100f;
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text3 = array[^2];
						if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
						{
							Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text3.Substring(1) + ") but you're using the manual function to assign it's source. (" + text + ") The file name will be ignored."));
						}
					}
					string text4 = array[^1];
					if (int.TryParse(text4, out var result))
					{
						num = (float)result * 0.01f;
					}
					else if (!string.IsNullOrEmpty(text4) && text4.StartsWith("_"))
					{
						Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text4.Substring(1) + ") but you're using the manual function to assign it's source. (" + text + ") The file name will be ignored."));
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(text))
			{
				text2 = originalName + "#" + text;
			}
			if (replacedClips.ContainsKey(text2) && num >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			num = Mathf.Clamp01(num);
			if (replacedClips.ContainsKey(text2))
			{
				replacedClips[text2].AddClip(newClip, num);
			}
			else
			{
				replacedClips.Add(text2, new ReplacementAudioClip(newClip, num, text));
			}
			float num2 = 0f;
			for (int j = 0; j < replacedClips[text2].clips.Count(); j++)
			{
				num2 += replacedClips[text2].clips[j].chance;
			}
			int num3 = Mathf.RoundToInt(num2 * 100f);
			if ((num3 < 100 || num3 > 100) && replacedClips[text2].clips.Count() > 1)
			{
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text2].clips.Count()} random audio clips for audio clip {text2} does not equal 100%. Currently {num3}% (at least yet?)");
				}
			}
			else if (num3 == 100 && replacedClips[text2].clips.Count() > 1 && infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text2].clips.Count()} random audio clips for audio clip {text2} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, string[] source)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, source);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance, string source)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (string.IsNullOrEmpty(source))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without allowed audio source specified! This is not allowed.");
				return;
			}
			string text = originalName;
			string name = newClip.GetName();
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text2 = array[^2];
						if (!string.IsNullOrEmpty(text2) && text2.StartsWith("_"))
						{
							Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text2.Substring(1) + ") but you're using the manual function to assign it's source. (" + source + ") The file name will be ignored."));
						}
					}
					string text3 = array[^1];
					if (int.TryParse(text3, out var result))
					{
						Instance.logger.LogDebug((object)$"Clip {name} contains random chance specified in it's name ({result}%) but you're using the manual function to assign it's chance. ({Mathf.RoundToInt(chance * 100f)}%) The file name will be ignored.");
					}
					else if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
					{
						Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text3.Substring(1) + ") but you're using the manual function to assign it's source. (" + source + ") The file name will be ignored."));
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(source))
			{
				text = originalName + "#" + source;
			}
			if (replacedClips.ContainsKey(text) && chance >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			chance = Mathf.Clamp01(chance);
			if (replacedClips.ContainsKey(text))
			{
				replacedClips[text].AddClip(newClip, chance);
			}
			else
			{
				replacedClips.Add(text, new ReplacementAudioClip(newClip, chance, source));
			}
			float num = 0f;
			for (int i = 0; i < replacedClips[text].clips.Count(); i++)
			{
				num += replacedClips[text].clips[i].chance;
			}
			int num2 = Mathf.RoundToInt(num * 100f);
			if ((num2 < 100 || num2 > 100) && replacedClips[text].clips.Count() > 1)
			{
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} does not equal 100%. Currently {num2}% (at least yet?)");
				}
			}
			else if (num2 == 100 && replacedClips[text].clips.Count() > 1 && infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance, string source)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, chance, source);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance, string[] source)
		{
			string text = string.Empty;
			if (source != null && source.Length != 0)
			{
				for (int i = 0; i < source.Length; i++)
				{
					if (!string.IsNullOrEmpty(source[i]))
					{
						text = text + "," + source[i];
					}
				}
			}
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without allowed audio source specified! This is not allowed.");
				return;
			}
			string text2 = originalName;
			string name = newClip.GetName();
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text3 = array[^2];
						if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
						{
							Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text3.Substring(1) + ") but you're using the manual function to assign it's source. (" + text + ") The file name will be ignored."));
						}
					}
					string text4 = array[^1];
					if (int.TryParse(text4, out var result))
					{
						Instance.logger.LogDebug((object)$"Clip {name} contains random chance specified in it's name ({result}%) but you're using the manual function to assign it's chance. ({Mathf.RoundToInt(chance * 100f)}%) The file name will be ignored.");
					}
					else if (!string.IsNullOrEmpty(text4) && text4.StartsWith("_"))
					{
						Instance.logger.LogDebug((object)("Clip " + name + " contains source specified in it's name (" + text4.Substring(1) + ") but you're using the manual function to assign it's source. (" + text + ") The file name will be ignored."));
					}
					name = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name + " does not contain a '-' character for source name or chance"));
				}
			}
			if (!string.IsNullOrEmpty(text))
			{
				text2 = originalName + "#" + text;
			}
			if (replacedClips.ContainsKey(text2) && chance >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with new clip that has 100% chance of playback! This is not allowed.");
				return;
			}
			chance = Mathf.Clamp01(chance);
			if (replacedClips.ContainsKey(text2))
			{
				replacedClips[text2].AddClip(newClip, chance);
			}
			else
			{
				replacedClips.Add(text2, new ReplacementAudioClip(newClip, chance, text));
			}
			float num = 0f;
			for (int j = 0; j < replacedClips[text2].clips.Count(); j++)
			{
				num += replacedClips[text2].clips[j].chance;
			}
			int num2 = Mathf.RoundToInt(num * 100f);
			if ((num2 < 100 || num2 > 100) && replacedClips[text2].clips.Count() > 1)
			{
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text2].clips.Count()} random audio clips for audio clip {text2} does not equal 100%. Currently {num2}% (at least yet?)");
				}
			}
			else if (num2 == 100 && replacedClips[text2].clips.Count() > 1 && infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text2].clips.Count()} random audio clips for audio clip {text2} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance, string[] source)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, chance, source);
			}
		}

		public static void RemoveRandomAudioClip(string name, float chance)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				if (!(chance > 0f))
				{
					return;
				}
				for (int i = 0; i < replacedClips[name].clips.Count(); i++)
				{
					if (replacedClips[name].clips[i].chance == chance)
					{
						replacedClips[name].clips.RemoveAt(i);
						if (replacedClips[name].clips.Count <= 0)
						{
							Instance.logger.LogDebug((object)("Removed replaced AudioClip " + name + " completely as all of it's random clips have been removed."));
							replacedClips.Remove(name);
						}
						break;
					}
				}
			}
		}

		public static void RemoveRandomAudioClip(string name, string source, float chance)
		{
			string text = name;
			if (!string.IsNullOrEmpty(text))
			{
				text = name + "#" + source;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				if (!(chance > 0f))
				{
					return;
				}
				for (int i = 0; i < replacedClips[text].clips.Count(); i++)
				{
					if (replacedClips[text].clips[i].chance == chance)
					{
						replacedClips[text].clips.RemoveAt(i);
						if (replacedClips[text].clips.Count <= 0)
						{
							Instance.logger.LogDebug((object)("Removed replaced AudioClip " + text + " completely as all of it's random clips have been removed."));
							replacedClips.Remove(text);
						}
						break;
					}
				}
			}
		}

		public static void RemoveRandomAudioClip(string name, string[] source, float chance)
		{
			string text = name;
			string text2 = string.Empty;
			if (source != null && source.Length != 0)
			{
				for (int i = 0; i < source.Length; i++)
				{
					if (!string.IsNullOrEmpty(source[i]))
					{
						text2 = text2 + "," + source[i];
					}
				}
			}
			if (!string.IsNullOrEmpty(text2))
			{
				text = name + "#" + text2;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				if (!(chance > 0f))
				{
					return;
				}
				for (int j = 0; j < replacedClips[text].clips.Count(); j++)
				{
					if (replacedClips[text].clips[j].chance == chance)
					{
						replacedClips[text].clips.RemoveAt(j);
						if (replacedClips[text].clips.Count <= 0)
						{
							Instance.logger.LogDebug((object)("Removed replaced AudioClip " + text + " completely as all of it's random clips have been removed."));
							replacedClips.Remove(text);
						}
						break;
					}
				}
			}
		}

		public static void RestoreAudioClip(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				replacedClips.Remove(name);
			}
		}

		public static void RestoreAudioClip(string name, string source)
		{
			string text = name;
			if (!string.IsNullOrEmpty(source))
			{
				text = name + "#" + source;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				replacedClips.Remove(text);
			}
		}

		public static void RestoreAudioClip(string name, string[] source)
		{
			string text = name;
			string text2 = string.Empty;
			if (source != null && source.Length != 0)
			{
				for (int i = 0; i < source.Length; i++)
				{
					if (!string.IsNullOrEmpty(source[i]))
					{
						text2 = text2 + "," + source[i];
					}
				}
			}
			if (!string.IsNullOrEmpty(text2))
			{
				text = name + "#" + text2;
			}
			if (string.IsNullOrEmpty(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(text))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				replacedClips.Remove(text);
			}
		}

		public static void RestoreAudioClip(AudioClip clip)
		{
			if ((Object)(object)clip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without vanilla clip name specified! This is not allowed.");
			}
			else
			{
				RestoreAudioClip(clip.GetName());
			}
		}

		public static void RestoreAudioClip(string name, AudioClip replacementClip)
		{
			if ((Object)(object)replacementClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without replacement clip specified! This is not allowed.");
				return;
			}
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without vanilla clip name specified! This is not allowed.");
				return;
			}
			string name2 = replacementClip.GetName();
			string text = string.Empty;
			float num = 0f;
			if (name2.Contains("-"))
			{
				string[] array = name2.Split('-');
				if (array.Length > 1)
				{
					if (array.Length > 2)
					{
						string text2 = array[^2];
						if (!string.IsNullOrEmpty(text2) && text2.StartsWith("_"))
						{
							text = text2.Substring(1);
						}
					}
					string text3 = array[^1];
					if (int.TryParse(text3, out var result))
					{
						num = (float)result * 0.01f;
					}
					else if (!string.IsNullOrEmpty(text3) && text3.StartsWith("_"))
					{
						text = text3.Substring(1);
					}
					name2 = string.Join("-", array, 0, array.Length - 1);
				}
				else if (infoDebugging)
				{
					Instance.logger.LogDebug((object)("Clip " + name2 + " does not contain a '-' character for source name or chance"));
				}
			}
			string text4 = name + "#" + text;
			if (!replacedClips.ContainsKey(text4))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				RestoreAudioClip(text4);
			}
		}

		public static AudioClip GetAudioClip(string modFolder, string soundName)
		{
			return GetAudioClip(modFolder, string.Empty, soundName);
		}

		public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName)
		{
			AudioType audioType = AudioType.wav;
			bool flag = true;
			string text = " ";
			string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName);
			string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName);
			string path = Path.Combine(Paths.PluginPath, modFolder, subFolder);
			string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName);
			string path2 = Path.Combine(Paths.PluginPath, subFolder);
			if (!Directory.Exists(path))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!"));
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!"));
					if (!modFolder.Contains("-"))
					{
						Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author.");
					}
				}
				flag = false;
			}
			if (!File.Exists(text2))
			{
				Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!"));
				flag = false;
				Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "..."));
				if (File.Exists(text3))
				{
					Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!"));
					text2 = text3;
					flag = true;
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!"));
				}
			}
			if (Directory.Exists(path2))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!"));
				}
				else if (!modFolder.Contains("-"))
				{
					Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!");
				}
			}
			if (File.Exists(text4))
			{
				Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!"));
				text = " legacy ";
				text2 = text4;
				flag = true;
			}
			string[] array = soundName.Split('.');
			if (array[^1].ToLower().Contains("wav"))
			{
				audioType = AudioType.wav;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as a PCM WAVE file!");
				}
			}
			else if (array[^1].ToLower().Contains("ogg"))
			{
				audioType = AudioType.ogg;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as an Ogg Vorbis file!");
				}
			}
			else if (array[^1].ToLower().Contains("mp3"))
			{
				audioType = AudioType.mp3;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as a MPEG MP3 file!");
				}
			}
			else
			{
				Instance.logger.LogWarning((object)("Failed to detect file type of a sound file! This may cause issues with other mod functionality. Sound: " + soundName));
			}
			AudioClip val = null;
			if (flag)
			{
				Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2));
				switch (audioType)
				{
				case AudioType.wav:
					val = WavUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.ogg:
					val = OggUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.mp3:
					val = Mp3Utility.LoadFromDiskToAudioClip(text2);
					break;
				}
				Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!");
			}
			else
			{
				Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!"));
			}
			if (string.IsNullOrEmpty(val.GetName()))
			{
				string empty = string.Empty;
				string[] array2 = new string[0];
				switch (audioType)
				{
				case AudioType.wav:
					empty = soundName.Replace(".wav", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				case AudioType.ogg:
					empty = soundName.Replace(".ogg", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				case AudioType.mp3:
					empty = soundName.Replace(".mp3", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				string name = val.GetName();
				if (clipTypes.ContainsKey(name))
				{
					clipTypes[name] = audioType;
				}
				else
				{
					clipTypes.Add(name, audioType);
				}
			}
			return val;
		}

		public static AudioClip GetAudioClip(string modFolder, string soundName, AudioType audioType)
		{
			return GetAudioClip(modFolder, string.Empty, soundName, audioType);
		}

		public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName, AudioType audioType)
		{
			bool flag = true;
			string text = " ";
			string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName);
			string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName);
			string path = Path.Combine(Paths.PluginPath, modFolder, subFolder);
			string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName);
			string path2 = Path.Combine(Paths.PluginPath, subFolder);
			if (!Directory.Exists(path))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!"));
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!"));
					if (!modFolder.Contains("-"))
					{
						Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author.");
					}
				}
				flag = false;
			}
			if (!File.Exists(text2))
			{
				Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!"));
				flag = false;
				Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "..."));
				if (File.Exists(text3))
				{
					Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!"));
					text2 = text3;
					flag = true;
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!"));
				}
			}
			if (Directory.Exists(path2))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!"));
				}
				else if (!modFolder.Contains("-"))
				{
					Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!");
				}
			}
			if (File.Exists(text4))
			{
				Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!"));
				text = " legacy ";
				text2 = text4;
				flag = true;
			}
			switch (audioType)
			{
			case AudioType.wav:
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File defined as a WAV file!");
				}
				break;
			case AudioType.ogg:
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File defined as an Ogg Vorbis file!");
				}
				break;
			case AudioType.mp3:
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File defined as a MPEG MP3 file!");
				}
				break;
			}
			AudioClip val = null;
			if (flag)
			{
				Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2));
				switch (audioType)
				{
				case AudioType.wav:
					val = WavUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.ogg:
					val = OggUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.mp3:
					val = Mp3Utility.LoadFromDiskToAudioClip(text2);
					break;
				}
				Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!");
			}
			else
			{
				Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!"));
			}
			if (string.IsNullOrEmpty(val.GetName()))
			{
				string empty = string.Empty;
				string[] array = new string[0];
				switch (audioType)
				{
				case AudioType.wav:
					empty = soundName.Replace(".wav", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				case AudioType.ogg:
					empty = soundName.Replace(".ogg", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				case AudioType.mp3:
					empty = soundName.Replace(".mp3", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				string name = val.GetName();
				if (clipTypes.ContainsKey(name))
				{
					clipTypes[name] = audioType;
				}
				else
				{
					clipTypes.Add(name, audioType);
				}
			}
			return val;
		}

		public static void SendNetworkedAudioClip(AudioClip audioClip)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)$"Networking disabled! Failed to send {audioClip}!");
				return;
			}
			if ((Object)(object)audioClip == (Object)null)
			{
				Instance.logger.LogWarning((object)$"audioClip variable of SendAudioClip not assigned! Failed to send {audioClip}!");
				return;
			}
			if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)$"Instance of SoundTool not found or networking has not finished initializing. Failed to send {audioClip}! If you're sending things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!");
				return;
			}
			string name = audioClip.GetName();
			if (clipTypes.ContainsKey(name))
			{
				if (clipTypes[name] == AudioType.ogg)
				{
					NetworkHandler.Instance.SendAudioClipServerRpc(name, OggUtility.AudioClipToByteArray(audioClip, out var _));
					return;
				}
				if (clipTypes[name] == AudioType.mp3)
				{
					NetworkHandler.Instance.SendAudioClipServerRpc(name, Mp3Utility.AudioClipToByteArray(audioClip, out var _));
					return;
				}
			}
			NetworkHandler.Instance.SendAudioClipServerRpc(name, WavUtility.AudioClipToByteArray(audioClip, out var _));
		}

		public static void RemoveNetworkedAudioClip(AudioClip audioClip)
		{
			RemoveNetworkedAudioClip(audioClip.GetName());
		}

		public static void RemoveNetworkedAudioClip(string audioClip)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)("Networking disabled! Failed to remove " + audioClip + "!"));
			}
			else if (string.IsNullOrEmpty(audioClip))
			{
				Instance.logger.LogWarning((object)("audioClip variable of RemoveAudioClip not assigned! Failed to remove " + audioClip + "!"));
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)("Instance of SoundTool not found or networking has not finished initializing. Failed to remove " + audioClip + "! If you're removing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"));
			}
			else
			{
				NetworkHandler.Instance.RemoveAudioClipServerRpc(audioClip);
			}
		}

		public static void SyncNetworkedAudioClips()
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)"Networking disabled! Failed to sync audio clips!");
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to sync networked audio! If you're syncing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!");
			}
			else
			{
				NetworkHandler.Instance.SyncAudioClipsServerRpc();
			}
		}

		public static void SendUnityRandomSeed(int seed)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)"Networking disabled! Failed to send Unity random seed!");
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to send Unity Random seed! If you're sending the seed in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked methods run only after the player setups a networked connection!");
			}
			else
			{
				NetworkHandler.Instance.SendSeedToClientsServerRpc(seed);
			}
		}
	}
}
namespace LCSoundTool.Utilities
{
	public static class Extensions
	{
		public static bool ContainsThisRandomAudioClip(this List<RandomAudioClip> list, RandomAudioClip thisClip)
		{
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].chance == thisClip.chance && list[i].clip.GetName() == thisClip.clip.GetName())
				{
					return true;
				}
			}
			return false;
		}
	}
	public static class Mp3Utility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)13);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load MP3 AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
	public static class OggUtility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)14);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load OGGVORBIS AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
	public static class WavUtility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load WAV AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
}
namespace LCSoundTool.Patches
{
	[HarmonyPatch(typeof(AudioSource))]
	internal class AudioSourcePatch
	{
		private static Dictionary<string, AudioClip> originalClips = new Dictionary<string, AudioClip>();

		[HarmonyPatch("Play", new Type[] { })]
		[HarmonyPrefix]
		public static void Play_Patch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("Play", new Type[] { typeof(ulong) })]
		[HarmonyPrefix]
		public static void Play_UlongPatch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("Play", new Type[] { typeof(double) })]
		[HarmonyPrefix]
		public static void Play_DoublePatch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("PlayDelayed", new Type[] { typeof(float) })]
		[HarmonyPrefix]
		public static void PlayDelayed_Patch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayDelayedMethod(__instance);
		}

		[HarmonyPatch("PlayClipAtPoint", new Type[]
		{
			typeof(AudioClip),
			typeof(Vector3),
			typeof(float)
		})]
		[HarmonyPrefix]
		public static bool PlayClipAtPoint_Patch(AudioClip clip, Vector3 position, float volume)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject($"ClipAtPoint_{clip}");
			val.transform.position = position;
			AudioSource val2 = val.AddComponent<AudioSource>();
			val2.clip = clip;
			val2.spatialBlend = 1f;
			val2.volume = volume;
			val2.Play();
			DebugPlayClipAtPointMethod(val2, position);
			Object.Destroy((Object)(object)val, clip.length * ((Time.timeScale < 0.01f) ? 0.01f : Time.timeScale));
			return false;
		}

		[HarmonyPatch("PlayOneShotHelper", new Type[]
		{
			typeof(AudioSource),
			typeof(AudioClip),
			typeof(float)
		})]
		[HarmonyPrefix]
		public static void PlayOneShotHelper_Patch(AudioSource source, ref AudioClip clip, float volumeScale)
		{
			clip = ReplaceClipWithNew(clip, source);
			DebugPlayOneShotMethod(source, clip);
		}

		private static void DebugPlayMethod(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} at");
				Transform val = ((Component)instance).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}");
				}
			}
		}

		private static void DebugPlayDelayedMethod(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name} with delay");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} with delay at");
				Transform val = ((Component)instance).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}");
				}
			}
		}

		private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position)
		{
			//IL_0065: 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)
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within ");
				Transform val = ((Component)audioSource).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}");
				}
			}
		}

		private static void DebugPlayOneShotMethod(AudioSource source, AudioClip clip)
		{
			if ((Object)(object)source == (Object)null || (Object)(object)clip == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)source != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{source} at {((Component)source).transform.root} is playing one shot {((Object)clip).name}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)source != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{source} is playing one shot {((Object)clip).name} at");
				Transform val = ((Component)source).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)source).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)source).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)source).transform.root}");
				}
			}
		}

		private static void RunDynamicClipReplacement(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null)
			{
				return;
			}
			string name = ((Object)((Component)instance).gameObject).name;
			bool flag = true;
			AudioClip value;
			string text = ((!originalClips.TryGetValue(name, out value)) ? instance.clip.GetName() : value.GetName());
			string key = text;
			if (SoundTool.replacedClips.Keys.Count > 0)
			{
				string[] array = SoundTool.replacedClips.Keys.ToArray();
				if (array.Length != 0)
				{
					for (int i = 0; i < array.Length; i++)
					{
						string[] array2 = array[i].Split("#");
						if (array2.Length == 2 && array2[1].Contains(((Object)((Component)instance).gameObject).name))
						{
							key = text + "#" + array2[1];
						}
					}
				}
			}
			if (SoundTool.replacedClips.ContainsKey(key))
			{
				if (!SoundTool.replacedClips[key].canPlay)
				{
					return;
				}
				if (!originalClips.ContainsKey(name))
				{
					originalClips.Add(name, instance.clip);
				}
				if (!string.IsNullOrEmpty(SoundTool.replacedClips[key].source))
				{
					flag = false;
					string[] array3 = SoundTool.replacedClips[key].source.Split(',');
					if ((Object)(object)instance != (Object)null && ((Object)((Component)instance).gameObject).name != null)
					{
						if (array3.Length > 1)
						{
							for (int j = 0; j < array3.Length; j++)
							{
								if (array3[j] == ((Object)((Component)instance).gameObject).name)
								{
									flag = true;
								}
							}
						}
						else if (array3[0] == ((Object)((Component)instance).gameObject).name)
						{
							flag = true;
						}
					}
				}
				List<RandomAudioClip> clips = SoundTool.replacedClips[key].clips;
				float num = 0f;
				foreach (RandomAudioClip item in clips)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				{
					foreach (RandomAudioClip item2 in clips)
					{
						if (num2 <= item2.chance)
						{
							if (flag)
							{
								instance.clip = item2.clip;
							}
							else if (originalClips.ContainsKey(name))
							{
								instance.clip = originalClips[name];
								originalClips.Remove(name);
							}
							break;
						}
						num2 -= item2.chance;
					}
					return;
				}
			}
			if (originalClips.ContainsKey(name))
			{
				instance.clip = originalClips[name];
				originalClips.Remove(name);
			}
		}

		private static AudioClip ReplaceClipWithNew(AudioClip original, AudioSource source = null)
		{
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			string name = original.GetName();
			bool flag = true;
			string key = name;
			if ((Object)(object)source != (Object)null && SoundTool.replacedClips.Keys.Count > 0)
			{
				string[] array = SoundTool.replacedClips.Keys.ToArray();
				if (array.Length != 0)
				{
					for (int i = 0; i < array.Length; i++)
					{
						string[] array2 = array[i].Split("#");
						if (array2.Length == 2 && array2[1].Contains(((Object)((Component)source).gameObject).name))
						{
							key = name + "#" + array2[1];
						}
					}
				}
			}
			if (SoundTool.replacedClips.ContainsKey(key))
			{
				if (!SoundTool.replacedClips[key].canPlay)
				{
					return original;
				}
				if (!originalClips.ContainsKey(key))
				{
					originalClips.Add(key, original);
				}
				if (!string.IsNullOrEmpty(SoundTool.replacedClips[key].source))
				{
					flag = false;
					string[] array3 = SoundTool.replacedClips[key].source.Split(',');
					if ((Object)(object)source != (Object)null && ((Object)((Component)source).gameObject).name != null)
					{
						if (array3.Length > 1)
						{
							for (int j = 0; j < array3.Length; j++)
							{
								if (array3[j] == ((Object)((Component)source).gameObject).name)
								{
									flag = true;
								}
							}
						}
						else if (array3[0] == ((Object)((Component)source).gameObject).name)
						{
							flag = true;
						}
					}
				}
				List<RandomAudioClip> clips = SoundTool.replacedClips[key].clips;
				float num = 0f;
				foreach (RandomAudioClip item in clips)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				foreach (RandomAudioClip item2 in clips)
				{
					if (num2 <= item2.chance)
					{
						if (flag)
						{
							return item2.clip;
						}
						if (originalClips.ContainsKey(key))
						{
							AudioClip result = originalClips[key];
							originalClips.Remove(key);
							return result;
						}
						return original;
					}
					num2 -= item2.chance;
				}
			}
			else if (originalClips.ContainsKey(key))
			{
				AudioClip result2 = originalClips[key];
				originalClips.Remove(key);
				return result2;
			}
			return original;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		public static GameObject networkPrefab;

		public static GameObject networkHandlerHost;

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		public static void Start_Patch()
		{
			if (!((Object)(object)networkPrefab != (Object)null))
			{
				SoundTool.Instance.logger.LogDebug((object)"Loading NetworkHandler prefab...");
				networkPrefab = Assets.bundle.LoadAsset<GameObject>("SoundToolNetworkHandler.prefab");
				if ((Object)(object)networkPrefab == (Object)null)
				{
					SoundTool.Instance.logger.LogError((object)"Failed to load NetworkHandler prefab!");
				}
				if ((Object)(object)networkPrefab != (Object)null)
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
					SoundTool.Instance.logger.LogDebug((object)"Registered NetworkHandler prefab!");
				}
				else
				{
					SoundTool.Instance.logger.LogWarning((object)"Failed to registered NetworkHandler prefab! No networking can take place.");
				}
			}
		}

		[HarmonyPatch("StartDisconnect")]
		[HarmonyPostfix]
		private static void StartDisconnect_Patch()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					SoundTool.Instance.logger.LogDebug((object)"Destroying NetworkHandler prefab!");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				SoundTool.Instance.logger.LogError((object)"Failed to destroy NetworkHandler prefab!");
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void SpawnNetworkHandler()
		{
			//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)
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					SoundTool.Instance.logger.LogDebug((object)"Spawning NetworkHandler prefab!");
					GameNetworkManagerPatch.networkHandlerHost = Object.Instantiate<GameObject>(GameNetworkManagerPatch.networkPrefab, Vector3.zero, Quaternion.identity);
					GameNetworkManagerPatch.networkHandlerHost.GetComponent<NetworkObject>().Spawn(true);
				}
			}
			catch
			{
				SoundTool.Instance.logger.LogError((object)"Failed to spawn NetworkHandler prefab!");
			}
		}
	}
}
namespace LCSoundTool.Networking
{
	public class NetworkHandler : NetworkBehaviour
	{
		public static NetworkHandler Instance { get; private set; }

		public static Dictionary<string, AudioClip> networkedAudioClips { get; private set; }

		public static event Action ClientNetworkedAudioChanged;

		public static event Action HostNetworkedAudioChanged;

		public override void OnNetworkSpawn()
		{
			Debug.Log((object)"LCSoundTool - NetworkHandler created!");
			NetworkHandler.ClientNetworkedAudioChanged = null;
			NetworkHandler.HostNetworkedAudioChanged = null;
			networkedAudioClips = new Dictionary<string, AudioClip>();
			Instance = this;
		}

		[ClientRpc]
		public void ReceiveAudioClipClientRpc(string clipName, byte[] audioData)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_00c6: 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_0105: 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)
			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(2736638642u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2736638642u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			if (!networkedAudioClips.ContainsKey(clipName))
			{
				AudioClip val3 = null;
				if (SoundTool.clipTypes.ContainsKey(clipName))
				{
					if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg)
					{
						val3 = OggUtility.ByteArrayToAudioClip(audioData, clipName);
					}
					else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3)
					{
						val3 = Mp3Utility.ByteArrayToAudioClip(audioData, clipName);
					}
				}
				if ((Object)(object)val3 == (Object)null)
				{
					val3 = WavUtility.ByteArrayToAudioClip(audioData, clipName);
				}
				networkedAudioClips.Add(clipName, val3);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
			else
			{
				SoundTool.Instance.logger.LogDebug((object)("Sound " + clipName + " already exists for this client! Skipping addition of this sound for this client."));
			}
		}

		[ClientRpc]
		public void RemoveAudioClipClientRpc(string clipName)
		{
			//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(1355469546u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName))
			{
				networkedAudioClips.Remove(clipName);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
		}

		[ClientRpc]
		public void SyncAudioClipsClientRpc(Strings clipNames)
		{
			//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)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3300200130u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3300200130u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			string[] myStrings = clipNames.MyStrings;
			for (int i = 0; i < myStrings.Length; i++)
			{
				if (!networkedAudioClips.ContainsKey(myStrings[i]))
				{
					SendExistingAudioClipServerRpc(myStrings[i]);
				}
			}
		}

		[ClientRpc]
		public void ReceiveSeedClientRpc(int seed)
		{
			//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(1556253924u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Random.InitState(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!");
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendAudioClipServerRpc(string clipName, byte[] audioData)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_00c6: 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_0105: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(867452943u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 867452943u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ReceiveAudioClipClientRpc(clipName, audioData);
				NetworkHandler.HostNetworkedAudioChanged?.Invoke();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void RemoveAudioClipServerRpc(string clipName)
		{
			//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3103497155u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((Ne

BepInEx/plugins/LethalLib/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.IgnoreSymbolStoreSequencePoints)]
[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("Evaisa")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Content-addition API for Lethal Company")]
[assembly: AssemblyFileVersion("0.13.2.0")]
[assembly: AssemblyInformationalVersion("0.13.2+8ac67e371acdf612b147e44f676c91232a884dad")]
[assembly: AssemblyProduct("LethalLib")]
[assembly: AssemblyTitle("LethalLib")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/EvaisaDev/LethalLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.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.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 LethalLib
{
	[BepInPlugin("evaisa.lethallib", "LethalLib", "0.13.2")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.13.2";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		private void Awake()
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0072: 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(((BaseUnityPlugin)this).Info.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_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: 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 = "0.13.2";
	}
}
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;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			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
		{
			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

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

			public int Rarity => 0;

			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)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					levelRarities.Add(levelFlags, rarity);
				}
				else if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
			}

			public ScrapItem(string id, string contentPath, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
			}
		}

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

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public StoreType storeType;

			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;

			public string infoKeywordPath;

			public int rarity;

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

			public string[] levelOverrides;

			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;

			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;

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

		public PluginInfo modInfo;

		private AssetBundle modBundle;

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

		public Dictionary<string, CustomContent> LoadedContent { get; } = new Dictionary<string, CustomContent>();


		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(customItem, 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.levelRarities, scrapItem.customLevelRarities);
				}
				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_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)
			//IL_001b: 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)
			//IL_003b: 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_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: 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 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 (dungeon.LevelTypes.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					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>();
			foreach (RandomMapObject val2 in array)
			{
				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 SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

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

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null)
			{
				this.enemy = enemy;
				this.spawnLevels = spawnLevels;
				this.spawnType = spawnType;
				if (spawnLevelOverrides != null)
				{
					foreach (string key in spawnLevelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public SpawnableEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				this.enemy = enemy;
				this.spawnType = spawnType;
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
			}
		}

		[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_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)
			//IL_001b: 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)
			//IL_003b: 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_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: 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_027a: 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_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: 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.levelRarities.ContainsKey(Levels.LevelTypes.All) || (spawnableEnemy.customLevelRarities != null && spawnableEnemy.customLevelRarities.ContainsKey(name));
					if (spawnableEnemy.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelEnum = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !spawnableEnemy.spawnLevels.HasFlag(levelEnum))
					{
						continue;
					}
					int rarity = 0;
					if (spawnableEnemy.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						rarity = spawnableEnemy.levelRarities.First((KeyValuePair<Levels.LevelTypes, int> x) => x.Key.HasFlag(levelEnum)).Value;
					}
					else if (spawnableEnemy.customLevelRarities != null && spawnableEnemy.customLevelRarities.ContainsKey(name))
					{
						rarity = spawnableEnemy.customLevelRarities[name];
					}
					SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
					{
						enemyType = spawnableEnemy.enemy,
						rarity = rarity
					};
					switch (spawnableEnemy.spawnType)
					{
					case SpawnType.Default:
						if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.Enemies.Add(item);
							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(item);
							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(item);
							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)
		{
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					spawnableEnemy.levelRarities.Add(levelFlags, rarity);
				}
				if (spawnLevelOverrides != null)
				{
					foreach (string key in spawnLevelOverrides)
					{
						spawnableEnemy.customLevelRarities.Add(key, rarity);
					}
				}
			}
			else
			{
				spawnableEnemy = new SpawnableEnemy(enemy2, rarity, levelFlags, spawnType, spawnLevelOverrides);
				spawnableEnemy.terminalNode = infoNode;
				spawnableEnemy.infoKeyword = infoKeyword;
				string name = Assembly.GetCallingAssembly().GetName().Name;
				spawnableEnemy.modName = name;
				spawnableEnemies.Add(spawnableEnemy);
			}
		}

		public static void RegisterEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						spawnableEnemy.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						spawnableEnemy.customLevelRarities.Add(customLevelRarity.Key, customLevelRarity.Value);
					}
					return;
				}
			}
			spawnableEnemy = new SpawnableEnemy(enemy2, spawnType, levelRarities, customLevelRarities);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, spawnType, levelRarities, customLevelRarities, infoNode, infoKeyword);
		}

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			EnemyType enemyType2 = enemyType;
			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 (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				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)enemyType2);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
				}
			}
		}
	}
	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 = "Unknown";

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

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				//IL_00fd: 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 obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (spawnLevelOverrides != null)
				{
					foreach (string key in spawnLevelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public ScrapItem(Item item, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				//IL_00fd: 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 obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
			}
		}

		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;

			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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//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_006e: Expected O, but got Unknown
			//IL_0083: 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: 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 void RoundManager_SpawnScrapInLevel(orig_SpawnScrapInLevel orig, RoundManager self)
		{
			orig.Invoke(self);
			Plugin.logger.LogInfo((object)("Spawnable scrap in level " + ((Object)self.currentLevel).name + ":"));
			foreach (SpawnableItemWithRarity item in self.currentLevel.spawnableScrap)
			{
				Plugin.logger.LogInfo((object)$"Item: {item.spawnableItem.itemName}, Rarity: {item.rarity}");
			}
		}

		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_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: 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_01d9: Expected O, but got Unknown
			//IL_08b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f9: Expected O, but got Unknown
			//IL_08fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0900: Unknown result type (might be due to invalid IL or missing references)
			//IL_0935: Unknown result type (might be due to invalid IL or missing references)
			//IL_093d: Expected O, but got Unknown
			//IL_09bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_09d5: Expected O, but got Unknown
			//IL_0a71: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a76: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a7e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a8b: 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.levelRarities.ContainsKey(Levels.LevelTypes.All) || (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name));
					if (scrapItem.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelEnum = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						continue;
					}
					int rarity = 0;
					if (scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						rarity = scrapItem.levelRarities.First((KeyValuePair<Levels.LevelTypes, int> x) => x.Key.HasFlag(levelEnum)).Value;
					}
					else if (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name))
					{
						rarity = scrapItem.customLevelRarities[name];
					}
					SpawnableItemWithRarity item2 = new SpawnableItemWithRarity
					{
						spawnableItem = scrapItem.item,
						rarity = rarity
					};
					if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item))
					{
						val.spawnableScrap.Add(item2);
						Plugin.logger.LogInfo((object)("Added " + ((Object)scrapItem.item).name + " to " + name));
					}
				}
			}
			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 item in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item.item.itemName) && !item.wasRemoved)
				{
					Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				item.wasRemoved = false;
				if (item.price == -1)
				{
					item.price = item.item.creditsWorth;
				}
				else
				{
					item.item.creditsWorth = item.price;
				}
				int num = -1;
				if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item.item))
				{
					list.Add(item.item);
				}
				else
				{
					num = list.IndexOf(item.item);
				}
				int buyItemIndex = ((num == -1) ? (list.Count - 1) : num);
				string itemName = item.item.itemName;
				_ = itemName[itemName.Length - 1];
				string text = itemName;
				Plugin.logger.LogInfo((object)("Adding " + itemName + " to terminal"));
				TerminalNode val4 = item.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 = item.price;
				val4.playSyncedClip = 0;
				Plugin.logger.LogInfo((object)$"Item price: {val4.itemCost}, Item index: {val4.buyItemIndex}");
				TerminalNode val5 = item.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 = item.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 = item.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 = item.item;
				buyableItemAssetInfo.keyword = val6;
				BuyableItemAssetInfo item3 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item3);
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags);
				string name = Assembly.GetCallingAssembly().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)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
				if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						scrapItem.customLevelRarities.Add(key, rarity);
					}
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags, levelOverrides);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						scrapItem.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						scrapItem.customLevelRarities.Add(customLevelRarity.Key, customLevelRarity.Value);
					}
					return;
				}
			}
			scrapItem = new ScrapItem(spawnableItem2, levelRarities, customLevelRarities);
			string name = Assembly.GetCallingAssembly().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);
			string name = Assembly.GetCallingAssembly().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);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

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

		public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item scrapItem2 = scrapItem;
			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 (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				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)scrapItem2 || (Object)(object)x.item == (Object)(object)scrapItem2);
					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)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.wasRemoved = true;
			List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = obj.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();
			val.compatibleNouns = list2.ToArray();
			obj.compatibleNouns = list3.ToArray();
		}

		public static void UpdateShopItemPrice(Item shopItem, int price)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.item.creditsWorth = price;
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			_ = obj.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = obj.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;
			}
			TerminalNode result = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword).result;
			result.itemCost = price;
			if (result.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result.terminalOptions;
			foreach (CompatibleNoun val in terminalOptions)
			{
				if ((Object)(object)val.result != (Object)null && val.result.buyItemIndex != -1)
				{
					val.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,
			Modded = 0x400,
			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_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)
			//IL_001b: 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)
			//IL_003b: 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>();
			foreach (RandomMapObject val in array)
			{
				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 (mapObject.levels.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					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)
		{
			SpawnableMapObject mapObject2 = mapObject;
			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 (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				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)mapObject2.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)
		{
			SpawnableOutsideObjectWithRarity mapObject2 = mapObject;
			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 (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				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)mapObject2.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_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)
			//IL_001b: 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 obj = PrefabUtils.CreatePrefab(name);
			obj.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name));
			obj.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(obj);
			return obj;
		}

		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_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)
			//IL_001b: 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_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_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Expected O, but got Unknown
				GameObject val = new GameObject("LethalLibGeneratedPrefabs")
				{
					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_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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				hideFlags = (HideFlags)61
			};
			val.transform.SetParent(prefabParent.transform);
			return val;
		}
	}
	public class Shaders
	{
		public static void FixShaders(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] materials = componentsInChildren[i].materials;
				foreach (Material val in materials)
				{
					if (((Object)val.shader).name.Contains("Standard"))
					{
						val.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 obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)obj).name = word;
			obj.word = word;
			obj.isVerb = isVerb;
			obj.compatibleNouns = compatibleNouns;
			obj.specialKeywordResult = specialKeywordResult;
			obj.defaultVerb = defaultVerb;
			obj.accessTerminalObjects = accessTerminalObjects;
			return obj;
		}
	}
	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;

			public bool wasAlwaysInStock;

			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 hook_RotateShipDecorSelection <2>__Terminal_RotateShipDecorSelection;
		}

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

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

		public static void Init()
		{
			//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)
			//IL_001b: 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)
			//IL_003b: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			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;
			object obj3 = <>O.<2>__Terminal_RotateShipDecorSelection;
			if (obj3 == null)
			{
				hook_RotateShipDecorSelection val3 = Terminal_RotateShipDecorSelection;
				<>O.<2>__Terminal_RotateShipDecorSelection = val3;
				obj3 = (object)val3;
			}
			Terminal.RotateShipDecorSelection += (hook_RotateShipDecorSelection)obj3;
		}

		private static void Terminal_RotateShipDecorSelection(orig_RotateShipDecorSelection orig, Terminal self)
		{
			foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables)
			{
				if (registeredUnlockable.StoreType == StoreType.Decor && registeredUnlockable.disabled)
				{
					registeredUnlockable.wasAlwaysInStock = registeredUnlockable.unlockable.alwaysInStock;
					registeredUnlockable.unlockable.alwaysInStock = true;
				}
			}
			orig.Invoke(self);
			foreach (RegisteredUnlockable registeredUnlockable2 in registeredUnlockables)
			{
				if (registeredUnlockable2.StoreType == StoreType.Decor && registeredUnlockable2.disabled)
				{
					registeredUnlockable2.unlockable.alwaysInStock = registeredUnlockable2.wasAlwaysInStock;
				}
			}
		}

		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_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_049c: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Expected O, but got Unknown
			//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_051e: Expected O, but got Unknown
			//IL_059a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b9: Expected O, but got Unknown
			//IL_0645: Unknown result type (might be due to invalid IL or missing references)
			//IL_064a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0657: Unknown result type (might be due to invalid IL or missing references)
			//IL_0664: 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 == i

BepInEx/plugins/MoreEmotes1.3.3.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.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MoreEmotesInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private NetcodeValidator netcodeValidator;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<string> config_KeyWheel_c;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<bool> config_UseConfigFile;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private ConfigEntry<string> config_KeyEmote9;

		private ConfigEntry<string> config_KeyEmote10;

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			LoadAssetBundles();
			LoadAssets();
			ConfigFile();
			SearchForIncompatibleMods();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
			netcodeValidator = new NetcodeValidator("MoreEmotes");
			netcodeValidator.PatchAll();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SignEmoteText, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SyncAnimatorToOthers, PlayerControllerB>();
		}

		private void LoadAssetBundles()
		{
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle");
			string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle");
			try
			{
				EmotePatch.AnimationsBundle = AssetBundle.LoadFromFile(text);
				EmotePatch.AnimatorBundle = AssetBundle.LoadFromFile(text2);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load AssetBundles. Make sure \"animatorsbundle\" and \"animationsbundle\" are inside the MoreEmotes folder.\nError: " + ex.Message));
			}
		}

		private void LoadAssets()
		{
			string path = "Assets/MoreEmotes";
			EmotePatch.local = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarig.controller"));
			EmotePatch.others = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarigOtherPlayers.controller"));
			MoreEmotesEvents.ClapSounds[0] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote1.wav"));
			MoreEmotesEvents.ClapSounds[1] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote2.wav"));
			EmotePatch.SettingsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesPanel.prefab"));
			EmotePatch.ButtonPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesButton.prefab"));
			EmotePatch.LegsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/plegs.prefab"));
			EmotePatch.SignPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/Sign.prefab"));
			EmotePatch.SignUIPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/SignTextUI.prefab"));
			EmotePatch.WheelPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
		}

		private void ConfigFile()
		{
			EmotePatch.ConfigFile_Keybinds = new string[32];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind = config_KeyWheel.Value;
			config_KeyWheel_c = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL (Controller)", "Key", "leftshoulder", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind_controller = config_KeyWheel_c.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.ConfigFile_InventoryCheck = config_InventoryCheck.Value;
			config_UseConfigFile = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "ConfigFile", false, "Ignores all in-game saved settings and instead uses the config file");
			EmotePatch.UseConfigFile = config_UseConfigFile.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
			config_KeyEmote9 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Prisyadka", "9", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[8] = config_KeyEmote9.Value.Replace(" ", "");
			config_KeyEmote10 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Sign", "0", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[9] = config_KeyEmote10.Value.Replace(" ", "");
		}

		private void SearchForIncompatibleMods()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				BepInPlugin metadata = pluginInfo.Value.Metadata;
				if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades", StringComparison.OrdinalIgnoreCase) || metadata.GUID.Equals("Stoneman.LethalProgression", StringComparison.OrdinalIgnoreCase))
				{
					EmotePatch.IncompatibleStuff = true;
					break;
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string GUID = "MoreEmotes";

		public const string NAME = "MoreEmotes-Sligili";

		public const string VER = "1.3.3";
	}
}
namespace MoreEmotes.Patch
{
	public enum Emotes
	{
		D_Sign = 1010,
		D_Clap = 1004,
		D_Middle_Finger = 1003,
		Dance = 1,
		Point = 2,
		Middle_Finger = 3,
		Clap = 4,
		Shy = 5,
		The_Griddy = 6,
		Twerk = 7,
		Salute = 8,
		Prisyadka = 9,
		Sign = 10
	}
	public class EmotePatch
	{
		public static AssetBundle AnimationsBundle;

		public static AssetBundle AnimatorBundle;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		public static bool UseConfigFile;

		public static string[] ConfigFile_Keybinds;

		public static string ConfigFile_WheelKeybind;

		public static string ConfigFile_WheelKeybind_controller;

		public static bool ConfigFile_InventoryCheck;

		public static string EmoteWheelKeyboard;

		public static string EmoteWheelController;

		public static bool IncompatibleStuff;

		private static int s_currentEmoteID = 0;

		private static float s_defaultPlayerSpeed;

		private static bool[] s_wasPerformingEmote = new bool[32];

		public static bool IsEmoteWheelOpen;

		private static bool s_isPlayerFirstFrame;

		private static bool s_isFirstTimeOnMenu;

		private static bool s_isPlayerSpawning;

		public const int AlternateEmoteIDOffset = 1000;

		private static int[] s_doubleEmotesIDS = new int[2] { 3, 4 };

		public static bool LocalArmsSeparatedFromCamera;

		private static Transform s_freeArmsTarget;

		private static Transform s_lockedArmsTarget;

		private static CallbackContext emptyContext;

		public static GameObject ButtonPrefab;

		public static GameObject SettingsPrefab;

		public static GameObject LegsPrefab;

		public static GameObject SignPrefab;

		public static GameObject SignUIPrefab;

		public static GameObject WheelPrefab;

		private static GameObject s_localPlayerLevelBadge;

		private static GameObject s_localPlayerBetaBadge;

		private static Transform s_legsMesh;

		private static EmoteWheel s_selectionWheel;

		private static SignUI s_customSignInputField;

		private static SyncAnimatorToOthers s_syncAnimator;

		private static int _AlternateEmoteIDOffset => 1000;

		private static void InstantiateSettingsMenu(Transform container)
		{
			RebindButton.ConfigFile_Keybinds = ConfigFile_Keybinds;
			if (!PlayerPrefs.HasKey("InvCheck") || UseConfigFile)
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ToggleButton.s_InventoryCheck = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
			SetupUI.UseConfigFile = UseConfigFile;
			SetupUI.InventoryCheck = ToggleButton.s_InventoryCheck;
			GameObject gameObject = ((Component)((Component)container).transform.Find("SettingsPanel")).gameObject;
			Object.Instantiate<GameObject>(ButtonPrefab, gameObject.transform).transform.SetSiblingIndex(7);
			Object.Instantiate<GameObject>(SettingsPrefab, gameObject.transform);
			gameObject.AddComponent<SetupUI>();
		}

		private static void CheckEmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			Emotes emotes = (Emotes)emoteID;
			string text = emotes.ToString();
			bool flag;
			if (UseConfigFile)
			{
				flag = ConfigFile_InventoryCheck;
				keyBind = ConfigFile_Keybinds[emoteID - 1];
			}
			else
			{
				flag = PlayerPrefs.GetInt("InvCheck") == 1;
				if (PlayerPrefs.HasKey(text))
				{
					keyBind = PlayerPrefs.GetString(text);
				}
				else
				{
					PlayerPrefs.SetString(text, keyBind);
				}
			}
			if (!keyBind.Equals(string.Empty) && InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && (!player.isHoldingObject || !needsEmptyHands || !flag))
			{
				player.PerformEmote(emptyContext, emoteID);
			}
		}

		private static void CheckWheelInput(string keybind, string controller, PlayerControllerB player)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			bool flag2 = false;
			if (Gamepad.all.Count != 0 && !controller.Equals(string.Empty))
			{
				flag = InputControlExtensions.IsPressed(((InputControl)Gamepad.current)[controller], 0f);
			}
			if (keybind != string.Empty)
			{
				flag2 = InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keybind], 0f) && !((ButtonControl)Keyboard.current[(Key)55]).wasPressedThisFrame;
			}
			bool flag3 = flag || flag2;
			if (flag3 && !IsEmoteWheelOpen && !player.isPlayerDead && !player.inTerminalMenu && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen)
			{
				IsEmoteWheelOpen = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
				player.disableLookInput = true;
			}
			else
			{
				if (!IsEmoteWheelOpen || (flag3 && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen))
				{
					return;
				}
				int selectedEmoteID = s_selectionWheel.SelectedEmoteID;
				if (!player.quickMenuManager.isMenuOpen && !s_customSignInputField.IsSignUIOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (!player.isPlayerDead && !player.quickMenuManager.isMenuOpen)
				{
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !ConfigFile_InventoryCheck)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
					else if (!player.isHoldingObject)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
				}
				if (!s_customSignInputField.IsSignUIOpen)
				{
					player.disableLookInput = false;
				}
				IsEmoteWheelOpen = false;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
			}
		}

		private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB player)
		{
			s_isPlayerFirstFrame = false;
			TurnControllerIntoAnOverrideController(player.playerBodyAnimator.runtimeAnimatorController);
			s_syncAnimator = ((Component)player).GetComponent<SyncAnimatorToOthers>();
			s_customSignInputField.Player = player;
			s_freeArmsTarget = Object.Instantiate<Transform>(player.localArmsRotationTarget, player.localArmsRotationTarget.parent.parent);
			s_lockedArmsTarget = player.localArmsRotationTarget;
			Transform val = ((Component)player).transform.Find("ScavengerModel").Find("metarig").Find("spine")
				.Find("spine.001")
				.Find("spine.002")
				.Find("spine.003");
			s_localPlayerLevelBadge = ((Component)val.Find("LevelSticker")).gameObject;
			s_localPlayerBetaBadge = ((Component)val.Find("BetaBadge")).gameObject;
			player.SpawnPlayerAnimation();
		}

		private static void SpawnSign(PlayerControllerB player)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(SignPrefab, ((Component)((Component)((Component)player).transform.Find("ScavengerModel")).transform.Find("metarig")).transform);
			val.transform.SetSiblingIndex(6);
			((Object)val).name = "Sign";
			val.transform.localPosition = new Vector3(0.029f, -0.45f, 1.3217f);
			val.transform.localRotation = Quaternion.Euler(65.556f, 180f, 180f);
		}

		private static void SpawnLegs(PlayerControllerB player)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(LegsPrefab, ((Component)((Component)player.playerBodyAnimator).transform.parent).transform);
			s_legsMesh = val.transform.Find("Mesh");
			((Component)s_legsMesh).transform.parent = ((Component)player.playerBodyAnimator).transform.parent;
			((Object)s_legsMesh).name = "LEGS";
			GameObject gameObject = ((Component)val.transform.Find("Armature")).gameObject;
			gameObject.transform.parent = ((Component)player.playerBodyAnimator).transform;
			((Object)gameObject).name = "FistPersonLegs";
			gameObject.transform.position = new Vector3(0f, 0.197f, 0f);
			gameObject.transform.localScale = new Vector3(13.99568f, 13.99568f, 13.99568f);
			Object.Destroy((Object)(object)val);
		}

		private static void ResetIKWeights(PlayerControllerB player)
		{
			Transform val = ((Component)player.playerBodyAnimator).transform.Find("Rig 1");
			ChainIKConstraint component = ((Component)val.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component2 = ((Component)val.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			TwoBoneIKConstraint component3 = ((Component)val.Find("RightLeg")).GetComponent<TwoBoneIKConstraint>();
			TwoBoneIKConstraint component4 = ((Component)val.Find("LeftLeg")).GetComponent<TwoBoneIKConstraint>();
			Transform val2 = ((Component)player.playerBodyAnimator).transform.Find("ScavengerModelArmsOnly").Find("metarig").Find("spine.003")
				.Find("RigArms");
			ChainIKConstraint component5 = ((Component)val2.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component6 = ((Component)val2.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component2).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)component4).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component5).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component6).weight = 1f;
		}

		private static void UpdateLegsMaterial(PlayerControllerB player)
		{
			((Renderer)((Component)s_legsMesh).GetComponent<SkinnedMeshRenderer>()).material = ((Renderer)((Component)((Component)((Component)player.playerBodyAnimator).transform.parent).transform.Find("LOD1")).gameObject.GetComponent<SkinnedMeshRenderer>()).material;
		}

		private static void TogglePlayerBadges(bool enabled)
		{
			if ((Object)(object)s_localPlayerBetaBadge != (Object)null)
			{
				((Renderer)s_localPlayerBetaBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			if ((Object)(object)s_localPlayerLevelBadge != (Object)null)
			{
				((Renderer)s_localPlayerLevelBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			else
			{
				Debug.LogError((object)"[MoreEmotes-Sligili] Couldn't find the level badge");
			}
		}

		private static bool CheckIfTooManyEmotesIsPlaying(PlayerControllerB player)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Animator playerBodyAnimator = player.playerBodyAnimator;
			AnimatorStateInfo currentAnimatorStateInfo = playerBodyAnimator.GetCurrentAnimatorStateInfo(1);
			return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Dance1") && player.performingEmote && GetAnimatorEmoteClipName(playerBodyAnimator) != "Dance1";
		}

		private static string GetAnimatorEmoteClipName(Animator animator)
		{
			AnimatorClipInfo[] currentAnimatorClipInfo = animator.GetCurrentAnimatorClipInfo(1);
			return ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name;
		}

		private static void TurnControllerIntoAnOverrideController(RuntimeAnimatorController controller)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!(controller is AnimatorOverrideController))
			{
				controller = (RuntimeAnimatorController)new AnimatorOverrideController(controller);
			}
		}

		public static void UpdateWheelKeybinds()
		{
			if (UseConfigFile)
			{
				EmoteWheelKeyboard = ConfigFile_WheelKeybind;
				EmoteWheelController = ConfigFile_WheelKeybind_controller;
				return;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel_c"))
			{
				PlayerPrefs.SetString("Emote_Wheel_c", ConfigFile_WheelKeybind_controller);
			}
			EmoteWheelController = PlayerPrefs.GetString("Emote_Wheel_c");
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", ConfigFile_WheelKeybind);
			}
			EmoteWheelKeyboard = PlayerPrefs.GetString("Emote_Wheel");
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ConfigFile_InventoryCheck = PlayerPrefs.GetInt("InvCheck") == 1;
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			D.Debug = true;
			try
			{
				InstantiateSettingsMenu(((Component)((Component)__instance).transform.parent).transform.Find("MenuContainer"));
			}
			catch (Exception ex)
			{
				if (!s_isFirstTimeOnMenu)
				{
					s_isFirstTimeOnMenu = true;
				}
				else
				{
					Debug.LogError((object)(ex.Message + "\n[MoreEmotes-Sligili] Couldn't find MenuContainer"));
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		private static void AwakePost(RoundManager __instance)
		{
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			UpdateWheelKeybinds();
			GameObject gameObject = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
			InstantiateSettingsMenu(gameObject.transform.Find("QuickMenu"));
			s_selectionWheel = Object.Instantiate<GameObject>(WheelPrefab, gameObject.transform).AddComponent<EmoteWheel>();
			s_customSignInputField = Object.Instantiate<GameObject>(SignUIPrefab, gameObject.transform).AddComponent<SignUI>();
			EmoteWheel.Keybinds = new string[ConfigFile_Keybinds.Length + 1];
			EmoteWheel.Keybinds = ConfigFile_Keybinds;
			s_isPlayerFirstFrame = true;
		}

		[HarmonyPatch(typeof(HUDManager), "EnableChat_performed")]
		[HarmonyPrefix]
		private static bool OpenChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
		[HarmonyPrefix]
		private static bool SubmitChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject.AddComponent<MoreEmotesEvents>().Player = __instance;
			s_defaultPlayerSpeed = __instance.movementSpeed;
			((Component)__instance).gameObject.AddComponent<CustomAnimationObjects>();
			SpawnSign(__instance);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				TurnControllerIntoAnOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				if (s_isPlayerFirstFrame)
				{
					SpawnLegs(__instance);
				}
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
				if (s_isPlayerFirstFrame)
				{
					OnFirstLocalPlayerFrameWithNewAnimator(__instance);
				}
				if (s_isPlayerSpawning)
				{
					__instance.SpawnPlayerAnimation();
					s_isPlayerSpawning = false;
				}
			}
			if (!IncompatibleStuff)
			{
				if ((bool)Ref.Method(__instance, "CheckConditionsForEmote") && __instance.performingEmote)
				{
					switch (s_currentEmoteID)
					{
					case 6:
						__instance.movementSpeed = s_defaultPlayerSpeed / 2f;
						break;
					case 9:
						__instance.movementSpeed = s_defaultPlayerSpeed / 3f;
						break;
					}
				}
				else
				{
					__instance.movementSpeed = s_defaultPlayerSpeed;
				}
			}
			__instance.localArmsRotationTarget = (LocalArmsSeparatedFromCamera ? (__instance.localArmsRotationTarget = s_freeArmsTarget) : (__instance.localArmsRotationTarget = s_lockedArmsTarget));
			CheckWheelInput(EmoteWheelKeyboard, EmoteWheelController, __instance);
			if (!__instance.quickMenuManager.isMenuOpen && !IsEmoteWheelOpen)
			{
				CheckEmoteInput(ConfigFile_Keybinds[2], needsEmptyHands: false, 3, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[3], needsEmptyHands: true, 4, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[4], needsEmptyHands: true, 5, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[5], needsEmptyHands: false, 6, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[6], needsEmptyHands: true, 7, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[7], needsEmptyHands: true, 8, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[8], needsEmptyHands: true, 9, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[9], needsEmptyHands: true, 10, __instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		private static void UpdatePrefix(PlayerControllerB __instance)
		{
			if (__instance.performingEmote)
			{
				s_wasPerformingEmote[__instance.playerClientId] = true;
			}
			if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId])
			{
				s_wasPerformingEmote[__instance.playerClientId] = false;
				ResetIKWeights(__instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
		[HarmonyPrefix]
		private static void OnLocalPlayerSpawn(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				s_isPlayerSpawning = true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool CheckConditionsPrefix(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			bool flag2 = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isWalking");
			if (s_currentEmoteID == 6 || s_currentEmoteID == 9)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			if (s_currentEmoteID == 10 || s_currentEmoteID == 1010)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && !flag2 && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static bool PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID < 0 || CheckIfTooManyEmotesIsPlaying(__instance)) && emoteID > 2)
			{
				return false;
			}
			if ((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer)
			{
				return false;
			}
			if (s_customSignInputField.IsSignUIOpen && emoteID != 1010)
			{
				return false;
			}
			if (emoteID > 0 && emoteID < 3 && !IsEmoteWheelOpen && !((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			int[] array = s_doubleEmotesIDS;
			foreach (int num in array)
			{
				int num2 = num + _AlternateEmoteIDOffset;
				bool flag = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
				if (emoteID == num && s_currentEmoteID == emoteID && __instance.performingEmote && (!__instance.isHoldingObject || !flag))
				{
					if (emoteID == num)
					{
						emoteID += _AlternateEmoteIDOffset;
					}
					else
					{
						emoteID -= 1000;
					}
				}
			}
			if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote)
			{
				ResetIKWeights(__instance);
			}
			if (!(bool)Ref.Method(__instance, "CheckConditionsForEmote"))
			{
				return false;
			}
			if (__instance.timeSinceStartingEmote < 0.5f)
			{
				return false;
			}
			s_currentEmoteID = emoteID;
			Action action = delegate
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.performingEmote = true;
				__instance.StartPerformingEmoteServerRpc();
				s_syncAnimator.UpdateEmoteIDForOthers(emoteID);
				TogglePlayerBadges(enabled: false);
			};
			switch (emoteID)
			{
			case 9:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					UpdateLegsMaterial(__instance);
				});
				break;
			case 10:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					((Component)s_customSignInputField).gameObject.SetActive(true);
				});
				break;
			}
			action();
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "StopPerformingEmoteServerRpc")]
		[HarmonyPostfix]
		private static void StopPerformingEmoteServerPrefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				__instance.playerBodyAnimator.SetInteger("emoteNumber", 0);
			}
			TogglePlayerBadges(enabled: true);
			s_syncAnimator.UpdateEmoteIDForOthers(0);
			s_currentEmoteID = 0;
		}
	}
}
namespace MoreEmotes.Scripts
{
	public class MoreEmotesEvents : MonoBehaviour
	{
		private Animator _playerAnimator;

		private AudioSource _playerAudioSource;

		public static AudioClip[] ClapSounds = (AudioClip[])(object)new AudioClip[2];

		public PlayerControllerB Player;

		private void Start()
		{
			_playerAnimator = ((Component)this).GetComponent<Animator>();
			_playerAudioSource = Player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if (!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 4)
				{
					bool flag = Player.isInHangarShipRoom && Player.playersManager.hangarDoorsClosed;
					RoundManager.Instance.PlayAudibleNoise(((Component)Player).transform.position, 22f, 0.6f, 0, flag, 6);
					_playerAudioSource.pitch = Random.Range(0.59f, 0.79f);
					_playerAudioSource.PlayOneShot(ClapSounds[Random.Range(0, ClapSounds.Length)]);
				}
			}
		}

		public void PlayFootstepSound()
		{
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if ((!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 6 || currentEmoteID == 8 || currentEmoteID == 9) && ((Vector2)(ref Player.moveInputVector)).sqrMagnitude == 0f)
				{
					Player.PlayFootstepLocal();
					Player.PlayFootstepServer();
				}
			}
		}

		private int GetCurrentEmoteID()
		{
			int num = _playerAnimator.GetInteger("emoteNumber");
			if (num >= 1000)
			{
				num -= 1000;
			}
			return num;
		}
	}
	public class SignEmoteText : NetworkBehaviour
	{
		private PlayerControllerB _playerInstance;

		private TextMeshPro _signModelText;

		public string Text => ((TMP_Text)_signModelText).text;

		private void Start()
		{
			_playerInstance = ((Component)this).GetComponent<PlayerControllerB>();
			_signModelText = ((Component)((Component)_playerInstance).transform.Find("ScavengerModel").Find("metarig").Find("Sign")
				.Find("Text")).GetComponent<TextMeshPro>();
		}

		public void UpdateSignText(string newText)
		{
			if (((NetworkBehaviour)_playerInstance).IsOwner && _playerInstance.isPlayerControlled)
			{
				UpdateSignTextServerRpc(newText);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateSignTextServerRpc(string newText)
		{
			UpdateSignTextClientRpc(newText);
		}

		[ClientRpc]
		private void UpdateSignTextClientRpc(string newText)
		{
			((TMP_Text)_signModelText).text = newText;
		}
	}
	public class EmoteWheel : MonoBehaviour
	{
		private RectTransform _graphics_selectedBlock;

		private RectTransform _graphics_selectionArrow;

		private Text _graphics_emoteInformation;

		private Text _graphics_pageInformation;

		private int _blocksNumber = 8;

		private int _selectedBlock = 1;

		private float _changePageCooldown = 0.1f;

		private float _selectionArrowLerpSpeed = 30f;

		private float _angle;

		private GameObject[] _pages;

		public float WheelMovementDeadzone = 3.3f;

		public float WheelMovementDeadzoneController = 0.7f;

		public static string[] Keybinds;

		private Vector2 _wheelCenter;

		private Vector2 _lastMouseCoords;

		public int SelectedPageNumber { get; private set; }

		public int SelectedEmoteID { get; private set; }

		public bool IsUsingController { get; private set; }

		private void Awake()
		{
			GetVanillaKeybinds();
			FindGraphics();
			FindPages(((Component)this).gameObject.transform.Find("FunctionalContent"));
			UpdatePageInfo();
		}

		private void OnEnable()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			_wheelCenter = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			Mouse.current.WarpCursorPosition(_wheelCenter);
		}

		private void GetVanillaKeybinds()
		{
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)" MoreEmotes: PlayerSettingsObject is null");
				return;
			}
			Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
		}

		private void FindGraphics()
		{
			_graphics_selectionArrow = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("SelectionArrow")).gameObject.GetComponent<RectTransform>();
			_graphics_selectedBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			_graphics_emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			_graphics_pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
		}

		private void FindPages(Transform contentParent)
		{
			_pages = (GameObject[])(object)new GameObject[((Component)contentParent).transform.childCount];
			_graphics_pageInformation.text = "< Page " + (SelectedPageNumber + 1) + "/" + _pages.Length + " >";
			for (int i = 0; i < ((Component)contentParent).transform.childCount; i++)
			{
				_pages[i] = ((Component)((Component)contentParent).transform.GetChild(i)).gameObject;
			}
		}

		private void Update()
		{
			ControllerInput();
			if (!IsUsingController)
			{
				MouseInput();
			}
			Cursor.visible = !IsUsingController;
			UpdateSelectionArrow();
			PageSelection();
			SelectedEmoteID = _selectedBlock + Mathf.RoundToInt((float)(_blocksNumber / 4)) + _blocksNumber * SelectedPageNumber;
			UpdateEmoteInfo();
		}

		private unsafe void ControllerInput()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (Gamepad.all.Count == 0)
			{
				IsUsingController = false;
				return;
			}
			float num = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).x).ReadUnprocessedValue();
			float num2 = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).y).ReadUnprocessedValue();
			if (Mathf.Abs(num) < WheelMovementDeadzoneController && Mathf.Abs(num2) < WheelMovementDeadzoneController)
			{
				if (System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value) != _lastMouseCoords)
				{
					IsUsingController = false;
				}
			}
			else
			{
				IsUsingController = true;
				_lastMouseCoords = System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value);
				WheelSelection(Vector2.zero, num, num2);
			}
		}

		private void MouseInput()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!(Vector2.Distance(_wheelCenter, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < WheelMovementDeadzone))
			{
				WheelSelection(_wheelCenter, ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue(), ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue());
			}
		}

		private void WheelSelection(Vector2 origin, float xAxisValue, float yAxisValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			bool flag = xAxisValue > origin.x;
			bool flag2 = yAxisValue > origin.y;
			int num = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
			float num2 = (yAxisValue - origin.y) / (xAxisValue - origin.x);
			float num3 = 180 * (num - ((num <= 2) ? 1 : 2));
			_angle = Mathf.Atan(num2) * (180f / (float)Math.PI) + num3;
			if (_angle == 90f)
			{
				_angle = 270f;
			}
			else if (_angle == 270f)
			{
				_angle = 90f;
			}
			float num4 = 360 / _blocksNumber;
			_selectedBlock = Mathf.RoundToInt((_angle - num4 * 1.5f) / num4);
			((Transform)_graphics_selectedBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num4 * (float)_selectedBlock);
		}

		private void PageSelection()
		{
			UpdatePageInfo();
			if (_changePageCooldown > 0f)
			{
				_changePageCooldown -= Time.deltaTime;
				return;
			}
			int num;
			if (IsUsingController)
			{
				if (!Gamepad.current.dpad.left.isPressed && !Gamepad.current.dpad.right.isPressed)
				{
					return;
				}
				num = (Gamepad.current.dpad.left.isPressed ? 1 : (-1));
			}
			else
			{
				if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() == 0f)
				{
					return;
				}
				num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
			}
			GameObject[] pages = _pages;
			foreach (GameObject val in pages)
			{
				val.SetActive(false);
			}
			SelectedPageNumber = (SelectedPageNumber + num + _pages.Length) % _pages.Length;
			_pages[SelectedPageNumber].SetActive(true);
			_changePageCooldown = ((!IsUsingController) ? 0.1f : 0.3f);
		}

		private void UpdatePageInfo()
		{
			_graphics_pageInformation.text = $"<color=#fe6b02><</color> Page {SelectedPageNumber + 1}/{_pages.Length} <color=#fe6b02>></color>";
		}

		private void UpdateEmoteInfo()
		{
			string text = ((SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
			int num = 0;
			foreach (Emotes value in Enum.GetValues(typeof(Emotes)))
			{
				if (value >= Emotes.Dance && value < (Emotes)64)
				{
					num++;
				}
			}
			string text2 = ((SelectedEmoteID > num) ? "EMPTY" : ((Emotes)SelectedEmoteID).ToString().Replace("_", " "));
			if (SelectedEmoteID > 2 && SelectedEmoteID <= Keybinds.Length)
			{
				if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
				{
					PlayerPrefs.SetString(text2.Replace(" ", "_"), (SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
				}
				else
				{
					text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
				}
			}
			text = "<size=120>[" + text + "]</size>";
			_graphics_emoteInformation.text = text2 + "\n" + text.ToUpper();
		}

		private void UpdateSelectionArrow()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			float num = 360 / _blocksNumber;
			Quaternion val = Quaternion.Euler(0f, 0f, _angle - num * 2f);
			((Transform)_graphics_selectionArrow).localRotation = Quaternion.Lerp(((Transform)_graphics_selectionArrow).localRotation, val, Time.deltaTime * _selectionArrowLerpSpeed);
		}
	}
	public class RebindButton : MonoBehaviour
	{
		public static string[] ConfigFile_Keybinds;

		private string _defaultKey;

		private string _playerPrefsString;

		private Transform _waitingForInput;

		private Text _keyInfo;

		public bool IsControllerButton { get; private set; } = false;


		private void Start()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			IsControllerButton = GetControllerFlag();
			_playerPrefsString = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_") + (IsControllerButton ? "_c" : "");
			_defaultKey = GetDefaultKey(text);
			FindComponents();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(_playerPrefsString))
			{
				PlayerPrefs.SetString(_playerPrefsString, _defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(_playerPrefsString));
		}

		private string GetDefaultKey(string emoteName)
		{
			if (Enum.TryParse<Emotes>(emoteName.Replace(" ", "_"), out var result))
			{
				return ConfigFile_Keybinds[(int)(result - 1)];
			}
			return IsControllerButton ? "leftshoulder" : "V";
		}

		private bool GetControllerFlag()
		{
			Transform val = ((Component)this).gameObject.transform.Find("Description").Find("Subtext");
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Text val2 = default(Text);
			if (((Component)val).TryGetComponent<Text>(ref val2))
			{
				return val2.text.Equals("(Controller)", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private void FindComponents()
		{
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteButton>();
			_keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			_waitingForInput = ((Component)this).transform.Find("wait");
		}

		public void SetKeybind(string key)
		{
			List<string> list = new List<string> { "up", "down", "left", "right" };
			if (list.Contains(key.ToLower()) && key.Length < 5)
			{
				key = "dpad/" + key;
			}
			PlayerPrefs.SetString(_playerPrefsString, key);
			_keyInfo.text = key.ToUpper();
			((MonoBehaviour)this).StopAllCoroutines();
			((Component)_waitingForInput).gameObject.SetActive(false);
		}

		private void GetKey()
		{
			((Component)_waitingForInput).gameObject.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame || (!((InputDevice)Gamepad.current).wasUpdatedThisFrame && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.leftStick, 0f) && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.rightStick, 0f)))
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback(((ctrl.device == Gamepad.current && IsControllerButton) || (ctrl.device == Keyboard.current && !IsControllerButton)) ? ctrl.name : _defaultKey);
				});
			}
		}
	}
	public class DeleteButton : MonoBehaviour
	{
		private void Start()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			RebindButton _rebindButton = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindButton>();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				_rebindButton.SetKeybind(string.Empty);
			});
		}
	}
	public class ToggleButton : MonoBehaviour
	{
		private Toggle _toggle;

		public static bool s_InventoryCheck;

		public string PlayerPrefsString;

		private void Start()
		{
			_toggle = ((Component)this).GetComponent<Toggle>();
			_toggle.isOn = s_InventoryCheck;
			((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(PlayerPrefsString))
			{
				SetNewValue(s_InventoryCheck);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(PlayerPrefsString, arg ? 1 : 0);
		}
	}
	public class EnableDisableButton : MonoBehaviour
	{
		public GameObject[] ToAlternateUI = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				GameObject[] toAlternateUI = ToAlternateUI;
				foreach (GameObject val in toAlternateUI)
				{
					val.SetActive((!val.activeInHierarchy) ? true : false);
				}
			});
			if (((Object)((Component)this).gameObject).name.Equals("BackButton", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}
	}
	public class SetupUI : MonoBehaviour
	{
		public static bool UseConfigFile;

		public static bool InventoryCheck;

		private void Awake()
		{
			Transform settingsUIPanel = ((Component)this).transform.Find("MoreEmotesPanel(Clone)");
			((Component)settingsUIPanel.Find("Version")).GetComponent<Text>().text = "1.3.3 - Sligili";
			SetupOpenSettingsButton();
			SetupBackButton();
			SetupRebindButtons(((Component)settingsUIPanel).transform.Find("KeybindButtons"));
			SetupRebindButtons(((Component)((Component)((Component)settingsUIPanel).transform.Find("Scroll View")).transform.Find("Viewport")).transform.Find("Content"));
			SetupInventoryCheckToggle();
			SetupUseConfigFileToggle();
			void SetupBackButton()
			{
				((Component)((Component)settingsUIPanel).transform.Find("BackButton")).gameObject.AddComponent<EnableDisableButton>();
			}
			void SetupInventoryCheckToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("Inv")).gameObject.AddComponent<ToggleButton>().PlayerPrefsString = "InvCheck";
			}
			void SetupOpenSettingsButton()
			{
				((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject.AddComponent<EnableDisableButton>();
			}
			static void SetupRebindButtons(Transform ButtonsParent)
			{
				Transform[] array = (Transform[])(object)new Transform[ButtonsParent.childCount];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = ButtonsParent.GetChild(i);
				}
				Transform[] array2 = array;
				foreach (Transform val in array2)
				{
					((Component)val.Find("Button")).gameObject.AddComponent<RebindButton>();
				}
			}
			void SetupUseConfigFileToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("cfg")).gameObject.GetComponent<Toggle>().isOn = UseConfigFile;
			}
		}

		private void Update()
		{
			EmotePatch.UpdateWheelKeybinds();
		}
	}
	public class SignUI : MonoBehaviour
	{
		public PlayerControllerB Player;

		private TMP_InputField _inputField;

		private Text _charactersLeftText;

		private TMP_Text _previewText;

		private Button _submitButton;

		private Button _cancelButton;

		public bool IsSignUIOpen;

		private void Awake()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			FindComponents();
			((UnityEvent)_submitButton.onClick).AddListener(new UnityAction(SubmitText));
			((UnityEvent)_cancelButton.onClick).AddListener((UnityAction)delegate
			{
				Close(cancelAction: true);
			});
			((UnityEvent<string>)(object)_inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string fieldText)
			{
				UpdatePreviewText(fieldText);
				UpdateCharactersLeftText();
			});
		}

		private void OnEnable()
		{
			Player.isTypingChat = true;
			IsSignUIOpen = true;
			((Selectable)_inputField).Select();
			_inputField.text = string.Empty;
			_previewText.text = "PREVIEW";
			Player.disableLookInput = true;
		}

		private void Update()
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)2;
			if (!Player.performingEmote)
			{
				Close(cancelAction: true);
			}
			if (((ButtonControl)Keyboard.current[(Key)2]).wasPressedThisFrame && !((ButtonControl)Keyboard.current[(Key)51]).isPressed)
			{
				SubmitText();
			}
			if (Player.quickMenuManager.isMenuOpen || EmotePatch.IsEmoteWheelOpen || InputControlExtensions.IsPressed(((InputControl)Mouse.current)["rightButton"], 0f))
			{
				Close(cancelAction: true);
			}
			if (Gamepad.all.Count != 0)
			{
				if (Gamepad.current.buttonWest.isPressed || Gamepad.current.startButton.isPressed)
				{
					SubmitText();
				}
				if (Gamepad.current.buttonEast.isPressed || Gamepad.current.selectButton.isPressed)
				{
					Close(cancelAction: true);
				}
			}
		}

		private void FindComponents()
		{
			_inputField = ((Component)((Component)this).transform.Find("InputField")).GetComponent<TMP_InputField>();
			_charactersLeftText = ((Component)((Component)this).transform.Find("CharsLeft")).GetComponent<Text>();
			_submitButton = ((Component)((Component)this).transform.Find("Submit")).GetComponent<Button>();
			_cancelButton = ((Component)((Component)this).transform.Find("Cancel")).GetComponent<Button>();
			_previewText = ((Component)((Component)((Component)this).transform.Find("Sign")).transform.Find("Text")).GetComponent<TMP_Text>();
		}

		private void UpdateCharactersLeftText()
		{
			_charactersLeftText.text = $"CHARACTERS LEFT: <color=yellow>{_inputField.characterLimit - _inputField.text.Length}</color>";
		}

		private void UpdatePreviewText(string text)
		{
			_previewText.text = text;
		}

		private void SubmitText()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (_inputField.text.Equals(string.Empty))
			{
				Close(cancelAction: true);
				return;
			}
			D.L("Submitted " + _inputField.text + " to server");
			((Component)Player).GetComponent<SignEmoteText>().UpdateSignText(_inputField.text);
			float num = 0.5f;
			if (Player.timeSinceStartingEmote > num)
			{
				Player.PerformEmote(default(CallbackContext), 1010);
			}
			Close(cancelAction: false);
		}

		private void Close(bool cancelAction)
		{
			Player.isTypingChat = false;
			IsSignUIOpen = false;
			if (cancelAction)
			{
				Player.performingEmote = false;
				Player.StopPerformingEmoteServerRpc();
			}
			if (!Player.quickMenuManager.isMenuOpen)
			{
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
			}
			Player.disableLookInput = false;
			((Component)this).gameObject.SetActive(false);
		}
	}
	public class SyncAnimatorToOthers : NetworkBehaviour
	{
		private PlayerControllerB _player;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		public void UpdateEmoteIDForOthers(int newID)
		{
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				UpdateCurrentEmoteIDServerRpc(newID);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateCurrentEmoteIDServerRpc(int newID)
		{
			UpdateCurrentEmoteIDClientRpc(newID);
		}

		[ClientRpc]
		private void UpdateCurrentEmoteIDClientRpc(int newID)
		{
			if (!((NetworkBehaviour)_player).IsOwner)
			{
				_player.playerBodyAnimator.SetInteger("emoteNumber", newID);
			}
		}
	}
	public class CustomAnimationObjects : MonoBehaviour
	{
		private PlayerControllerB _player;

		private MeshRenderer _sign;

		private GameObject _signText;

		private SkinnedMeshRenderer _legs;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		private void Update()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sign == (Object)null || (Object)(object)_signText == (Object)null)
			{
				FindSign();
				return;
			}
			((Component)_sign).transform.localPosition = ((Component)_sign).transform.parent.Find("spine").localPosition;
			if ((Object)(object)_legs == (Object)null && ((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				FindLegs();
				return;
			}
			DisableEverything();
			if (!_player.performingEmote)
			{
				return;
			}
			switch (_player.playerBodyAnimator.GetInteger("emoteNumber"))
			{
			case 10:
			case 1010:
				((Renderer)_sign).enabled = true;
				if (!_signText.activeSelf)
				{
					_signText.SetActive(true);
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			case 9:
				if ((Object)(object)_legs != (Object)null)
				{
					((Renderer)_legs).enabled = true;
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			}
		}

		private void DisableEverything()
		{
			if ((Object)(object)_legs != (Object)null)
			{
				((Renderer)_legs).enabled = false;
			}
			((Renderer)_sign).enabled = false;
			if (_signText.activeSelf)
			{
				_signText.SetActive(false);
			}
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				EmotePatch.LocalArmsSeparatedFromCamera = false;
			}
		}

		private void FindSign()
		{
			_sign = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("metarig").Find("Sign")).GetComponent<MeshRenderer>();
			_signText = ((Component)((Component)_sign).transform.Find("Text")).gameObject;
		}

		private void FindLegs()
		{
			_legs = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("LEGS")).GetComponent<SkinnedMeshRenderer>();
		}
	}
}

BepInEx/plugins/MoreItems.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 BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreItems.Patches;

[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("MoreItems")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("MoreItems")]
[assembly: AssemblyTitle("MoreItems")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.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 MoreItems
{
	[BepInPlugin("MoreItems", "MoreItems", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("MoreItems");

		private void Awake()
		{
			try
			{
				harmony.PatchAll(typeof(GameNetworkManagerPatch));
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreItems is loaded!");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin MoreItems failed to load and threw an exception:\n" + ex.Message));
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MoreItems";

		public const string PLUGIN_NAME = "MoreItems";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}
namespace MoreItems.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		private const int newMaxItemCapacity = 999;

		[HarmonyPatch("SaveItemsInShip")]
		[HarmonyPrefix]
		private static void IncreaseShipItemCapacity()
		{
			StartOfRound.Instance.maxShipItemCapacity = 999;
			Logger.CreateLogSource("MoreItems").LogInfo((object)$"Maximum amount of items that can be saved set to {999} just before saving.");
		}
	}
}

BepInEx/plugins/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;
	}
}

BepInEx/plugins/NeedyCats.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.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using Unity.Netcode.Samples;
using UnityEngine;
using UnityEngine.AI;

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

		public AudioSource audioSource;

		public SkinnedMeshRenderer skinnedMeshRenderer;

		[Space(3f)]
		public Vector2 IntervalMeow;

		public Vector2 IntervalMove;

		public Vector2 IntervalSitAnimChange;

		public Vector2 IntervalIdleAnimChange;

		public float WalkingSpeed = 1f;

		public float RunningSpeed = 8f;

		private (int, float)[] placeableMeowInterval;

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

		private float timeBeforeNextMove = 1f;

		private float timeBeforeNextMeow = 1f;

		private float timeBeforeNextSitAnim = 1f;

		private int sitAnimationsLength = 3;

		private float timeBeforeNextIdleAnim = 1f;

		private int idleAnimationsLength = 4;

		private bool isSitting;

		private int materialIndex;

		private int nameIndex;

		private bool hasLoadedSave;

		private HoarderBugItem hoarderBugItem;

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

		public AudioClip[] fleeSFX;

		public AudioClip[] calmSFX;

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

		public float maxLoudness = 1f;

		public float minLoudness = 0.95f;

		public float minPitch = 0.9f;

		public float maxPitch = 1f;

		private NavMeshAgent agent;

		private Random random;

		[Space(3f)]
		public Vector3 destination;

		private GameObject[] allAINodes;

		private NavMeshPath navmeshPath;

		private float velX;

		private float velY;

		private Vector3 previousPosition;

		private Vector3 agentLocalVelocity;

		private ClientNetworkTransform clientNetworkTransform;

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

		public void Awake()
		{
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public void SetRandomDestination()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)this).transform.position + Random.insideUnitSphere * 5f;
			agent.speed = WalkingSpeed;
			SetDestinationToPosition(position);
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			public static AssetBundle MainAssetBundle = null;

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

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

		private const string modGUID = "Jordo.NeedyCats";

		private const string modName = "Needy Cats";

		private const string modVersion = "1.1.1";

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

		public static NeedyCatsBase Instance;

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

		private static ConfigEntry<int> spawnRate;

		private static ConfigEntry<string> catNamesConfig;

		internal static ManualLogSource mls;

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

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

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

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

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

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

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

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

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

BepInEx/plugins/Peter.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 LC_API.BundleAPI;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Peter")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c25405c516fddcff690faa70c67b9176ec8d70ca")]
[assembly: AssemblyProduct("Peter")]
[assembly: AssemblyTitle("Peter")]
[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 Peter
{
	[BepInPlugin("Peter", "Peter", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public Harmony harmonymain;

		private void Awake()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmonymain = new Harmony("Peter");
			harmonymain.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"peter loaded.");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "Peter";

		public const string PLUGIN_NAME = "Peter";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace Peter.Patches
{
	[HarmonyPatch]
	internal class EnemyTypes
	{
		[HarmonyPatch(typeof(RoundManager), "BeginEnemySpawning")]
		[HarmonyPostfix]
		public static void SummonPeter(RoundManager __instance)
		{
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			foreach (SpawnableEnemyWithRarity enemy in RoundManager.Instance.currentLevel.Enemies)
			{
				if ((Object)(object)enemy.enemyType != (Object)null && enemy.enemyType.enemyName == "Spring")
				{
					SpringManAI component = enemy.enemyType.enemyPrefab.GetComponent<SpringManAI>();
					if (!((Object)(object)((Component)component).gameObject.transform.Find("SpringManModel") != (Object)null) || !((Object)(object)((Component)component).gameObject.transform.Find("SpringManModel").Find("Body") != (Object)null) || !((Object)(object)((Component)((Component)component).gameObject.transform.Find("SpringManModel").Find("Body")).gameObject != (Object)null) || !((Object)(object)((Component)((Component)component).gameObject.transform.Find("SpringManModel").Find("Body")).gameObject.GetComponent<SkinnedMeshRenderer>() != (Object)null))
					{
						break;
					}
					component.springNoises = (AudioClip[])(object)new AudioClip[1] { BundleLoader.GetLoadedAsset<AudioClip>("assets/peter/peter-hehehe.mp3") };
					Object.Destroy((Object)(object)((Component)((Component)component).gameObject.transform.Find("SpringManModel").Find("Body")).gameObject.GetComponent<SkinnedMeshRenderer>());
					Object.Destroy((Object)(object)((Component)((Component)component).gameObject.transform.Find("SpringManModel").Find("Head")).gameObject.GetComponent<MeshRenderer>());
					GameObject val = Object.Instantiate<GameObject>(BundleLoader.GetLoadedAsset<GameObject>("assets/peter/default.prefab"));
					Debug.Log((object)"SPAWNED PETER AEAEAEE");
					val.transform.SetParent(enemy.enemyType.enemyPrefab.transform, false);
					val.transform.localPosition = new Vector3(0f, 2.2f, 0f);
				}
			}
		}
	}
}

BepInEx/plugins/ShipLoot/ShipLoot.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 BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ShipLoot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("ShipLoot")]
[assembly: AssemblyCopyright("Copyright © tinyhoot 2023")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ShipLoot
{
	[BepInPlugin("com.github.tinyhoot.ShipLoot", "ShipLoot", "1.0")]
	internal class ShipLoot : BaseUnityPlugin
	{
		public const string GUID = "com.github.tinyhoot.ShipLoot";

		public const string NAME = "ShipLoot";

		public const string VERSION = "1.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			new Harmony("com.github.tinyhoot.ShipLoot").PatchAll(Assembly.GetExecutingAssembly());
		}
	}
}
namespace ShipLoot.Patches
{
	[HarmonyPatch]
	internal class HudManagerPatcher
	{
		private static GameObject _totalCounter;

		private static TextMeshProUGUI _textMesh;

		private static float _displayTimeLeft;

		private const float DisplayTime = 5f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		private static void OnScan(HUDManager __instance, CallbackContext context)
		{
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && __instance.CanPlayerScan() && !(__instance.playerPingingScan > -0.5f) && (StartOfRound.Instance.inShipPhase || GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom))
			{
				if (!Object.op_Implicit((Object)(object)_totalCounter))
				{
					CopyValueCounter();
				}
				float num = CalculateLootValue();
				((TMP_Text)_textMesh).text = $"SHIP: ${num:F0}";
				_displayTimeLeft = 5f;
				if (!_totalCounter.activeSelf)
				{
					((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(ShipLootCoroutine());
				}
			}
		}

		private static IEnumerator ShipLootCoroutine()
		{
			_totalCounter.SetActive(true);
			while (_displayTimeLeft > 0f)
			{
				float displayTimeLeft = _displayTimeLeft;
				_displayTimeLeft = 0f;
				yield return (object)new WaitForSeconds(displayTimeLeft);
			}
			_totalCounter.SetActive(false);
		}

		private static float CalculateLootValue()
		{
			List<GrabbableObject> list = (from obj in GameObject.Find("/Environment/HangarShip").GetComponentsInChildren<GrabbableObject>()
				where ((Object)obj).name != "ClipboardManual" && ((Object)obj).name != "StickyNoteItem"
				select obj).ToList();
			ShipLoot.Log.LogDebug((object)"Calculating total ship scrap value.");
			CollectionExtensions.Do<GrabbableObject>((IEnumerable<GrabbableObject>)list, (Action<GrabbableObject>)delegate(GrabbableObject scrap)
			{
				ShipLoot.Log.LogDebug((object)$"{((Object)scrap).name} - ${scrap.scrapValue}");
			});
			return list.Sum((GrabbableObject scrap) => scrap.scrapValue);
		}

		private static void CopyValueCounter()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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_008d: 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))
			{
				ShipLoot.Log.LogError((object)"Failed to find ValueCounter object to copy!");
			}
			_totalCounter = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent, false);
			_totalCounter.transform.Translate(0f, 1f, 0f);
			Vector3 localPosition = _totalCounter.transform.localPosition;
			_totalCounter.transform.localPosition = new Vector3(localPosition.x + 50f, -50f, localPosition.z);
			_textMesh = _totalCounter.GetComponentInChildren<TextMeshProUGUI>();
		}
	}
}

BepInEx/plugins/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[6]
		{
			new Logo
			{
				fileName = "Teo",
				playerNames = new string[9] { "SAMMY", "paddy", "Ozias", "Teo", "Rugbug Redfern", "WuluKing", "Boolie", "TeaEditor", "FlashGamesNemesis" }
			},
			new Logo
			{
				fileName = "OfflineTV",
				playerNames = new string[3] { "Masayoshi", "QUARTERJADE", "DisguisedToast" }
			},
			new Logo
			{
				fileName = "Neuro",
				playerNames = new string[1] { "vedal" }
			},
			new Logo
			{
				fileName = "Mogul",
				playerNames = new string[2] { "ludwig", "AirCoots" }
			},
			new Logo
			{
				fileName = "Imp",
				playerNames = new string[1] { "camila" }
			},
			new Logo
			{
				fileName = "Iron",
				playerNames = new string[1] { "ironmouse" }
			}
		};

		private Image cachedHeader;

		private Image cachedLogoHeader;

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

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

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

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

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

		private const string modGUID = "RugbugRedfern.SkinwalkerMod";

		private const string modVersion = "2.0.7";

		private static bool initialized;

		public static PluginLoader Instance { get; private set; }

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

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

		public const float PLAY_INTERVAL_MIN = 15f;

		public const float PLAY_INTERVAL_MAX = 40f;

		private const float MAX_DIST = 100f;

		private float nextTimeToPlayAudio;

		private EnemyAI ai;

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

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

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

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

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

		public static ConfigEntry<bool> VoiceEnabled_Bracken;

		public static ConfigEntry<bool> VoiceEnabled_BunkerSpider;

		public static ConfigEntry<bool> VoiceEnabled_Centipede;

		public static ConfigEntry<bool> VoiceEnabled_CoilHead;

		public static ConfigEntry<bool> VoiceEnabled_EyelessDog;

		public static ConfigEntry<bool> VoiceEnabled_ForestGiant;

		public static ConfigEntry<bool> VoiceEnabled_GhostGirl;

		public static ConfigEntry<bool> VoiceEnabled_GiantWorm;

		public static ConfigEntry<bool> VoiceEnabled_HoardingBug;

		public static ConfigEntry<bool> VoiceEnabled_Hygrodere;

		public static ConfigEntry<bool> VoiceEnabled_Jester;

		public static ConfigEntry<bool> VoiceEnabled_Masked;

		public static ConfigEntry<bool> VoiceEnabled_Nutcracker;

		public static ConfigEntry<bool> VoiceEnabled_SporeLizard;

		public static ConfigEntry<bool> VoiceEnabled_Thumper;

		public static ConfigEntry<bool> VoiceEnabled_OtherEnemies;

		public static ConfigEntry<float> VoiceLineFrequency;

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

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

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

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

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

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

		private float nextTimeToCheckFolder = 30f;

		private float nextTimeToCheckEnemies = 30f;

		private const float folderScanInterval = 8f;

		private const float enemyScanInterval = 5f;

		public static SkinwalkerModPersistent Instance { get; private set; }

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

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

		private void OnApplicationQuit()
		{
			DisableRecording();
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public static SkinwalkerNetworkManager Instance { get; private set; }

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

		public override void OnDestroy()
		{
			((NetworkBehaviour)this).OnDestroy();
			SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy");
			SkinwalkerModPersistent.Instance?.ClearCache();
		}

		protected override void __initializeVariables()
		{
			if (VoiceEnabled_BaboonHawk == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk);
			if (VoiceEnabled_Bracken == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken);
			if (VoiceEnabled_BunkerSpider == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider);
			if (VoiceEnabled_Centipede == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede);
			if (VoiceEnabled_CoilHead == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead);
			if (VoiceEnabled_EyelessDog == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog);
			if (VoiceEnabled_ForestGiant == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant);
			if (VoiceEnabled_GhostGirl == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl);
			if (VoiceEnabled_GiantWorm == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm);
			if (VoiceEnabled_HoardingBug == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug);
			if (VoiceEnabled_Hygrodere == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere);
			if (VoiceEnabled_Jester == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester);
			if (VoiceEnabled_Masked == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked);
			if (VoiceEnabled_Nutcracker == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker);
			if (VoiceEnabled_SporeLizard == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard);
			if (VoiceEnabled_Thumper == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper);
			if (VoiceEnabled_OtherEnemies == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_OtherEnemies cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_OtherEnemies).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies, "VoiceEnabled_OtherEnemies");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies);
			if (VoiceLineFrequency == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency);
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected internal override string __getTypeName()
		{
			return "SkinwalkerNetworkManager";
		}
	}
}
namespace SkinwalkerMod.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

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

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

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

		internal Resources()
		{
		}
	}
}

BuyableShotgun.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 LethalLib.Modules;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("BuyableShotgun")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+de03bd2735d14ec5e61f253b6602806c4ce89ece")]
[assembly: AssemblyProduct("BuyableShotgun")]
[assembly: AssemblyTitle("BuyableShotgun")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BuyableShotgun
{
	[BepInPlugin("MegaPiggy.BuyableShotgun", "BuyableShotgun", "1.0.1")]
	public class BuyableShotgun : BaseUnityPlugin
	{
		private const string modGUID = "MegaPiggy.BuyableShotgun";

		private const string modName = "BuyableShotgun";

		private const string modVersion = "1.0.1";

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

		private static BuyableShotgun Instance;

		private ConfigEntry<int> ShotgunPriceConfig;

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

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

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

		public Item ShotgunClone { get; private set; }

		public int ShotgunPrice => ShotgunPriceConfig.Value;

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

		private Item MakeNonScrap(Item original, int price)
		{
			Item val = Object.Instantiate<Item>(original);
			((Object)val).name = "Buyable" + ((Object)original).name;
			val.isScrap = false;
			val.creditsWorth = price;
			return val;
		}

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

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

FreeJester/FreeJester.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 FreeJester.Patches;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FreeJester")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreeJester")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("cb752f14-68ca-44e9-836b-f8a323fbbf36")]
[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 FreeJester
{
	[BepInPlugin("atg.FreeJester", "Free Jester", "1.0.3")]
	public class FreeJesterBase : BaseUnityPlugin
	{
		private const string modGUID = "atg.FreeJester";

		private const string modName = "Free Jester";

		private const string modVersion = "1.0.3";

		private Harmony harmony = new Harmony("atg.FreeJester");

		private static FreeJesterBase Instance;

		internal ManualLogSource mls;

		internal static AudioClip[] newSFX;

		private void Awake()
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("atg.FreeJester");
			mls.LogInfo((object)"Starting Free Jester :D");
			mls.LogInfo((object)(((BaseUnityPlugin)Instance).Info.Location.TrimEnd("FreeJester.dll".ToCharArray()) + "freebird"));
			AssetBundle val = AssetBundle.LoadFromFile(((BaseUnityPlugin)Instance).Info.Location.TrimEnd("FreeJester.dll".ToCharArray()) + "freebird");
			if ((Object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load audio assets!");
				return;
			}
			newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/freebird.mp3");
			harmony.PatchAll(typeof(JesterAIPatch));
			mls.LogInfo((object)"Free Jester is loaded");
			harmony.PatchAll(typeof(FreeJesterBase));
		}
	}
}
namespace FreeJester.Patches
{
	[HarmonyPatch(typeof(JesterAI))]
	internal class JesterAIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		public static void FreeJesterPatch(ref AudioClip ___popGoesTheWeaselTheme)
		{
			AudioClip[] newSFX = FreeJesterBase.newSFX;
			if (newSFX != null && newSFX.Length != 0)
			{
				AudioClip val = newSFX[0];
				___popGoesTheWeaselTheme = val;
			}
		}
	}
}

HornMoan.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.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("HornMoan")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("HornMoan")]
[assembly: AssemblyTitle("HornMoan")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace HornMoan
{
	[BepInPlugin("MetalPipeSFX.HornMoan", "HornMoan", "2.1.0")]
	public class HornMoanBase : BaseUnityPlugin
	{
		private const string modGUID = "MetalPipeSFX.HornMoan";

		private const string modName = "HornMoan";

		private const string modVersion = "2.1.0";

		private static HornMoanBase Instance;

		private readonly Harmony harmony = new Harmony("MetalPipeSFX.HornMoan");

		internal ManualLogSource mls = null;

		public void Awake()
		{
			mls = Logger.CreateLogSource("MetalPipeSFX.HornMoan");
			mls.LogInfo((object)"The Moaning is Loading");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			mls.LogInfo((object)"Loaded The Moaning Successfully");
		}
	}
	[HarmonyPatch(typeof(GrabbableObject))]
	internal class PipePatch
	{
		private static List<string> audios = new List<string> { "Moaning1.mp3", "MoaningFar.mp3" };

		private static List<AudioClip> clips = new List<AudioClip>();

		private static string uPath = Path.Combine(Paths.PluginPath + "\\MetalPipeSFX-HornMoan\\");

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void AudioPatch(GrabbableObject __instance)
		{
			ManualLogSource val = Logger.CreateLogSource("MetalPipeSFX.HornMoan");
			for (int i = 0; i < audios.Count; i++)
			{
				LoadAudioClip(uPath + audios[i]);
			}
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).GetComponent<NoisemakerProp>() != (Object)null && ((Object)__instance.itemProperties).name == "Airhorn")
			{
				val.LogMessage((object)"We found an Airhorn!!");
				((Component)__instance).GetComponent<NoisemakerProp>().noiseSFX[0] = clips[0];
				((Component)__instance).GetComponent<NoisemakerProp>().noiseSFXFar[0] = clips[1];
				val.LogMessage((object)((Object)((Component)__instance).GetComponent<NoisemakerProp>().noiseSFX[0]).name);
				val.LogMessage((object)((Object)((Component)__instance).GetComponent<NoisemakerProp>().noiseSFXFar[0]).name);
			}
		}

		private static void LoadAudioClip(string filepath)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Invalid comparison between Unknown and I4
			ManualLogSource val = Logger.CreateLogSource("MetalPipeSFX.HornMoan");
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(filepath, (AudioType)13);
			audioClip.SendWebRequest();
			while (!audioClip.isDone)
			{
			}
			if (audioClip.error != null)
			{
				val.LogError((object)("Error loading sounds: " + filepath + "\n" + audioClip.error));
			}
			AudioClip content = DownloadHandlerAudioClip.GetContent(audioClip);
			if (Object.op_Implicit((Object)(object)content) && (int)content.loadState == 2)
			{
				val.LogInfo((object)("Loaded " + filepath));
				((Object)content).name = Path.GetFileName(filepath);
				clips.Add(content);
			}
		}
	}
}

PlayerBracken.dll

Decompiled 10 months ago
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 GameNetcodeStuff;
using HarmonyLib;
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: AssemblyTitle("PlayerBracken")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlayerBracken")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e509da5c-cf1d-4920-88e7-e6e88e8a0faa")]
[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 PlayerBracken
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "PlayerBracken";

		public const string PLUGIN_NAME = "PlayerBracken";

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

		public static ConfigEntry<bool> showPlayerNameText;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin PlayerBracken is loaded!");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "playerbracken.bundle");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			Visuals = val.LoadAsset<GameObject>("assets/raecomission/animcontainer.prefab");
			showPlayerNameText = ((BaseUnityPlugin)this).Config.Bind<bool>("PlayerBracken", "ShowPlayerNameText", true, "Enable/Disable whether the player name should appear above the fake Player. This will pick a random player in the server for the name.");
			Renderer[] componentsInChildren = Visuals.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren)
			{
				((Component)val2).gameObject.layer = LayerMask.NameToLayer("Enemies");
			}
		}
	}
}
namespace PlayerBracken.Patches
{
	[HarmonyPatch(typeof(FlowermanAI), "Start")]
	internal class FlowermanPatch
	{
		private static void Postfix(FlowermanAI __instance)
		{
			//IL_00d7: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Plugin.Visuals == (Object)null)
			{
				return;
			}
			Transform val = ((Component)__instance).transform.Find("FlowermanModel");
			object obj;
			if (val == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val.Find("LOD1");
				obj = ((obj2 != null) ? ((Component)obj2).GetComponent<SkinnedMeshRenderer>() : null);
			}
			SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)obj;
			object obj3;
			if (val == null)
			{
				obj3 = null;
			}
			else
			{
				Transform obj4 = val.Find("AnimContainer");
				obj3 = ((obj4 != null) ? obj4.Find("metarig") : null);
			}
			Transform val3 = (Transform)obj3;
			if ((Object)(object)val2 == (Object)null || !((Renderer)val2).enabled)
			{
				return;
			}
			((Renderer)val2).enabled = false;
			Renderer[] componentsInChildren = ((Component)val3).gameObject.GetComponentsInChildren<Renderer>();
			foreach (Renderer val4 in componentsInChildren)
			{
				val4.enabled = false;
			}
			GameObject val5 = Object.Instantiate<GameObject>(Plugin.Visuals, val);
			val5.transform.localPosition = Vector3.zero;
			val5.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
			val5.transform.localScale = new Vector3(5.85875f, 5.85875f, 5.85875f);
			Transform val6 = val5.transform.Find("metarig");
			((EnemyAI)__instance).creatureAnimator = ((Component)val6).GetComponent<Animator>();
			__instance.rightHandGrip = val6.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003")
				.Find("shoulder.R")
				.Find("arm.R_upper")
				.Find("arm.R_lower")
				.Find("hand.R")
				.Find("HandGripPosition");
			TextMeshProUGUI component = ((Component)val5.transform.Find("PlayerUsernameCanvas").Find("Text (TMP)")).GetComponent<TextMeshProUGUI>();
			if (Plugin.showPlayerNameText.Value)
			{
				string[] array = StartOfRound.Instance.allPlayerScripts.Select((PlayerControllerB x) => x.playerUsername).ToArray();
				int num = Random.Range(0, array.Length - 1);
				((Component)component).gameObject.SetActive(true);
				((TMP_Text)component).text = array[num];
			}
			else
			{
				((Component)component).gameObject.SetActive(false);
			}
		}
	}
}

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.6.0")]
	[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 void LogWarning(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogWarning((object)message);
		}

		public static void LogError(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogError((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.5";
	}
}
namespace ReservedWalkieSlot.Input
{
	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;
	}
	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;
		}
	}
	[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 = WalkiePatcher.GetMainWalkie(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainWalkie == (Object)null) && ((GrabbableObject)mainWalkie).isBeingUsed && !ShipBuildModeManager.Instance.InBuildMode)
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					Plugin.Log("Speaking into walkie");
					((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 = WalkiePatcher.GetMainWalkie(localPlayerController);
				if (((CallbackContext)(ref context)).canceled && !((Object)(object)mainWalkie == (Object)null))
				{
					Plugin.Log("Not talking into walkie");
					((GrabbableObject)mainWalkie).UseItemOnClient(false);
				}
			}
		}
	}
}
namespace ReservedWalkieSlot.Patches
{
	[HarmonyPatch]
	public class MaskedEnemyPatcher
	{
		public static Dictionary<MaskedPlayerEnemy, GameObject> heldWalkiesByEnemy = new Dictionary<MaskedPlayerEnemy, GameObject>();

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

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

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "LateUpdate")]
		[HarmonyPostfix]
		public static void ShowWalkieOnEnemy(MaskedPlayerEnemy __instance)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: 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)
			//IL_00e8: 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_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			if (!spawnedEnemies.Contains(__instance) && SyncManager.syncReservedItemsList.Contains(Plugin.walkieInfo) && !heldWalkiesByEnemy.ContainsKey(__instance) && (Object)(object)__instance.mimickingPlayer != (Object)null && PlayerPatcher.allPlayerData.TryGetValue(__instance.mimickingPlayer, out var value))
			{
				spawnedEnemies.Add(__instance);
				WalkieTalkie reservedWalkie = WalkiePatcher.GetReservedWalkie(value.playerController);
				if ((Object)(object)reservedWalkie != (Object)null)
				{
					Plugin.LogWarning("OnMaskedEnemySpawn - MimickingPlayer: " + ((Object)value.playerController).name + " - Spawning walkie object on enemy.");
					GameObject val = new GameObject("ReservedWalkie [MaskedEnemy]");
					Light[] componentsInChildren = ((Component)reservedWalkie).GetComponentsInChildren<Light>();
					MeshRenderer mainObjectRenderer = ((GrabbableObject)reservedWalkie).mainObjectRenderer;
					Light[] array = componentsInChildren;
					foreach (Light val2 in array)
					{
						Light component = Object.Instantiate<GameObject>(((Component)val2).gameObject, ((Component)val2).transform.localPosition, ((Component)val2).transform.localRotation, val.transform).GetComponent<Light>();
						((Behaviour)component).enabled = true;
						((Component)component).gameObject.layer = 6;
					}
					MeshRenderer component2 = Object.Instantiate<GameObject>(((Component)mainObjectRenderer).gameObject, ((Component)mainObjectRenderer).transform.localPosition, ((Component)mainObjectRenderer).transform.localRotation, val.transform).GetComponent<MeshRenderer>();
					((Renderer)component2).enabled = true;
					((Component)component2).gameObject.layer = 6;
					val.transform.localScale = ((Component)reservedWalkie).transform.localScale;
					heldWalkiesByEnemy.Add(__instance, val);
				}
			}
			if (heldWalkiesByEnemy.TryGetValue(__instance, out var value2))
			{
				if (((EnemyAI)__instance).isEnemyDead)
				{
					Plugin.LogWarning("Destroying walkie. Enemy dead.");
					Object.DestroyImmediate((Object)(object)value2);
					spawnedEnemies.Remove(__instance);
					heldWalkiesByEnemy.Remove(__instance);
				}
				else
				{
					Transform parent = ((EnemyAI)__instance).eye.parent.parent;
					value2.transform.rotation = parent.rotation * Quaternion.Euler(WalkiePatcher.playerShoulderRotationOffset);
					value2.transform.position = parent.position + parent.rotation * WalkiePatcher.playerShoulderPositionOffset;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ShipBuildModeManager), "PlayerMeetsConditionsToBuild")]
	public class PlayerMeetsConditionsToBuildPatcher
	{
		private static bool activatingWalkie;

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

		public static void Prefix(ShipBuildModeManager __instance)
		{
			if (!((Object)(object)localPlayerController == (Object)null))
			{
				activatingWalkie = localPlayerController.activatingItem;
				WalkieTalkie mainWalkie = WalkiePatcher.GetMainWalkie(localPlayerController);
				if (!((Object)(object)mainWalkie == (Object)null) && !((Object)(object)((GrabbableObject)mainWalkie).playerHeldBy == (Object)null) && !((Object)(object)((GrabbableObject)mainWalkie).playerHeldBy != (Object)(object)localPlayerController) && localPlayerController.activatingItem && mainWalkie.speakingIntoWalkieTalkie)
				{
					localPlayerController.activatingItem = false;
				}
			}
		}

		public static void Postfix(ShipBuildModeManager __instance)
		{
			if (!((Object)(object)localPlayerController == (Object)null))
			{
				localPlayerController.activatingItem = activatingWalkie;
			}
		}
	}
	[HarmonyPatch]
	public static class WalkiePatcher
	{
		public static Vector3 localPlayerShoulderPositionOffset = new Vector3(0.125f, 0.4f, 0.125f);

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

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

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

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

		public static WalkieTalkie GetReservedWalkie(PlayerControllerB playerController)
		{
			ReservedPlayerData value;
			return (WalkieTalkie)((SyncManager.syncReservedItemsList.Contains(Plugin.walkieInfo) && PlayerPatcher.allPlayerData.TryGetValue(playerController, out value)) ? /*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)
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? 23 : 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)
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = 6;
				}
			}
			((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder);
		}

		[HarmonyPatch(typeof(WalkieTalkie), "DiscardItem")]
		[HarmonyPostfix]
		public static void OnDiscardWalkie(WalkieTalkie __instance)
		{
			Renderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				if (!((Object)val).name.Contains("ScanNode") && !((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger"))
				{
					((Component)val).gameObject.layer = 6;
				}
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
		[HarmonyPostfix]
		public static void SetPositionOffset(GrabbableObject __instance)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			if (__instance is 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 && !ReservedItemPatcher.ReservedItemIsBeingGrabbed(__instance))
			{
				enable = true;
			}
		}
	}
}

YippeeMod.dll

Decompiled 10 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using YippeeMod.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("YippeeMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("YippeeMod")]
[assembly: AssemblyTitle("YippeeMod")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace YippeeMod
{
	[BepInPlugin("sunnobunno.YippeeMod", "Yippee tbh mod", "1.2.3")]
	public class YippeeModBase : BaseUnityPlugin
	{
		private const string modGUID = "sunnobunno.YippeeMod";

		private const string modName = "Yippee tbh mod";

		private const string modVersion = "1.2.3";

		private readonly Harmony harmony = new Harmony("sunnobunno.YippeeMod");

		private static YippeeModBase? Instance;

		internal ManualLogSource? mls;

		internal static AudioClip[]? newSFX;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("sunnobunno.YippeeMod");
			mls.LogInfo((object)"sunnobunno.YippeeMod is loading.");
			string location = ((BaseUnityPlugin)Instance).Info.Location;
			string text = "YippeeMod.dll";
			string text2 = location.TrimEnd(text.ToCharArray());
			string text3 = text2 + "yippeesound";
			AssetBundle val = AssetBundle.LoadFromFile(text3);
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load audio assets!");
				return;
			}
			newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/yippee-tbh.mp3");
			harmony.PatchAll(typeof(HoarderBugPatch));
			mls.LogInfo((object)"sunnobunno.YippeeMod is loaded. Yippee!!!");
		}
	}
}
namespace YippeeMod.Patches
{
	[HarmonyPatch(typeof(HoarderBugAI))]
	internal class HoarderBugPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void hoarderBugAudioPatch(ref AudioClip[] ___chitterSFX)
		{
			AudioClip[] newSFX = YippeeModBase.newSFX;
			___chitterSFX = newSFX;
		}
	}
}