Decompiled source of modspooky Modpack v1.1.0

pachers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

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

pachers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.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

pachers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault())
			{
				Start();
			}
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(str, value));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour.HookGen
{
	public class HookGenerator
	{
		private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

		private static readonly Regex NameVerifyRegex;

		private static readonly Dictionary<Type, string> ReflTypeNameMap;

		private static readonly Dictionary<string, string> TypeNameMap;

		public MonoModder Modder;

		public ModuleDefinition OutputModule;

		public string Namespace;

		public string NamespaceIL;

		public bool HookOrig;

		public bool HookPrivate;

		public string HookExtName;

		public ModuleDefinition module_RuntimeDetour;

		public ModuleDefinition module_Utils;

		public TypeReference t_MulticastDelegate;

		public TypeReference t_IAsyncResult;

		public TypeReference t_AsyncCallback;

		public TypeReference t_MethodBase;

		public TypeReference t_RuntimeMethodHandle;

		public TypeReference t_EditorBrowsableState;

		public MethodReference m_Object_ctor;

		public MethodReference m_ObsoleteAttribute_ctor;

		public MethodReference m_EditorBrowsableAttribute_ctor;

		public MethodReference m_GetMethodFromHandle;

		public MethodReference m_Add;

		public MethodReference m_Remove;

		public MethodReference m_Modify;

		public MethodReference m_Unmodify;

		public TypeReference t_ILManipulator;

		static HookGenerator()
		{
			NameVerifyRegex = new Regex("[^a-zA-Z]");
			ReflTypeNameMap = new Dictionary<Type, string>
			{
				{
					typeof(string),
					"string"
				},
				{
					typeof(object),
					"object"
				},
				{
					typeof(bool),
					"bool"
				},
				{
					typeof(byte),
					"byte"
				},
				{
					typeof(char),
					"char"
				},
				{
					typeof(decimal),
					"decimal"
				},
				{
					typeof(double),
					"double"
				},
				{
					typeof(short),
					"short"
				},
				{
					typeof(int),
					"int"
				},
				{
					typeof(long),
					"long"
				},
				{
					typeof(sbyte),
					"sbyte"
				},
				{
					typeof(float),
					"float"
				},
				{
					typeof(ushort),
					"ushort"
				},
				{
					typeof(uint),
					"uint"
				},
				{
					typeof(ulong),
					"ulong"
				},
				{
					typeof(void),
					"void"
				}
			};
			TypeNameMap = new Dictionary<string, string>();
			foreach (KeyValuePair<Type, string> item in ReflTypeNameMap)
			{
				TypeNameMap[item.Key.FullName] = item.Value;
			}
		}

		public HookGenerator(MonoModder modder, string name)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0326: Expected O, but got Unknown
			Modder = modder;
			OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters
			{
				Architecture = modder.Module.Architecture,
				AssemblyResolver = modder.Module.AssemblyResolver,
				Kind = (ModuleKind)0,
				Runtime = modder.Module.Runtime
			});
			modder.MapDependencies();
			Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences);
			modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);
			Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
			if (string.IsNullOrEmpty(Namespace))
			{
				Namespace = "On";
			}
			NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
			if (string.IsNullOrEmpty(NamespaceIL))
			{
				NamespaceIL = "IL";
			}
			HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
			HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";
			modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
			{
				throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");
			}
			modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
			{
				throw new FileNotFoundException("MonoMod.Utils not found!");
			}
			t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
			t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
			t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
			t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
			t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
			t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));
			TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");
			t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator"));
			m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true));
			m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true));
			m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true));
			ModuleDefinition outputModule = OutputModule;
			MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase);
			val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle));
			m_GetMethodFromHandle = outputModule.ImportReference(val);
			m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true));
			m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true));
			m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true));
			m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true));
		}

		public void Generate()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					GenerateFor(current, out var hookType, out var hookILType);
					if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested)
					{
						OutputModule.Types.Add(hookType);
						OutputModule.Types.Add(hookILType);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			hookType = (hookILType = null);
			if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic))
			{
				return;
			}
			Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName);
			hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			bool flag = false;
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					flag |= GenerateFor(hookType, hookILType, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					TypeDefinition current2 = enumerator2.Current;
					GenerateFor(current2, out var hookType2, out var hookILType2);
					if (hookType2 != null && hookILType2 != null)
					{
						flag = true;
						hookType.NestedTypes.Add(hookType2);
						hookILType.NestedTypes.Add(hookILType2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			if (!flag)
			{
				hookType = (hookILType = null);
			}
		}

		public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
		{
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Expected O, but got Unknown
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Expected O, but got Unknown
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Expected O, but got Unknown
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Expected O, but got Unknown
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0601: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0653: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Expected O, but got Unknown
			if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor))
			{
				return false;
			}
			if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_"))
			{
				return false;
			}
			if (!HookPrivate && method.IsPrivate)
			{
				return false;
			}
			string name = GetFriendlyName((MethodReference)(object)method);
			bool flag = true;
			if (((MethodReference)method).Parameters.Count == 0)
			{
				flag = false;
			}
			IEnumerable<MethodDefinition> source = null;
			if (flag)
			{
				source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method);
				if (source.Count() == 0)
				{
					flag = false;
				}
			}
			if (flag)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++)
				{
					ParameterDefinition param = ((MethodReference)method).Parameters[parami];
					if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false);
					}
					if (source.Any(delegate(MethodDefinition other)
					{
						ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami);
						return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace;
					}))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true);
					}
					stringBuilder.Append("_");
					stringBuilder.Append(typeName.Replace(".", "").Replace("`", ""));
				}
				name += stringBuilder.ToString();
			}
			if (Extensions.FindEvent(hookType, name) != null)
			{
				int num = 1;
				string text;
				while (Extensions.FindEvent(hookType, text = name + "_" + num) != null)
				{
					num++;
				}
				name = text;
			}
			TypeDefinition val = GenerateDelegateFor(method);
			((MemberReference)val).Name = "orig_" + name;
			val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val);
			TypeDefinition val2 = GenerateDelegateFor(method);
			((MemberReference)val2).Name = "hook_" + name;
			((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val2);
			MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method);
			MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val4.Body = new MethodBody(val4);
			ILProcessor iLProcessor = val4.Body.GetILProcessor();
			iLProcessor.Emit(OpCodes.Ldtoken, val3);
			iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor.Emit(OpCodes.Ldarg_0);
			GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor.Emit(OpCodes.Ret);
			hookType.Methods.Add(val4);
			MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val6.Body = new MethodBody(val6);
			ILProcessor iLProcessor2 = val6.Body.GetILProcessor();
			iLProcessor2.Emit(OpCodes.Ldtoken, val3);
			iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor2.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Remove);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor2.Emit(OpCodes.Ret);
			hookType.Methods.Add(val6);
			EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2)
			{
				AddMethod = val4,
				RemoveMethod = val6
			};
			hookType.Events.Add(val7);
			MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val8.Body = new MethodBody(val8);
			ILProcessor iLProcessor3 = val8.Body.GetILProcessor();
			iLProcessor3.Emit(OpCodes.Ldtoken, val3);
			iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor3.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Modify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor3.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val8);
			MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val9.Body = new MethodBody(val9);
			ILProcessor iLProcessor4 = val9.Body.GetILProcessor();
			iLProcessor4.Emit(OpCodes.Ldtoken, val3);
			iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor4.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Unmodify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor4.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val9);
			EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator)
			{
				AddMethod = val8,
				RemoveMethod = val9
			};
			hookILType.Events.Add(val10);
			return true;
		}

		public TypeDefinition GenerateDelegateFor(MethodDefinition method)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			string name = GetFriendlyName((MethodReference)(object)method);
			int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method);
			if (num != 0)
			{
				string suffix = num.ToString();
				do
				{
					name = name + "_" + suffix;
				}
				while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix));
			}
			name = "d_" + name;
			TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate);
			MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
			val2.Body = new MethodBody(val2);
			val.Methods.Add(val2);
			MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType))
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			if (!method.IsStatic)
			{
				TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType);
				if (((TypeReference)method.DeclaringType).IsValueType)
				{
					val4 = (TypeReference)new ByReferenceType(val4);
				}
				((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4));
			}
			Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current = enumerator.Current;
					((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			val3.Body = new MethodBody(val3);
			val.Methods.Add(val3);
			MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			enumerator = ((MethodReference)val3).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current2 = enumerator.Current;
					((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback));
			((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object));
			val5.Body = new MethodBody(val5);
			val.Methods.Add(val5);
			MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult));
			val6.Body = new MethodBody(val6);
			val.Methods.Add(val6);
			return val;
		}

		private string GetFriendlyName(MethodReference method)
		{
			string text = ((MemberReference)method).Name;
			if (text.StartsWith("."))
			{
				text = text.Substring(1);
			}
			return text.Replace('.', '_');
		}

		private string GetFriendlyName(TypeReference type, bool full)
		{
			if (type is TypeSpecification)
			{
				StringBuilder stringBuilder = new StringBuilder();
				BuildFriendlyName(stringBuilder, type, full);
				return stringBuilder.ToString();
			}
			if (!full)
			{
				return ((MemberReference)type).Name;
			}
			return ((MemberReference)type).FullName;
		}

		private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!(type is TypeSpecification))
			{
				builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", ""));
				return;
			}
			if (type.IsByReference)
			{
				builder.Append("ref");
			}
			else if (type.IsPointer)
			{
				builder.Append("ptr");
			}
			BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full);
			if (type.IsArray)
			{
				builder.Append("Array");
			}
		}

		private bool IsPublic(TypeDefinition typeDef)
		{
			if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic))
			{
				return !typeDef.IsNotPublic;
			}
			return false;
		}

		private bool HasPublicArgs(GenericInstanceType typeGen)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeReference current = enumerator.Current;
					if (current.IsGenericParameter)
					{
						return false;
					}
					GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null);
					if (val != null && !HasPublicArgs(val))
					{
						return false;
					}
					if (!IsPublic(Extensions.SafeResolve(current)))
					{
						return false;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return true;
		}

		private TypeReference ImportVisible(TypeReference typeRef)
		{
			for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null))
			{
				GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null);
				if (val2 == null || HasPublicArgs(val2))
				{
					TypeDefinition val3 = val;
					while (true)
					{
						if (val3 != null)
						{
							if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters))
							{
								val3 = val3.DeclaringType;
								continue;
							}
							if (!val.IsEnum)
							{
								break;
							}
							typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType;
						}
						try
						{
							return OutputModule.ImportReference(typeRef);
						}
						catch
						{
							return OutputModule.TypeSystem.Object;
						}
					}
				}
				typeRef = val.BaseType;
			}
			return OutputModule.TypeSystem.Object;
		}

		private CustomAttribute GenerateObsolete(string message, bool error)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message));
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error));
			return val;
		}

		private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state));
			return val;
		}
	}
	internal class Program
	{
		private static void Main(string[] args)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version);
			if (args.Length == 0)
			{
				Console.WriteLine("No valid arguments (assembly path) passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			int num = 0;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] == "--namespace" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]);
					continue;
				}
				if (args[i] == "--namespace-il" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]);
					continue;
				}
				if (args[i] == "--orig")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1");
					continue;
				}
				if (args[i] == "--private")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
					continue;
				}
				num = i;
				break;
			}
			if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW")))
			{
				Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			}
			if (num >= args.Length)
			{
				Console.WriteLine("No assembly path passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			string text = args[num];
			string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null);
			text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll"));
			MonoModder val = new MonoModder
			{
				InputPath = text,
				OutputPath = text2,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				val.Read();
				val.MapDependencies();
				if (File.Exists(text2))
				{
					val.Log("[HookGen] Clearing " + text2);
					File.Delete(text2);
				}
				val.Log("[HookGen] Starting HookGenerator");
				HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2));
				ModuleDefinition outputModule = hookGenerator.OutputModule;
				try
				{
					hookGenerator.Generate();
					outputModule.Write(text2);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				val.Log("[HookGen] Done.");
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}
	}
}

plugins/DantorsMentalHospitalDunGen/MentalHospital.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using HarmonyLib;
using LethalLevelLoader;
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("MentalHospital")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MentalHospital")]
[assembly: AssemblyTitle("MentalHospital")]
[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 MentalHospital
{
	[BepInPlugin("MentalHospital", "MentalHospital", "1.0.0")]
	public class MentalHospitalDunGen : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("SpawnScrapInLevel")]
			[HarmonyPrefix]
			private static bool SetItemSpawnPoints(ref RuntimeDungeon ___dungeonGenerator)
			{
				if (((Object)___dungeonGenerator.Generator.DungeonFlow).name != "HospitalFlow")
				{
					return true;
				}
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Instance.mls.LogError((object)"Failed to get start of round instance. Scrap spawns may not work correctly.");
					return true;
				}
				Item val = instance.allItemsList.itemsList.Find((Item x) => x.itemName == "Bottles");
				if ((Object)(object)val == (Object)null)
				{
					Instance.mls.LogError((object)"Failed to find bottle bin item for reference snatching; scrap spawn may be significantly lower than expected.");
					return true;
				}
				Item val2 = instance.allItemsList.itemsList.Find((Item x) => x.itemName == "Golden cup");
				int num = 0;
				int num2 = 0;
				int num3 = 0;
				ItemGroup spawnableItems = val.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "GeneralItemClass");
				ItemGroup val3 = val.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "TabletopItems");
				ItemGroup spawnableItems2 = (ItemGroup)(((Object)(object)val2 == (Object)null) ? ((object)val3) : ((object)val2.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "SmallItems")));
				RandomScrapSpawn[] array = Object.FindObjectsOfType<RandomScrapSpawn>();
				RandomScrapSpawn[] array2 = array;
				foreach (RandomScrapSpawn val4 in array2)
				{
					switch (((Object)val4.spawnableItems).name)
					{
					case "GeneralItemClassDUMMY":
						val4.spawnableItems = spawnableItems;
						num++;
						break;
					case "TabletopItemsDUMMY":
						val4.spawnableItems = val3;
						num2++;
						break;
					case "SmallItemsDUMMY":
						val4.spawnableItems = spawnableItems2;
						num3++;
						break;
					}
				}
				Instance.mls.LogInfo((object)$"Totals for scrap replacement: General: {num}, Tabletop: {num2}, Small: {num3}");
				if (num + num2 + num3 < 10)
				{
					Instance.mls.LogWarning((object)"Unusually low scrap spawn count; scrap may be sparse.");
				}
				return true;
			}
		}

		private const string modGUID = "DantorMentalHospital";

		private const string modName = "Dantor's Mental Hospital";

		private const string modVersion = "1.0.0";

		private static MentalHospitalDunGen Instance;

		private readonly Harmony harmony = new Harmony("Dantor's Mental Hospital");

		private ConfigEntry<int> configSCPRarity;

		private ConfigEntry<string> configMoons;

		private ConfigEntry<bool> configGuaranteedSCP;

		private ConfigEntry<int> configLengthOverride;

		internal ManualLogSource mls;

		public static AssetBundle Assets;

		private void Awake()
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Expected O, but got Unknown
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Expected O, but got Unknown
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			//IL_031b: Expected O, but got Unknown
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0367: Expected O, but got Unknown
			//IL_0433: Unknown result type (might be due to invalid IL or missing references)
			//IL_043d: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cd: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			mls = Logger.CreateLogSource("MentalHospital");
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			Assets = AssetBundle.LoadFromFile(Path.Combine(directoryName, "hospitalbundle"));
			if ((Object)(object)Assets == (Object)null)
			{
				mls.LogError((object)"Failed to load DantorsMentalHospital assets.");
				return;
			}
			DungeonFlow val = Assets.LoadAsset<DungeonFlow>("Assets/Abandoned_Psychiatric_Hospitals/DunGen Data/HospitalFlow.asset");
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load DantorsMentalHospital Dungeon Flow.");
				return;
			}
			configSCPRarity = ((BaseUnityPlugin)this).Config.Bind<int>("General", "HospitalRarity", 100, new ConfigDescription("How rare it is for the mental hospital to be chosen. Higher values increases the chance of spawning the mental hospital. Vanillas' main dungeons use a value of 300. Google Weighted Random if you don't know how it works, as that's how Lethal Company rarities function.", (AcceptableValueBase)null, Array.Empty<object>()));
			configMoons = ((BaseUnityPlugin)this).Config.Bind<string>("General", "HospitalMoonsList", "vanilla", new ConfigDescription("The moon(s) that the hospital can spawn on, in the form of a comma separated list of selectable level names and optionally a weight value by using an '@' and weight value after it (e.g. \"Titan@300,Dine,Rend@10,Secret Labs@9999\")\nThe name matching is lenient and should pick it up if you use the terminal name or internal mod name. If no rarity is specified, the HospitalRarity parameter is used.\nThe following strings: \"all\", \"vanilla\", \"modded\", \"paid\", \"free\" are dynamic presets which add the dungeon to that specified group (string must only contain one of these, or a manual moon name list).\n", (AcceptableValueBase)null, Array.Empty<object>()));
			configGuaranteedSCP = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "HospitalGuaranteed", false, new ConfigDescription("\nIt should work but if it doesn't use a weight of something like '99999'", (AcceptableValueBase)null, Array.Empty<object>()));
			ExtendedDungeonFlow val2 = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			val2.contentSourceName = "Dantors Mental Hospital";
			val2.dungeonFlow = val;
			val2.dungeonDefaultRarity = 0;
			int num = (configGuaranteedSCP.Value ? 99999 : configSCPRarity.Value);
			switch (configMoons.Value.ToLower())
			{
			case "all":
				val2.dynamicLevelTagsList.Add(new StringWithRarity("Vanilla", num));
				val2.dynamicLevelTagsList.Add(new StringWithRarity("Custom", num));
				mls.LogInfo((object)"Registered DantorsMentalHospital dungeon for all moons.");
				break;
			case "vanilla":
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				mls.LogInfo((object)"Registered DantorsMentalHospital dungeon for all vanilla moons.");
				break;
			case "modded":
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
				mls.LogInfo((object)"Registered DantorsMentalHospital dungeon for all modded moons.");
				break;
			case "paid":
				val2.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(1f, 9999f), num));
				mls.LogInfo((object)"Registered DantorsMentalHospital dungeon for all paid moons.");
				break;
			case "free":
				val2.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(0f, 0f), num));
				mls.LogInfo((object)"Registered DantorsMentalHospital dungeon for all free moons.");
				break;
			default:
			{
				mls.LogInfo((object)"Registering DantorsMentalHospital dungeon for predefined moon list.");
				string[] array3 = configMoons.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
				List<StringWithRarity> list = new List<StringWithRarity>();
				for (int k = 0; k < array3.Length; k++)
				{
					string[] array4 = array3[k].Split('@', StringSplitOptions.RemoveEmptyEntries);
					int num2 = array4.Length;
					int result;
					if (num2 > 2)
					{
						mls.LogError((object)("Invalid setup for moon rarity config: " + array3[k] + ". Skipping."));
					}
					else if (num2 == 1)
					{
						mls.LogInfo((object)$"Registering DantorsMentalHospital dungeon for moon {array3[k]} at default rarity {num}");
						list.Add(new StringWithRarity(array3[k], num));
					}
					else if (!int.TryParse(array4[1], out result))
					{
						mls.LogError((object)("Failed to parse rarity value for moon " + array4[0] + ": " + array4[1] + ". Skipping."));
					}
					else
					{
						mls.LogInfo((object)$"Registering DantorsMentalHospital dungeon for moon {array3[k]} at default rarity {num}");
						list.Add(new StringWithRarity(array4[0], result));
					}
				}
				val2.manualPlanetNameReferenceList = list;
				break;
			}
			}
			val2.dungeonSizeMin = 0.5f;
			val2.dungeonSizeMax = 1.25f;
			val2.dungeonSizeLerpPercentage = 1f;
			val2.enableDynamicDungeonSizeRestriction = true;
			AssetBundleLoader.RegisterExtendedDungeonFlow(val2);
			harmony.PatchAll(typeof(MentalHospitalDunGen));
			harmony.PatchAll(typeof(RoundManagerPatch));
			mls.LogInfo((object)"DantorsMentalHospital DunGen for Lethal Company [Version 1.0.0] successfully loaded.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MentalHospital is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MentalHospital";

		public const string PLUGIN_NAME = "MentalHospital";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/LCOffice.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LCOffice.Patches;
using LethalLevelLoader;
using LethalLib.Modules;
using LethalNetworkAPI;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations.Rigging;
using UnityEngine.Events;
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("LcOffice")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LcOffice")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("8ee335db-0cbe-470c-8fbc-69263f01b35a")]
[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: 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 LCOffice
{
	[BepInPlugin("Piggy.LCOffice", "LCOffice", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "Piggy.LCOffice";

		private const string modName = "LCOffice";

		private const string modVersion = "1.0.3";

		private readonly Harmony harmony = new Harmony("Piggy.LCOffice");

		private static Plugin Instance;

		public static ManualLogSource mls;

		public static AssetBundle Bundle;

		public static AudioClip ElevatorOpen;

		public static AudioClip ElevatorClose;

		public static AudioClip ElevatorUp;

		public static AudioClip ElevatorDown;

		public static AudioClip stanleyVoiceline1;

		public static AudioClip bossaLullaby;

		public static AudioClip shopTheme;

		public static AudioClip saferoomTheme;

		public static AudioClip cootieTheme;

		public static AudioClip garageDoorSlam;

		public static AudioClip garageSlide;

		public static AudioClip floorOpen;

		public static AudioClip floorClose;

		public static AudioClip footstep1;

		public static AudioClip footstep2;

		public static AudioClip footstep3;

		public static AudioClip footstep4;

		public static AudioClip dogEatItem;

		public static AudioClip bigGrowl;

		public static AudioClip enragedScream;

		public static AudioClip dogSprint;

		public static AudioClip ripPlayerApart;

		public static AudioClip cry1;

		public static AudioClip dogHowl;

		public static AudioClip stomachGrowl;

		public static AudioClip eatenExplode;

		public static AudioClip dogSneeze;

		public static GameObject shrimpPrefab;

		public static GameObject storagePrefab;

		public static GameObject socketPrefab;

		public static GameObject socketInteractPrefab;

		public static EnemyType shrimpEnemy;

		public static ExtendedDungeonFlow officeExtendedDungeonFlow;

		public static DungeonFlow officeDungeonFlow;

		public static TerminalNode shrimpTerminalNode;

		public static TerminalKeyword shrimpTerminalKeyword;

		public static string PluginDirectory;

		private ConfigEntry<bool> configGuaranteedOffice;

		private ConfigEntry<int> configOfficeRarity;

		private ConfigEntry<string> configMoons;

		private ConfigEntry<string> shrimpSpawnWeight;

		private ConfigEntry<int> shrimpModdedSpawnWeight;

		public static bool setKorean;

		private void Awake()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Expected O, but got Unknown
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Expected O, but got Unknown
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0347: 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_0357: Expected O, but got Unknown
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configOfficeRarity = ((BaseUnityPlugin)this).Config.Bind<int>("General", "OfficeRarity", 50, new ConfigDescription("How rare it is for the office to be chosen. Higher values increases the chance of spawning the office.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			configGuaranteedOffice = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "OfficeGuaranteed", false, new ConfigDescription("If enabled, the office will be effectively guaranteed to spawn. Only recommended for debugging/sightseeing purposes.", (AcceptableValueBase)null, Array.Empty<object>()));
			configMoons = ((BaseUnityPlugin)this).Config.Bind<string>("General", "OfficeMoonsList", "free", new ConfigDescription("The moon(s) that the office can spawn on, in the form of a comma separated list of selectable level names (e.g. \"TitanLevel,RendLevel,DineLevel\")\nNOTE: These must be the internal data names of the levels (all vanilla moons are \"MoonnameLevel\", for modded moon support you will have to find their name if it doesn't follow the convention).\nThe following strings: \"all\", \"vanilla\", \"modded\", \"paid\", \"free\", \"none\" are dynamic presets which add the dungeon to that specified group (string must only contain one of these, or a manual moon name list).\nDefault dungeon generation size is balanced around the dungeon scale multiplier of Titan (2.35), moons with significantly different dungeon size multipliers (see Lethal Company wiki for values) may result in dungeons that are extremely small/large.", (AcceptableValueBase)null, Array.Empty<object>()));
			shrimpSpawnWeight = ((BaseUnityPlugin)this).Config.Bind<string>("Spawn", "ShrimpSpawnWeight", "2,4,5,3,6,8,8,10", new ConfigDescription("Set the shrimp spawn weight for each moon. In this order:\n(experimentation, assurance, vow, march, offense, rend, dine, titan).", (AcceptableValueBase)null, Array.Empty<object>()));
			shrimpModdedSpawnWeight = ((BaseUnityPlugin)this).Config.Bind<int>("Spawn", "ShrimpModdedMoonSpawnWeight", 5, new ConfigDescription("Set the shrimp spawn weight for modded moon. ", (AcceptableValueBase)null, Array.Empty<object>()));
			setKorean = ((BaseUnityPlugin)this).Config.Bind<bool>("Translation", "Enable Korean", false, "Set language to Korean.").Value;
			PluginDirectory = ((BaseUnityPlugin)this).Info.Location;
			mls = Logger.CreateLogSource("Piggy.LCOffice");
			mls.LogInfo((object)"LC_Office is loaded!");
			Bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lcoffice"));
			officeDungeonFlow = Bundle.LoadAsset<DungeonFlow>("OfficeDungeonFlow.asset");
			officeExtendedDungeonFlow = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			officeExtendedDungeonFlow.contentSourceName = "LC_Office";
			officeExtendedDungeonFlow.dungeonFlow = officeDungeonFlow;
			officeExtendedDungeonFlow.dungeonDefaultRarity = 0;
			int num = (configGuaranteedOffice.Value ? 99999 : configOfficeRarity.Value);
			if (configMoons.Value.ToLower() == "all")
			{
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
			}
			else if (configMoons.Value.ToLower() == "vanilla")
			{
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
			}
			else if (configMoons.Value.ToLower() == "modded")
			{
				officeExtendedDungeonFlow.dynamicLevelTagsList.Add(new StringWithRarity("Custom", num));
			}
			else if (configMoons.Value.ToLower() == "paid")
			{
				officeExtendedDungeonFlow.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(1f, 9999f), num));
			}
			else if (configMoons.Value.ToLower() == "free")
			{
				officeExtendedDungeonFlow.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(0f, 0f), num));
			}
			else if (!(configMoons.Value.ToLower() == "none"))
			{
				string[] array = configMoons.Value.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
				StringWithRarity[] array2 = (StringWithRarity[])(object)new StringWithRarity[array.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array2[i] = new StringWithRarity(array[i], num);
				}
				officeExtendedDungeonFlow.manualPlanetNameReferenceList = array2.ToList();
			}
			officeExtendedDungeonFlow.dungeonSizeMax = 0.1f;
			officeExtendedDungeonFlow.dungeonSizeLerpPercentage = 0f;
			AssetBundleLoader.RegisterExtendedDungeonFlow(officeExtendedDungeonFlow);
			shrimpPrefab = Bundle.LoadAsset<GameObject>("Shrimp.prefab");
			shrimpPrefab.AddComponent<ShrimpAI>();
			shrimpEnemy = Bundle.LoadAsset<EnemyType>("ShrimpEnemy.asset");
			storagePrefab = Bundle.LoadAsset<GameObject>("DepositPlace.prefab");
			socketPrefab = Bundle.LoadAsset<GameObject>("ElevatorSocket.prefab");
			socketInteractPrefab = Bundle.LoadAsset<GameObject>("LungPlacement.prefab");
			GameObject val = Bundle.LoadAsset<GameObject>("OfficeStartRoom.prefab");
			val.AddComponent<ElevatorSystem>();
			bossaLullaby = Bundle.LoadAsset<AudioClip>("bossa_lullaby_refiltered.ogg");
			shopTheme = Bundle.LoadAsset<AudioClip>("shop_refiltered.ogg");
			saferoomTheme = Bundle.LoadAsset<AudioClip>("saferoom_refiltered.ogg");
			ElevatorOpen = Bundle.LoadAsset<AudioClip>("ElevatorOpen.ogg");
			ElevatorClose = Bundle.LoadAsset<AudioClip>("ElevatorClose.ogg");
			ElevatorDown = Bundle.LoadAsset<AudioClip>("ElevatorDown.ogg");
			ElevatorUp = Bundle.LoadAsset<AudioClip>("ElevatorUp.ogg");
			garageDoorSlam = Bundle.LoadAsset<AudioClip>("GarageDoorSlam.ogg");
			garageSlide = Bundle.LoadAsset<AudioClip>("GarageDoorSlide1.ogg");
			floorOpen = Bundle.LoadAsset<AudioClip>("FloorOpen.ogg");
			floorClose = Bundle.LoadAsset<AudioClip>("FloorClosed.ogg");
			footstep1 = Bundle.LoadAsset<AudioClip>("Footstep1.ogg");
			footstep2 = Bundle.LoadAsset<AudioClip>("Footstep2.ogg");
			footstep3 = Bundle.LoadAsset<AudioClip>("Footstep3.ogg");
			footstep4 = Bundle.LoadAsset<AudioClip>("Footstep4.ogg");
			dogEatItem = Bundle.LoadAsset<AudioClip>("DogEatObject.ogg");
			bigGrowl = Bundle.LoadAsset<AudioClip>("BigGrowl.ogg");
			enragedScream = Bundle.LoadAsset<AudioClip>("DogRage.ogg");
			dogSprint = Bundle.LoadAsset<AudioClip>("DogSprint.ogg");
			ripPlayerApart = Bundle.LoadAsset<AudioClip>("RipPlayerApart.ogg");
			cry1 = Bundle.LoadAsset<AudioClip>("Cry1.ogg");
			dogHowl = Bundle.LoadAsset<AudioClip>("DogHowl.ogg");
			stomachGrowl = Bundle.LoadAsset<AudioClip>("StomachGrowl.ogg");
			eatenExplode = Bundle.LoadAsset<AudioClip>("eatenExplode.ogg");
			dogSneeze = Bundle.LoadAsset<AudioClip>("Sneeze.ogg");
			stanleyVoiceline1 = Bundle.LoadAsset<AudioClip>("stanley.ogg");
			shrimpTerminalNode = Bundle.LoadAsset<TerminalNode>("ShrimpFile.asset");
			shrimpTerminalKeyword = Bundle.LoadAsset<TerminalKeyword>("shrimpTK.asset");
			if (!setKorean)
			{
				shrimpTerminalNode.displayText = "Shrimp\r\n\r\nSigurd’s Danger Level: 60%\r\n\r\n\nScientific name: Canispiritus-Artemus\r\n\r\nShrimps are dog-like creatures, known to be the first tenant of the Upturned Inn. For the most part, he is relatively friendly to humans, following them around, curiously stalking them. Unfortunately, their passive temperament comes with a dangerously vicious hunger.\r\nDue to the nature of their biology, he has a much more unique stomach organ than most other creatures. The stomach lining is flexible, yet hardy, allowing a Shrimp to digest and absorb the nutrients from anything, biological or not, so long as it isn’t too large.\r\n\r\nHowever, this evolutionary adaptation was most likely a result of their naturally rapid metabolism. He uses nutrients so quickly that he needs to eat multiple meals a day to survive. The time between these meals are inconsistent, as the rate of caloric consumption is variable. This can range from hours to even minutes and causes the shrimp to behave monstrously if he has not eaten for a while.\r\n\r\nKnown to live in abandoned buildings, shrimp can often be seen in large abandoned factories or offices scavenging for scrap metal, to eat. That isn’t to say he can’t be found elsewhere. He is usually a lone hunters and expert trackers out of necessity.\r\n\r\nSigurd’s Note:\r\nIf this guy spots you, you’ll want to drop something you’re holding and let him eat it. It’s either you or that piece of scrap on you.\r\n\r\nit’s best to avoid letting him spot you. I swear… it’s almost like his eyes are staring into your soul.\r\nI never want to see one of these guys behind me again.\r\n\r\n\r\nIK: <i>Sir, don't be sad! Shrimp didn't hate you.\r\nhe was just... hungry.</i>\r\n\r\n";
				shrimpTerminalNode.creatureName = "Shrimp";
				shrimpTerminalKeyword.word = "shrimp";
			}
			else
			{
				shrimpTerminalNode.displayText = "쉬림프\r\n\r\n시구르드의 위험 수준: 60%\r\n\r\n\n학명: 카니스피리투스-아르테무스\r\n\r\n쉬림프는 개를 닮은 생명체로 Upturned Inn의 첫 번째 세입자로 알려져 있습니다. 평소에는 상대적으로 우호적이며, 호기심을 가지고 인간을 따라다닙니다. 불행하게도 그는 위험할 정도로 굉장한 식욕을 가지고 있습니다.\r\n생물학적 특성으로 인해, 그는 대부분의 다른 생물보다 훨씬 더 독특한 위장 기관을 가지고 있습니다. 위 내막은 유연하면서도 견고하기 때문에 어떤 물체라도 영양분을 소화하고 흡수할 수 있습니다.\r\n그러나 이러한 진화적 적응은 자연적으로 빠른 신진대사의 결과일 가능성이 높습니다. 그는 영양분을 너무 빨리 사용하기 때문에 생존하려면 하루에 여러 끼를 먹어야 합니다.\r\n칼로리 소비율이 다양하기 때문에 식사 사이의 시간이 일정하지 않습니다. 이는 몇 시간에서 몇 분까지 지속될 수 있으며, 쉬림프가 오랫동안 무언가를 먹지 않으면 매우 포악해지며 따라다니던 사람을 쫒습니다.\r\n\r\n버려진 건물에 사는 것으로 알려진 쉬림프는 버려진 공장이나 사무실에서 폐철물을 찾아다니는 것으로 발견할 수 있습니다. 그렇다고 다른 곳에서 그를 찾을 수 없다는 말은 아닙니다. 그는 일반적으로 고독한 사냥꾼이며, 때로는 전문적인 추적자가 되기도 합니다.\r\n\r\n시구르드의 노트: 이 녀석이 으르렁거리는 소리를 듣게 된다면, 먹이를 줄 수 있는 무언가를 가지고 있기를 바라세요. 아니면 당신이 이 녀석의 식사가 될 거예요.\r\n맹세컨대... 마치 당신의 영혼을 들여다보는 것 같아요. 다시는 내 뒤에서 이 녀석을 보고 싶지 않아요.\r\n\r\n\r\nIK: <i>손님, 슬퍼하지 마세요! 쉬림프는 당신을 싫어하지 않는답니다.\r\n걔는 그냥... 배고플 뿐이에요.</i>\r\n\r\n";
				shrimpTerminalNode.creatureName = "쉬림프";
				shrimpTerminalKeyword.word = "쉬림프";
			}
			NetworkPrefabs.RegisterNetworkPrefab(shrimpPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(storagePrefab);
			NetworkPrefabs.RegisterNetworkPrefab(socketInteractPrefab);
			int[] array3 = shrimpSpawnWeight.Value.Split(new char[1] { ',' }).Select(int.Parse).ToArray();
			Enemies.RegisterEnemy(shrimpEnemy, array3[0], (LevelTypes)4, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in ExperimentationLevel: " + array3[0]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[1], (LevelTypes)8, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in AssuranceLevel: " + array3[1]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[2], (LevelTypes)16, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in VowLevel: " + array3[2]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[3], (LevelTypes)64, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in MarchLevel: " + array3[3]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[4], (LevelTypes)32, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in OffenseLevel: " + array3[4]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[5], (LevelTypes)128, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in RendLevel: " + array3[5]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[6], (LevelTypes)256, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in DineLevel: " + array3[6]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[7], (LevelTypes)512, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in TitanLevel: " + array3[7]));
			Enemies.RegisterEnemy(shrimpEnemy, shrimpModdedSpawnWeight.Value, (LevelTypes)1024, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in Modded Moons: " + shrimpModdedSpawnWeight.Value));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[LC_Office] Successfully loaded assets!");
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(GrabbableObjectPatch));
			harmony.PatchAll(typeof(TerminalPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(GameNetworkManagerPatch));
			harmony.PatchAll(typeof(PlaceLung));
			socketInteractPrefab.AddComponent<PlaceLung>();
		}
	}
}
namespace LCOffice.Patches
{
	public class PlaceLung : NetworkBehaviour
	{
		public static LethalNetworkVariable<bool> lungPlacedThisFrame = new LethalNetworkVariable<bool>("lungPlacedThisFrame");

		public static LethalNetworkVariable<bool> placeLungNetwork = new LethalNetworkVariable<bool>("placeLung");

		public static LethalNetworkVariable<ulong> lungPlacer = new LethalNetworkVariable<ulong>("Installer");

		[PublicNetworkVariable]
		public static LethalNetworkVariable<GameObject> placedLung = new LethalNetworkVariable<GameObject>("placedLung");

		public LethalClientEvent onLungPlace = new LethalClientEvent("onLungPlace", (Action)null, (Action<ulong>)null);

		public LethalClientMessage<bool> onLungPlaced = new LethalClientMessage<bool>("onLungPlaced", (Action<bool>)null, (Action<bool, ulong>)null);

		public LethalClientMessage<bool> onLungRemoved = new LethalClientMessage<bool>("onLungRemoved", (Action<bool>)null, (Action<bool, ulong>)null);

		public bool isPlaceCalled;

		public bool isOtherClientPlaceChecked;

		public bool isOtherClientRemoveChecked;

		public static bool lungPlaced;

		public static bool lungPlacedLocalFrame;

		public static bool emergencyPowerRequires;

		public static bool emergencyCheck;

		public bool isSetupEnd;

		public static ElevatorSystem elevatorSystem;

		public static Animator socketLED;

		public static AudioSource socketAudioSource;

		public static InteractTrigger socketInteractTrigger;

		public static Transform lungPos;

		public static Transform lungSocket;

		public static Transform lungParent;

		public static Animator lungParentAnimator;

		public static AudioSource elevatorMusic;

		public static AudioSource elevatorSound;

		public static Animator elevatorAnimator;

		public static List<InteractTrigger> upButtons = new List<InteractTrigger>();

		public static List<InteractTrigger> downButtons = new List<InteractTrigger>();

		public LungProp lungComponent;

		public bool isForceMoving;

		public BoxCollider boxCollider;

		public List<Light> elevatorLights = new List<Light>();

		private void Start()
		{
			lungPlacedThisFrame.Value = false;
			placeLungNetwork.Value = false;
			lungPlacer.Value = 0uL;
			placedLung.Value = null;
		}

		private void LateUpdate()
		{
			//IL_002a: 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_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_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Setup();
			((Component)this).transform.position = lungPos.position;
			((Component)this).transform.rotation = lungPos.rotation;
			if (emergencyCheck && !emergencyPowerRequires && !lungPlaced && !ElevatorSystem.isElevatorDowned.Value)
			{
				elevatorSystem.ElevatorDownTrigger(StartOfRound.Instance.localPlayerController);
			}
			if (emergencyCheck && !emergencyPowerRequires)
			{
				ElevatorSystem.isElevatorClosed.Value = false;
				elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 2.5f);
				AnimatorStateInfo currentAnimatorStateInfo = elevatorSystem.doorAnimator.GetCurrentAnimatorStateInfo(0);
				if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 1f && elevatorSystem.doorAnimator.GetBool("closed"))
				{
					currentAnimatorStateInfo = elevatorSystem.animator.GetCurrentAnimatorStateInfo(0);
					if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 1f && elevatorSystem.animator.GetBool("goDown") && ((Component)elevatorAnimator).gameObject.transform.localPosition.y <= -9.6998f)
					{
						emergencyPowerRequires = true;
						emergencyCheck = false;
					}
				}
			}
			if (lungPlaced)
			{
				lungComponent = placedLung.Value.GetComponent<LungProp>();
				boxCollider.size = new Vector3(0f, 0f, 0f);
				placedLung.Value.transform.SetParent(lungParent);
				placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
				placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
				if (lungPlacedLocalFrame && emergencyPowerRequires)
				{
					foreach (InteractTrigger upButton in upButtons)
					{
						((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
					}
					foreach (InteractTrigger downButton in downButtons)
					{
						((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
					}
					lungPlacedLocalFrame = false;
				}
			}
			else
			{
				if (emergencyPowerRequires)
				{
					foreach (InteractTrigger upButton2 in upButtons)
					{
						((UnityEventBase)upButton2.onInteract).RemoveAllListeners();
					}
					foreach (InteractTrigger downButton2 in downButtons)
					{
						((UnityEventBase)downButton2.onInteract).RemoveAllListeners();
					}
				}
				lungPlacedLocalFrame = true;
				boxCollider.size = new Vector3(2f, 1.6f, 2f);
				lungComponent = null;
			}
			CheckPlayerHoldingLung();
			if (lungPlaced)
			{
				RemoveLung();
			}
			if (lungPlacedThisFrame.Value)
			{
				LungPlacement();
			}
			if (isOtherClientPlaceChecked)
			{
				OnLungPlacedThisFrameOtherClient();
			}
			if (isOtherClientRemoveChecked)
			{
				RemoveLungOtherClient();
			}
			if (emergencyPowerRequires)
			{
				if (lungPlaced)
				{
					elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 1f, Time.deltaTime * 3f));
					elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
					elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3f);
					elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3.5f);
				}
				else
				{
					elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 0f, Time.deltaTime * 3f));
					elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
					elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 3f);
					elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 2.5f);
				}
			}
			else
			{
				elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 1f, Time.deltaTime * 3f));
				elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
				elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3f);
				elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3.5f);
			}
		}

		private void Setup()
		{
			if (isSetupEnd)
			{
				return;
			}
			elevatorSystem = Object.FindObjectOfType<ElevatorSystem>();
			socketAudioSource = ((Component)this).GetComponent<AudioSource>();
			socketInteractTrigger = ((Component)this).GetComponent<InteractTrigger>();
			((UnityEvent<PlayerControllerB>)(object)socketInteractTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)PlaceApparatus);
			socketLED = GameObject.Find("SocketLED").GetComponent<Animator>();
			boxCollider = ((Component)this).GetComponent<BoxCollider>();
			lungPos = GameObject.Find("LungPos").transform;
			lungSocket = GameObject.Find("LungSocket").transform;
			elevatorMusic = GameObject.Find("ElevatorMusic").GetComponent<AudioSource>();
			elevatorSound = GameObject.Find("ElevatorSound").GetComponent<AudioSource>();
			elevatorAnimator = Object.FindObjectOfType<ElevatorSystem>().animator;
			elevatorLights.Add(GameObject.Find("ElevatorLight1").GetComponent<Light>());
			elevatorLights.Add(GameObject.Find("ElevatorLight2").GetComponent<Light>());
			lungParent = GameObject.Find("LungParent").transform;
			lungParentAnimator = ((Component)lungParent).GetComponent<Animator>();
			foreach (Animator panelAnimator in elevatorSystem.panelAnimators)
			{
				upButtons.Add(((Component)((Component)panelAnimator).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>());
				downButtons.Add(((Component)((Component)panelAnimator).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>());
			}
			lungPlacedThisFrame.Value = false;
			placeLungNetwork.Value = false;
			lungPlacer.Value = 0uL;
			placedLung.Value = null;
			isSetupEnd = true;
		}

		private void CheckPlayerHoldingLung()
		{
			if (StartOfRound.Instance.localPlayerController.isHoldingObject)
			{
				if ((Object)(object)((Component)StartOfRound.Instance.localPlayerController.currentlyGrabbingObject).GetComponent<LungProp>() != (Object)null)
				{
					socketInteractTrigger.interactable = true;
				}
				else
				{
					socketInteractTrigger.interactable = false;
				}
			}
			else
			{
				socketInteractTrigger.interactable = false;
			}
		}

		private void LungPlacement()
		{
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			onLungPlaced.OnReceivedFromClient += OnLungPlacedThisFrame;
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame.Value is true");
			if (isPlaceCalled)
			{
				return;
			}
			PlayerControllerB playerController = LethalNetworkExtensions.GetPlayerController(lungPlacer.Value);
			socketLED.SetBool("warning", false);
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame is enabled");
			placedLung.Value = ((Component)playerController.currentlyGrabbingObject).gameObject;
			socketAudioSource.PlayOneShot(((Component)playerController.currentlyGrabbingObject).GetComponent<LungProp>().connectSFX);
			if (emergencyPowerRequires)
			{
				foreach (Light elevatorLight in elevatorLights)
				{
					((Behaviour)elevatorLight).enabled = true;
				}
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
				}
			}
			playerController.DiscardHeldObject(true, ((NetworkBehaviour)this).NetworkObject, ((Component)this).transform.position, true);
			lungPlaced = true;
			lungComponent = placedLung.Value.GetComponent<LungProp>();
			placedLung.Value.transform.SetParent(lungParent);
			placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
			placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
			isPlaceCalled = true;
			lungParentAnimator.SetTrigger("LungPlaced");
			if (!LethalNetworkExtensions.GetPlayerController(lungPlacer.Value).isCameraDisabled)
			{
				onLungPlaced.SendAllClients(true, false, false);
			}
			lungPlacedThisFrame.Value = false;
		}

		private void OnLungPlacedThisFrame(bool value, ulong id)
		{
			if (isOtherClientPlaceChecked != value)
			{
				isOtherClientPlaceChecked = value;
			}
		}

		private void OnLungPlacedThisFrameOtherClient()
		{
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			if (isPlaceCalled)
			{
				return;
			}
			PlayerControllerB playerController = LethalNetworkExtensions.GetPlayerController(lungPlacer.Value);
			socketLED.SetBool("warning", false);
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame is enabled");
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().connectSFX);
			if (emergencyPowerRequires)
			{
				foreach (Light elevatorLight in elevatorLights)
				{
					((Behaviour)elevatorLight).enabled = true;
				}
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
				}
			}
			lungPlaced = true;
			lungComponent = placedLung.Value.GetComponent<LungProp>();
			placedLung.Value.transform.SetParent(lungParent);
			placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
			placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
			boxCollider.size = new Vector3(0f, 0f, 0f);
			lungPlacedThisFrame.Value = false;
			isPlaceCalled = true;
			lungParentAnimator.SetTrigger("LungPlaced");
			isOtherClientPlaceChecked = false;
		}

		private void PlaceApparatus(PlayerControllerB playerControllerB)
		{
			Plugin.mls.LogInfo((object)("PlaceApparatus triggered by " + ((Object)((Component)playerControllerB).gameObject).name));
			if ((Object)(object)((Component)playerControllerB.currentlyGrabbingObject).GetComponent<LungProp>() != (Object)null && playerControllerB.isHoldingObject)
			{
				Plugin.mls.LogInfo((object)(((Object)((Component)playerControllerB).gameObject).name + " is placed LungProp"));
				lungPlacedThisFrame.Value = true;
				lungPlacer.Value = playerControllerB.actualClientId;
			}
		}

		private void RemoveLung()
		{
			onLungRemoved.OnReceivedFromClient += OnLungRemovedThisFrame;
			if (!((GrabbableObject)lungComponent).isHeld)
			{
				return;
			}
			foreach (Light elevatorLight in elevatorLights)
			{
				((Behaviour)elevatorLight).enabled = false;
			}
			socketLED.SetBool("warning", true);
			if (emergencyPowerRequires)
			{
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEventBase)upButton.onInteract).RemoveAllListeners();
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEventBase)downButton.onInteract).RemoveAllListeners();
				}
			}
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().disconnectSFX);
			lungPlaced = false;
			isPlaceCalled = false;
			onLungRemoved.SendAllClients(true, false, false);
		}

		private void OnLungRemovedThisFrame(bool value, ulong id)
		{
			if (isOtherClientRemoveChecked != value)
			{
				isOtherClientRemoveChecked = value;
			}
		}

		private void RemoveLungOtherClient()
		{
			if (!lungPlaced || !((GrabbableObject)lungComponent).isHeld)
			{
				return;
			}
			foreach (Light elevatorLight in elevatorLights)
			{
				((Behaviour)elevatorLight).enabled = false;
			}
			socketLED.SetBool("warning", true);
			if (emergencyPowerRequires)
			{
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEventBase)upButton.onInteract).RemoveAllListeners();
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEventBase)downButton.onInteract).RemoveAllListeners();
				}
			}
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().disconnectSFX);
			lungPlaced = false;
			isPlaceCalled = false;
		}

		private IEnumerator LightFlickerOn()
		{
			using List<Light>.Enumerator enumerator = elevatorLights.GetEnumerator();
			if (enumerator.MoveNext())
			{
				Light elevatorLight = enumerator.Current;
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = false;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = false;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(2f);
				yield break;
			}
		}

		[HarmonyPatch(typeof(LungProp))]
		[HarmonyPrefix]
		[HarmonyPatch("EquipItem")]
		private static void EquipItem_Patch(ref bool ___isLungDocked)
		{
			if (!___isLungDocked || !RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Animator component = GameObject.Find("SocketLED").GetComponent<Animator>();
			component.SetBool("on", true);
			ElevatorSystem elevatorSystem = Object.FindObjectOfType<ElevatorSystem>();
			PlaceLung placeLung = Object.FindObjectOfType<PlaceLung>();
			foreach (Animator panelAnimator in elevatorSystem.panelAnimators)
			{
				((UnityEventBase)((Component)((Component)panelAnimator).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>().onInteract).RemoveAllListeners();
				((UnityEventBase)((Component)((Component)panelAnimator).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>().onInteract).RemoveAllListeners();
				if (!lungPlaced)
				{
					((Behaviour)GameObject.Find("ElevatorLight1").GetComponent<Light>()).enabled = false;
					((Behaviour)GameObject.Find("ElevatorLight2").GetComponent<Light>()).enabled = false;
				}
				component.SetBool("warning", true);
				emergencyCheck = true;
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Disconnect")]
		private static void Disconnect_Prefix()
		{
		}
	}
	public class RoundMapSystem : NetworkBehaviour
	{
		public bool isOffice;

		public bool isChecked;

		public bool isDungeonOfficeChecked;

		public static RoundMapSystem Instance { get; private set; }

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

		private void LateUpdate()
		{
			if (!isChecked && !StartOfRound.Instance.inShipPhase && (!((Object)(object)GameObject.Find("IndustrialFan") == (Object)null) || !((Object)(object)GameObject.Find("ManorStartRoom") == (Object)null)))
			{
				if ((Object)(object)GameObject.Find("IndustrialFan") != (Object)null && (Object)(object)GameObject.Find("ElevatorScreenDoor") != (Object)null)
				{
					isOffice = true;
					Plugin.mls.LogInfo((object)"isOffice true");
				}
				else
				{
					isOffice = false;
					Plugin.mls.LogInfo((object)"isOffice false");
				}
				if (!isDungeonOfficeChecked)
				{
					((MonoBehaviour)this).StartCoroutine(CheckOfficeElevator());
				}
				isDungeonOfficeChecked = true;
			}
		}

		private IEnumerator CheckOfficeElevator()
		{
			yield return (object)new WaitForSeconds(2f);
			isChecked = true;
		}
	}
	public class ShrimpCollider : MonoBehaviour, IHittable
	{
		public ShrimpAI shrimpAI;

		private void Start()
		{
			shrimpAI = ((Component)((Component)this).transform.parent).GetComponent<ShrimpAI>();
		}

		bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit, bool playHitSFX = false)
		{
			if (ShrimpAI.hungerValue.Value < 55f && shrimpAI.scaredBackingAway <= 0f)
			{
				ShrimpAI.isHitted.Value = true;
			}
			return true;
		}
	}
	public class ShrimpAI : EnemyAI
	{
		public float networkPosDistance;

		public Vector3 prevPosition;

		public float stuckDetectionTimer;

		public float prevPositionDistance;

		public AISearchRoutine roamMap = new AISearchRoutine();

		private Vector3 spawnPosition;

		public PlayerControllerB hittedPlayer;

		public static LethalNetworkVariable<bool> KillingPlayerBool = new LethalNetworkVariable<bool>("KillingPlayerBool");

		public static LethalNetworkVariable<int> SelectNode = new LethalNetworkVariable<int>("SelectNode");

		public static LethalNetworkVariable<float> shrimpVelocity = new LethalNetworkVariable<float>("shrimpVelocity");

		public static LethalNetworkVariable<float> hungerValue = new LethalNetworkVariable<float>("hungerValue");

		public static LethalNetworkVariable<bool> isHitted = new LethalNetworkVariable<bool>("isHitted");

		public static LethalNetworkVariable<Vector3> networkPosition = new LethalNetworkVariable<Vector3>("networkPosition");

		public static LethalNetworkVariable<Vector3> networkRotation = new LethalNetworkVariable<Vector3>("networkRotation");

		public static LethalNetworkVariable<PlayerControllerB> networkTargetPlayer = new LethalNetworkVariable<PlayerControllerB>("networkTargetPlayer");

		public bool isKillingPlayer;

		public bool isSeenPlayer;

		public bool isEnraging;

		public bool isAngered;

		public bool canBeMoved;

		public bool isRunning;

		public bool dogRandomWalk;

		public float footStepTime;

		public float randomVal;

		public bool isTargetAvailable;

		public float networkTargetPlayerDistance;

		public float nearestItemDistance;

		public bool isNearestItem;

		public List<GameObject> droppedItems = new List<GameObject>();

		public GameObject nearestDroppedItem;

		public Transform dogHead;

		public Ray lookRay;

		public Transform lookTarget;

		public BoxCollider[] allBoxCollider;

		public Transform IdleTarget;

		public bool isIdleTargetAvailable;

		public bool forceChangeTarget;

		public Rig lookRig;

		public Light lungLight;

		public bool ateLung;

		public bool isSatisfied;

		public float satisfyValue;

		public Transform leftEye;

		public Transform rightEye;

		public Transform shrimpEye;

		public Transform mouth;

		public GameObject shrimpKillTrigger;

		public Transform bittenObjectHolder;

		public float searchingForObjectTimer;

		private Vector3 scaleOfEyesNormally;

		public AudioSource mainAudio;

		public AudioSource voiceAudio;

		public AudioSource voice2Audio;

		public AudioSource dogMusic;

		public AudioSource sprintAudio;

		public Vector3 originalMouthScale;

		public float scaredBackingAway;

		public Ray backAwayRay;

		private RaycastHit hitInfo;

		private RaycastHit hitInfoB;

		public float followTimer;

		public EnemyBehaviourState roamingState;

		public EnemyBehaviourState followingPlayer;

		public EnemyBehaviourState enragedState;

		public List<EnemyBehaviourState> tempEnemyBehaviourStates;

		public List<SkinnedMeshRenderer> skinnedMeshRendererList;

		public List<MeshRenderer> meshRendererList;

		private void Awake()
		{
			base.agent = ((Component)this).GetComponent<NavMeshAgent>();
		}

		public override void Start()
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Expected O, but got Unknown
			KillingPlayerBool.Value = false;
			SelectNode.Value = 0;
			shrimpVelocity.Value = 0f;
			hungerValue.Value = 0f;
			isHitted.Value = false;
			networkTargetPlayer.Value = null;
			((Component)((Component)this).transform.GetChild(0)).GetComponent<EnemyAICollisionDetect>().mainScript = (EnemyAI)(object)this;
			base.enemyType = Plugin.shrimpEnemy;
			base.skinnedMeshRenderers = ((Component)this).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
			base.meshRenderers = ((Component)this).gameObject.GetComponentsInChildren<MeshRenderer>();
			base.thisNetworkObject = ((Component)this).gameObject.GetComponentInChildren<NetworkObject>();
			base.serverPosition = ((Component)this).transform.position;
			base.thisEnemyIndex = RoundManager.Instance.numberOfEnemiesInScene;
			RoundManager instance = RoundManager.Instance;
			instance.numberOfEnemiesInScene++;
			base.allAINodes = GameObject.FindGameObjectsWithTag("AINode");
			base.path1 = new NavMeshPath();
			mouth = GameObject.Find("ShrimpMouth").transform;
			leftEye = GameObject.Find("ShrimpLeftEye").transform;
			rightEye = GameObject.Find("ShrimpRightEye").transform;
			shrimpKillTrigger = GameObject.Find("ShrimpKillTrigger");
			base.creatureAnimator = ((Component)((Component)this).transform.GetChild(0).GetChild(1)).gameObject.GetComponent<Animator>();
			base.creatureAnimator.SetTrigger("Walk");
			mainAudio = GameObject.Find("ShrimpMainAudio").GetComponent<AudioSource>();
			voiceAudio = GameObject.Find("ShrimpGrowlAudio").GetComponent<AudioSource>();
			voice2Audio = GameObject.Find("ShrimpAngerAudio").GetComponent<AudioSource>();
			lookRig = GameObject.Find("ShrimpLookAtPlayer").GetComponent<Rig>();
			lungLight = GameObject.Find("LungFlash").GetComponent<Light>();
			lungLight.intensity = 0f;
			AudioSource[] componentsInChildren = ((Component)((Component)this).transform).GetComponentsInChildren<AudioSource>();
			AudioSource[] array = componentsInChildren;
			foreach (AudioSource val in array)
			{
				val.outputAudioMixerGroup = GameObject.Find("StatusEffectAudio").GetComponent<AudioSource>().outputAudioMixerGroup;
			}
			lookTarget = GameObject.Find("Shrimp_Look_target").transform;
			dogHead = GameObject.Find("ShrimpLookPoint").transform;
			bittenObjectHolder = GameObject.Find("BittenObjectHolder").transform;
			shrimpEye = GameObject.Find("ShrimpEye").transform;
			scaleOfEyesNormally = leftEye.localScale;
			originalMouthScale = mouth.localScale;
			voice2Audio.clip = Plugin.dogSprint;
			voice2Audio.Play();
			base.creatureVoice = voice2Audio;
			base.creatureSFX = voice2Audio;
			base.eye = shrimpEye;
			SetupBehaviour();
			tempEnemyBehaviourStates.Add(roamingState);
			tempEnemyBehaviourStates.Add(followingPlayer);
			tempEnemyBehaviourStates.Add(enragedState);
			base.enemyBehaviourStates = tempEnemyBehaviourStates.ToArray();
			spawnPosition = ((Component)this).transform.position;
			roamMap = new AISearchRoutine();
			ItemElevatorCheck[] array2 = Object.FindObjectsOfType<ItemElevatorCheck>();
			ItemElevatorCheck[] array3 = array2;
			foreach (ItemElevatorCheck itemElevatorCheck in array3)
			{
				itemElevatorCheck.shrimpAI = this;
			}
			if (Plugin.setKorean)
			{
				((Component)((Component)this).transform.GetChild(1)).GetComponent<ScanNodeProperties>().headerText = "쉬림프";
			}
		}

		public IEnumerator stunnedTimer(PlayerControllerB playerWhoHit)
		{
			isHitted.Value = false;
			hittedPlayer = playerWhoHit;
			base.agent.speed = 0f;
			base.creatureAnimator.SetTrigger("Recoil");
			mainAudio.PlayOneShot(Plugin.cry1, 1f);
			yield return (object)new WaitForSeconds(0.5f);
			scaredBackingAway = 3f;
			yield return (object)new WaitForSeconds(2f);
			hittedPlayer = null;
		}

		private void StunTest()
		{
			//IL_0064: 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)
			if (scaredBackingAway > 0f)
			{
				if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
				{
					lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
					base.agent.SetDestination(((EnemyAI)this).ChooseFarthestNodeFromPosition(((Component)this).transform.position, true, 0, false).position);
				}
				base.creatureAnimator.SetFloat("walkSpeed", -3.5f);
				scaredBackingAway -= Time.deltaTime;
			}
		}

		public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			((EnemyAI)this).HitEnemy(force, playerWhoHit, false);
			if (hungerValue.Value < 60f && scaredBackingAway <= 0f)
			{
				isHitted.Value = true;
			}
		}

		public void FootStepSound()
		{
			randomVal = Random.Range(0, 20);
			if (randomVal < 5f)
			{
				mainAudio.PlayOneShot(Plugin.footstep1, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 10f)
			{
				mainAudio.PlayOneShot(Plugin.footstep2, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 15f)
			{
				mainAudio.PlayOneShot(Plugin.footstep3, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 20f)
			{
				mainAudio.PlayOneShot(Plugin.footstep4, Random.Range(0.8f, 1f));
			}
		}

		private IEnumerator DogSatisfied()
		{
			yield return (object)new WaitForSeconds(2f);
			canBeMoved = true;
			networkTargetPlayer.Value = null;
		}

		public override void Update()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0593: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_053c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Unknown result type (might be due to invalid IL or missing references)
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0571: Unknown result type (might be due to invalid IL or missing references)
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0600: Unknown result type (might be due to invalid IL or missing references)
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Unknown result type (might be due to invalid IL or missing references)
			//IL_062d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_063b: Unknown result type (might be due to invalid IL or missing references)
			//IL_064b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0650: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0450: Unknown result type (might be due to invalid IL or missing references)
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0804: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cb: 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_06d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0703: Unknown result type (might be due to invalid IL or missing references)
			//IL_0709: Unknown result type (might be due to invalid IL or missing references)
			//IL_0719: Unknown result type (might be due to invalid IL or missing references)
			//IL_074e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0754: Unknown result type (might be due to invalid IL or missing references)
			//IL_075e: Unknown result type (might be due to invalid IL or missing references)
			//IL_076e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0785: Unknown result type (might be due to invalid IL or missing references)
			//IL_078b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0795: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a5: Unknown result type (might be due to invalid IL or missing references)
			if (!isSatisfied)
			{
				CheckPlayer();
			}
			if ((Object)(object)networkTargetPlayer.Value != (Object)null)
			{
				GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
				foreach (GameObject val in allPlayerObjects)
				{
					float num = Vector3.Distance(((Component)this).transform.position, val.transform.position);
					if (num < float.PositiveInfinity && num > 80f)
					{
						networkTargetPlayer.Value = null;
					}
				}
			}
			base.targetPlayer = networkTargetPlayer.Value;
			SetByHunger();
			EatItem();
			CheckTargetAvailable();
			if (isHitted.Value)
			{
				((MonoBehaviour)this).StartCoroutine(stunnedTimer(base.targetPlayer));
			}
			if (((NetworkBehaviour)this).IsOwner)
			{
				((EnemyAI)this).SyncPositionToClients();
			}
			else
			{
				((EnemyAI)this).SetClientCalculatingAI(false);
			}
			if (ateLung)
			{
				lungLight.intensity = Mathf.Lerp(lungLight.intensity, 1500f, Time.deltaTime * 10f);
			}
			if (satisfyValue >= 21f && !isSatisfied)
			{
				canBeMoved = false;
				((MonoBehaviour)this).StartCoroutine(DogSatisfied());
				mainAudio.PlayOneShot(Plugin.dogSneeze);
				isSatisfied = true;
			}
			if (isSatisfied && satisfyValue > 0f)
			{
				satisfyValue -= Time.deltaTime;
				isSeenPlayer = false;
			}
			if (satisfyValue <= 0f && isSatisfied)
			{
				isSatisfied = false;
				satisfyValue = 0f;
			}
			if ((Object)(object)base.targetPlayer == (Object)null && !isNearestItem && (Object)(object)base.targetNode == (Object)null)
			{
				int num2 = Random.Range(1, base.allAINodes.Length);
				if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num2].transform.position) > 5f && SelectNode.Value != num2 && ((NetworkBehaviour)this).IsOwner && ((NetworkBehaviour)this).IsOwner)
				{
					SelectNode.Value = num2;
				}
			}
			if (stuckDetectionTimer > 3.5f)
			{
				int num3 = Random.Range(1, base.allAINodes.Length);
				if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num3].transform.position) > 5f && SelectNode.Value != num3)
				{
					if (((NetworkBehaviour)this).IsOwner)
					{
						SelectNode.Value = num3;
					}
					stuckDetectionTimer = 0f;
				}
				else if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num3].transform.position) > 5f)
				{
					stuckDetectionTimer = 0f;
				}
			}
			Vector3 velocity;
			if (((Object)(object)base.targetPlayer == (Object)null && !isNearestItem) || isSatisfied)
			{
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
				if ((Object)(object)base.targetNode != (Object)null)
				{
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(base.targetNode.position);
					}
					if (shrimpVelocity.Value < 0.5f)
					{
						stuckDetectionTimer += Time.deltaTime;
					}
					else
					{
						stuckDetectionTimer = 0f;
					}
					float num4 = 30f;
					Vector3 val2 = ((Component)this).transform.position - prevPosition;
					velocity = base.agent.velocity;
					float num5 = Vector3.Angle(val2, ((Vector3)(ref velocity)).normalized);
					if (num5 > num4)
					{
						Plugin.mls.LogInfo((object)("각도 차이가 " + num5 + "이며, " + num4 + " 이상 차이납니다."));
					}
					prevPosition = ((Component)this).transform.position;
				}
			}
			base.targetNode = base.allAINodes[SelectNode.Value].transform;
			if ((Object)(object)base.targetPlayer != (Object)null || isNearestItem)
			{
				dogRandomWalk = false;
				stuckDetectionTimer = 0f;
			}
			Quaternion rotation;
			if (((NetworkBehaviour)this).IsOwner)
			{
				networkPosition.Value = ((Component)this).transform.position;
				LethalNetworkVariable<Vector3> obj = networkRotation;
				rotation = ((Component)this).transform.rotation;
				obj.Value = ((Quaternion)(ref rotation)).eulerAngles;
				LethalNetworkVariable<float> obj2 = shrimpVelocity;
				velocity = base.agent.velocity;
				obj2.Value = ((Vector3)(ref velocity)).sqrMagnitude;
			}
			else
			{
				networkPosDistance = Vector3.Distance(((Component)this).transform.position, networkPosition.Value);
				if (networkPosDistance > 3f)
				{
					((Component)this).transform.position = networkPosition.Value;
					Plugin.mls.LogWarning((object)"Force the shrimp to change position.");
				}
				else
				{
					((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, networkPosition.Value, Time.deltaTime * 10f);
				}
				Transform transform = ((Component)this).transform;
				rotation = ((Component)this).transform.rotation;
				transform.rotation = Quaternion.Euler(Vector3.Lerp(((Quaternion)(ref rotation)).eulerAngles, networkRotation.Value, Time.deltaTime * 10f));
				if (networkPosDistance > 15f)
				{
					Plugin.mls.LogFatal((object)"Shrimp spawned successfully, but its current position is VERY different from the network position. This error is usually caused by low network quality or high traffic on the server.");
				}
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				isTargetAvailable = true;
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				if (hungerValue.Value < 55f)
				{
					leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
					rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
				}
				else if (hungerValue.Value > 55f)
				{
					leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally * 0.4f, 20f * Time.deltaTime);
					rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally * 0.4f, 20f * Time.deltaTime);
				}
			}
			else
			{
				leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
				rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
			}
			base.creatureAnimator.SetBool("DogRandomWalk", dogRandomWalk);
			if (canBeMoved && !isRunning)
			{
				base.creatureAnimator.SetBool("Running", false);
				base.agent.speed = 5.5f;
				base.agent.acceleration = 7f;
				base.agent.angularSpeed = 150f;
			}
			else if (!canBeMoved && !isRunning)
			{
				base.creatureAnimator.SetBool("Running", false);
				base.agent.speed = 0f;
				base.agent.angularSpeed = 0f;
			}
			if (isRunning)
			{
				base.creatureAnimator.SetBool("Running", true);
				base.agent.speed = Mathf.Lerp(base.agent.speed, 15f, Time.deltaTime * 2f);
				base.agent.angularSpeed = 10000f;
				base.agent.acceleration = 50f;
			}
			StunTest();
		}

		private IEnumerator SyncRotation()
		{
			Transform transform = ((Component)this).transform;
			Quaternion rotation = ((Component)this).transform.rotation;
			transform.rotation = Quaternion.Euler(Vector3.Lerp(((Quaternion)(ref rotation)).eulerAngles, networkRotation.Value, Time.deltaTime * 10f));
			yield return (object)new WaitForSeconds(1f);
		}

		private float CalculateRotationDifference(Vector3 rotation1, Vector3 rotation2)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: 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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Quaternion val = Quaternion.Euler(rotation1);
			Quaternion val2 = Quaternion.Euler(rotation2);
			return Quaternion.Angle(val, val2);
		}

		private void CheckPlayer()
		{
			//IL_0226: 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_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: 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_020b: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = ((EnemyAI)this).CheckLineOfSightForPlayer(40f, 40, -1);
			if ((Object)(object)val != (Object)null && (Object)(object)base.targetPlayer == (Object)null && !isKillingPlayer)
			{
				if (!isSeenPlayer)
				{
					mainAudio.PlayOneShot(Plugin.dogHowl);
					base.creatureAnimator.SetTrigger("Walk");
					isSeenPlayer = true;
				}
				networkTargetPlayer.Value = val;
			}
			if (droppedItems.Count > 0 && (Object)(object)nearestDroppedItem == (Object)null)
			{
				FindNearestItem();
			}
			footStepTime += Time.deltaTime * shrimpVelocity.Value / 8f;
			if ((double)footStepTime > 0.5)
			{
				FootStepSound();
				footStepTime = 0f;
			}
			base.creatureAnimator.SetFloat("walkSpeed", Mathf.Clamp(shrimpVelocity.Value / 5f, 0f, 3f));
			base.creatureAnimator.SetFloat("runSpeed", Mathf.Clamp(shrimpVelocity.Value / 2.7f, 3f, 4f));
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				if (!isNearestItem && scaredBackingAway <= 0f)
				{
					if (hungerValue.Value > 55f)
					{
						lookRay = new Ray(dogHead.position, ((Component)base.targetPlayer).transform.position - dogHead.position);
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Ray)(ref lookRay)).GetPoint(3f), 30f * Time.deltaTime);
					}
					else
					{
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Component)base.targetPlayer.lowerSpine).transform.position, 6f * Time.deltaTime);
					}
				}
				base.agent.autoBraking = true;
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0.5f, Time.deltaTime);
				dogRandomWalk = false;
				if (!isSeenPlayer)
				{
					mainAudio.PlayOneShot(Plugin.dogHowl, 1f);
				}
				isSeenPlayer = true;
			}
			if (!isRunning && !isNearestItem)
			{
				base.agent.stoppingDistance = 4.5f;
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
			}
			else
			{
				base.agent.stoppingDistance = 0.5f;
			}
			if (!isNearestItem)
			{
			}
		}

		private void SetByHunger()
		{
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0556: Unknown result type (might be due to invalid IL or missing references)
			//IL_0566: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: 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)
			if (hungerValue.Value < 66f)
			{
				if (isSeenPlayer && !isTargetAvailable && ((NetworkBehaviour)this).IsOwner)
				{
					LethalNetworkVariable<float> obj = hungerValue;
					obj.Value += Time.deltaTime * 0.09f;
				}
				else if (isSeenPlayer && isTargetAvailable && ((NetworkBehaviour)this).IsOwner)
				{
					LethalNetworkVariable<float> obj2 = hungerValue;
					obj2.Value += Time.deltaTime;
				}
			}
			if (hungerValue.Value > 55f && hungerValue.Value < 60f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 1f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				voiceAudio.loop = true;
				voiceAudio.clip = Plugin.stomachGrowl;
				if (!voiceAudio.isPlaying)
				{
					voiceAudio.Play();
				}
			}
			else if (hungerValue.Value < 63f && hungerValue.Value >= 60f && !isEnraging)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0.8f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				isEnraging = true;
				voiceAudio.clip = Plugin.bigGrowl;
				if (!voiceAudio.isPlaying)
				{
					voiceAudio.Play();
				}
			}
			else if (hungerValue.Value < 63f && hungerValue.Value > 60f && isEnraging)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 1f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				if (!isNearestItem)
				{
					canBeMoved = false;
				}
			}
			else if (hungerValue.Value < 55f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 0f, 125f * Time.deltaTime);
			}
			else if (hungerValue.Value > 63f && !isAngered)
			{
				if (!isNearestItem && !isKillingPlayer && base.stunNormalizedTimer <= 0f)
				{
					canBeMoved = true;
				}
				voiceAudio.clip = Plugin.enragedScream;
				voiceAudio.Play();
				isEnraging = false;
				isAngered = true;
			}
			else if (hungerValue.Value > 65f)
			{
				base.openDoorSpeedMultiplier = 1.5f;
				isRunning = true;
				voice2Audio.volume = Mathf.Lerp(voice2Audio.volume, 1f, 125f * Time.deltaTime);
			}
			else if (hungerValue.Value > 63f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0.8f, 45f * Time.deltaTime);
				mouth.localScale = Vector3.Lerp(mouth.localScale, new Vector3(0.005590725f, 0.01034348f, 0.02495567f), 30f * Time.deltaTime);
			}
			if (hungerValue.Value < 60f)
			{
				isEnraging = false;
				isAngered = false;
				if (!isNearestItem && !isKillingPlayer && base.stunNormalizedTimer <= 0f)
				{
					canBeMoved = true;
				}
			}
			if (hungerValue.Value < 66f)
			{
				isRunning = false;
				base.openDoorSpeedMultiplier = 0.3f;
			}
			if (hungerValue.Value < 63f)
			{
				mouth.localScale = Vector3.Lerp(mouth.localScale, originalMouthScale, 20f * Time.deltaTime);
				voice2Audio.volume = Mathf.Lerp(voice2Audio.volume, 0f, 125f * Time.deltaTime);
				isRunning = false;
			}
			if (hungerValue.Value > 64f && networkTargetPlayerDistance < 3.5f && !isKillingPlayer && (Object)(object)base.targetPlayer != (Object)null && !base.targetPlayer.isCameraDisabled)
			{
				KillingPlayerBool.Value = true;
			}
			if (KillingPlayerBool.Value)
			{
				if (!base.targetPlayer.isCameraDisabled)
				{
					Plugin.mls.LogInfo((object)("Shrimp: (Owner) Killing " + ((Object)base.targetPlayer).name + "!"));
					((MonoBehaviour)this).StartCoroutine(KillPlayer(base.targetPlayer));
					KillingPlayerBool.Value = false;
				}
				else if (base.targetPlayer.isCameraDisabled)
				{
					Plugin.mls.LogInfo((object)("Shrimp: (Not Owner) Killing " + ((Object)base.targetPlayer).name + "!"));
					((MonoBehaviour)this).StartCoroutine(KillPlayerInOtherClient(base.targetPlayer));
					KillingPlayerBool.Value = false;
				}
			}
			if (isKillingPlayer)
			{
				canBeMoved = false;
			}
		}

		private void EatItem()
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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_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_0082: 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_00a3: 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_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)nearestDroppedItem != (Object)null)
			{
				if (isNearestItem && !nearestDroppedItem.GetComponent<GrabbableObject>().isHeld)
				{
					if (hungerValue.Value < 55f)
					{
						lookRay = new Ray(dogHead.position, nearestDroppedItem.transform.position - dogHead.position);
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Ray)(ref lookRay)).GetPoint(1.8f), 6f * Time.deltaTime);
					}
					else
					{
						lookTarget.position = Vector3.Lerp(lookTarget.position, nearestDroppedItem.transform.position, 6f * Time.deltaTime);
					}
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(nearestDroppedItem.transform.position);
					}
					nearestItemDistance = Vector3.Distance(((Component)this).transform.position, nearestDroppedItem.transform.position);
					if (nearestItemDistance < 1.35f)
					{
						canBeMoved = false;
						isRunning = false;
						nearestDroppedItem.transform.SetParent(((Component)this).transform, true);
						if ((Object)(object)nearestDroppedItem.GetComponent<LungProp>() != (Object)null)
						{
							satisfyValue += 30f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj = hungerValue;
								obj.Value -= 50f;
							}
							ateLung = true;
							((Behaviour)nearestDroppedItem.GetComponentInChildren<Light>()).enabled = false;
						}
						else if ((Object)(object)nearestDroppedItem.GetComponent<StunGrenadeItem>() != (Object)null)
						{
							StunGrenadeItem component = nearestDroppedItem.GetComponent<StunGrenadeItem>();
							component.hasExploded = true;
							((MonoBehaviour)this).StartCoroutine(EatenFlashbang());
						}
						base.creatureAnimator.SetTrigger("eat");
						mainAudio.PlayOneShot(Plugin.dogEatItem);
						isNearestItem = false;
						nearestItemDistance = 500f;
						if (nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight > 1f)
						{
							satisfyValue += Mathf.Clamp(nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight - 1f, 0f, 100f) * 150f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj2 = hungerValue;
								obj2.Value -= Mathf.Clamp(nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight - 1f, 0f, 100f) * 230f;
							}
						}
						else
						{
							satisfyValue += 6f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj3 = hungerValue;
								obj3.Value -= 12f;
							}
						}
						GrabbableObject component2 = nearestDroppedItem.GetComponent<GrabbableObject>();
						component2.grabbable = false;
						component2.grabbableToEnemies = false;
						component2.deactivated = true;
						if ((Object)(object)component2.radarIcon != (Object)null)
						{
							Object.Destroy((Object)(object)((Component)component2.radarIcon).gameObject);
						}
						MeshRenderer[] componentsInChildren = ((Component)component2).gameObject.GetComponentsInChildren<MeshRenderer>();
						for (int i = 0; i < componentsInChildren.Length; i++)
						{
							Object.Destroy((Object)(object)componentsInChildren[i]);
						}
						Collider[] componentsInChildren2 = ((Component)component2).gameObject.GetComponentsInChildren<Collider>();
						for (int j = 0; j < componentsInChildren2.Length; j++)
						{
							Object.Destroy((Object)(object)componentsInChildren2[j]);
						}
						droppedItems.Remove(nearestDroppedItem);
						nearestDroppedItem = null;
					}
					else if (!isKillingPlayer && base.stunNormalizedTimer <= 0f)
					{
						canBeMoved = true;
					}
				}
				else if ((Object)(object)base.targetPlayer != (Object)null && !isSatisfied)
				{
					nearestDroppedItem = null;
					nearestItemDistance = 3000f;
					isNearestItem = false;
				}
			}
			if (base.stunNormalizedTimer > 0f)
			{
				canBeMoved = false;
				base.creatureAnimator.SetBool("Stun", true);
			}
			else
			{
				base.creatureAnimator.SetBool("Stun", false);
			}
		}

		private void CheckTargetAvailable()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			if ((networkTargetPlayerDistance <= 12f || Object.op_Implicit((Object)(object)((EnemyAI)this).CheckLineOfSightForPlayer(40f, 40, -1))) && !isNearestItem && !isKillingPlayer && scaredBackingAway <= 0f)
			{
				followTimer = 10f;
				canBeMoved = true;
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				networkTargetPlayerDistance = Vector3.Distance(((Component)this).transform.position, ((Component)base.targetPlayer).transform.position);
			}
			else
			{
				networkTargetPlayerDistance = 3000f;
			}
			if ((followTimer > 0f || networkTargetPlayerDistance < 10f) && !isSatisfied)
			{
				if (isTargetAvailable && scaredBackingAway <= 0f && !isNearestItem && ((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
				{
					base.agent.SetDestination(((Component)base.targetPlayer).transform.position);
				}
				if ((Object)(object)nearestDroppedItem != (Object)null && nearestDroppedItem.GetComponent<GrabbableObject>().isHeld)
				{
					nearestDroppedItem.GetComponent<ItemElevatorCheck>().dogEatTimer = 5f;
					droppedItems.Remove(nearestDroppedItem);
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(((Component)base.targetPlayer).transform.position);
					}
					nearestDroppedItem = null;
					nearestItemDistance = 3000f;
					isNearestItem = false;
				}
			}
			if ((((Object)(object)base.targetPlayer != (Object)null && networkTargetPlayerDistance > 12f) || !Object.op_Implicit((Object)(object)((EnemyAI)this).CheckLineOfSightForPlayer(40f, 30, -1))) && followTimer > 0f)
			{
				followTimer -= Time.deltaTime;
			}
			if ((Object)(object)base.targetPlayer == (Object)null)
			{
				followTimer = 10f;
			}
			if (followTimer <= 0f)
			{
				networkTargetPlayer.Value = null;
				base.targetPlayer = null;
				isTargetAvailable = false;
			}
		}

		private bool IsPlayerVisible(PlayerControllerB player)
		{
			//IL_0007: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)player).transform.position - ((Component)this).transform.position;
			float num = Vector3.Angle(((Component)this).transform.forward, val);
			if (num < 35f && Physics.Raycast(((Component)this).transform.position, val, 120f, LayerMask.NameToLayer("Player")))
			{
				return true;
			}
			return false;
		}

		private void FindNearestItem()
		{
			//IL_001f: 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)
			foreach (GameObject droppedItem in droppedItems)
			{
				float num = Vector3.Distance(((Component)this).transform.position, droppedItem.transform.position);
				if (num < float.PositiveInfinity && num < 30f)
				{
					nearestDroppedItem = droppedItem;
					isNearestItem = true;
					return;
				}
			}
			isNearestItem = false;
		}

		private IEnumerator EatenFlashbang()
		{
			yield return (object)new WaitForSeconds(2f);
			mainAudio.PlayOneShot(Plugin.eatenExplode);
		}

		private void KillPlayerTrigger(PlayerControllerB killPlayer)
		{
			if (!killPlayer.isCameraDisabled)
			{
				((MonoBehaviour)this).StartCoroutine(KillPlayer(killPlayer));
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(KillPlayerInOtherClient(killPlayer));
			}
		}

		private IEnumerator KillPlayer(PlayerControllerB killPlayer)
		{
			hungerValue.Value = 0f;
			Plugin.mls.LogInfo((object)("Shrimp: Killing " + ((Object)killPlayer).name + "!"));
			yield return (object)new WaitForSeconds(0.05f);
			isKillingPlayer = true;
			base.creatureAnimator.SetTrigger("RipObject");
			mainAudio.PlayOneShot(Plugin.ripPlayerApart);
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)killPlayer)
			{
				killPlayer.KillPlayer(Vector3.zero, true, (CauseOfDeath)6, 0);
			}
			yield return (object)new WaitForSeconds(0.1f);
			if ((Object)(object)killPlayer.deadBody == (Object)null)
			{
				Debug.Log((object)"Shrimp: Player body was not spawned or found within 0.5 seconds.");
				killPlayer.inAnimationWithEnemy = null;
				isKillingPlayer = false;
				KillingPlayerBool.Value = false;
			}
			else
			{
				TakeBodyInMouth(killPlayer.deadBody);
				yield return (object)new WaitForSeconds(4.4f);
				base.creatureAnimator.SetTrigger("eat");
				mainAudio.PlayOneShot(Plugin.dogEatItem);
				((Component)killPlayer.deadBody).gameObject.SetActive(false);
				yield return (object)new WaitForSeconds(2f);
				isKillingPlayer = false;
			}
		}

		private IEnumerator KillPlayerInOtherClient(PlayerControllerB killPlayer)
		{
			Plugin.mls.LogInfo((object)("Shrimp: Killing " + ((Object)killPlayer).name + "!"));
			hungerValue.Value = 0f;
			yield return (object)new WaitForSeconds(0.05f);
			isKillingPlayer = true;
			base.creatureAnimator.SetTrigger("RipObject");
			mainAudio.PlayOneShot(Plugin.ripPlayerApart);
			yield return (object)new WaitForSeconds(0.1f);
			if ((Object)(object)killPlayer.deadBody == (Object)null)
			{
				Debug.Log((object)"Shrimp: Player body was not spawned or found within 0.5 seconds.");
				killPlayer.inAnimationWithEnemy = null;
				isKillingPlayer = false;
				KillingPlayerBool.Value = false;
			}
			else
			{
				TakeBodyInMouth(killPlayer.deadBody);
				yield return (object)new WaitForSeconds(4.4f);
				base.creatureAnimator.SetTrigger("eat");
				mainAudio.PlayOneShot(Plugin.dogEatItem);
				((Component)killPlayer.deadBody).gameObject.SetActive(false);
				yield return (object)new WaitForSeconds(2f);
				isKillingPlayer = false;
			}
		}

		private void TakeBodyInMouth(DeadBodyInfo body)
		{
			body.attachedTo = bittenObjectHolder;
			body.attachedLimb = body.bodyParts[5];
			body.matchPositionExactly = true;
		}

		private void SetupBehaviour()
		{
			roamingState.name = "Roaming";
			roamingState.boolValue = true;
			followingPlayer.name = "Following";
			followingPlayer.boolValue = true;
			enragedState.name = "Enraged";
			enragedState.boolValue = true;
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("Start")]
		private static void Start_Prefix(Terminal __instance, ref List<TerminalNode> ___enemyFiles)
		{
			___enemyFiles.Add(Plugin.shrimpTerminalNode);
			TerminalKeyword defaultVerb = __instance.terminalNodes.allKeywords.First((TerminalKeyword x) => x.word == "info");
			TerminalKeyword shrimpTerminalKeyword = Plugin.shrimpTerminalKeyword;
			shrimpTerminalKeyword.defaultVerb = defaultVerb;
		}
	}
	public class TrapRoomTrigger : NetworkBehaviour
	{
		public LethalClientMessage<bool> SendTrapFloorTrigger = new LethalClientMessage<bool>("SendTrapFloorTrigger", (Action<bool>)null, (Action<bool, ulong>)null);

		public LethalClientMessage<bool> SendTrapDeactivate = new LethalClientMessage<bool>("SendTrapDeactivate", (Action<bool>)null, (Action<bool, ulong>)null);

		public AudioSource floorAudioSource;

		public AudioSource floorAudioSource2;

		public AudioSource doorAudioSource;

		public Animator roomAnimator;

		public bool isPlayed;

		public bool isPlayedOnce;

		public bool isDeactivated;

		public PlayerControllerB[] players;

		public float Timer;

		private void SendTrapFloorTriggerSync(bool value, ulong id)
		{
			if (value && !isPlayed)
			{
				isPlayed = true;
			}
			else if (!value && isPlayed)
			{
				isPlayed = false;
			}
		}

		private void SendTrapDeactivateSync(bool value, ulong id)
		{
			if (value && !isDeactivated)
			{
				isDeactivated = true;
			}
			else if (!value && isDeactivated)
			{
				isDeactivated = false;
			}
		}

		private void Start()
		{
			SendTrapFloorTrigger.OnReceivedFromClient += SendTrapFloorTriggerSync;
			SendTrapDeactivate.OnReceivedFromClient += SendTrapDeactivateSync;
			roomAnimator = GameObject.Find("TrapDoorAnimator").GetComponent<Animator>();
			floorAudioSource = GameObject.Find("Floor1").GetComponent<AudioSource>();
			floorAudioSource2 = GameObject.Find("Floor2").GetComponent<AudioSource>();
			doorAudioSource = GameObject.Find("DoorSlam").GetComponent<AudioSource>();
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("TrapTrigger").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)TriggerTrap);
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("IgnoreFallDamagePlayer").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)IgnoreFallDamage);
			((UnityEvent<PlayerControllerB>)(object)((Component)this).GetComponent<TerminalAccessibleObject>().terminalCodeEvent).AddListener((UnityAction<PlayerControllerB>)DeactivateTrap);
		}

		private void Update()
		{
			if (isPlayed && !isPlayedOnce && !isDeactivated)
			{
				((MonoBehaviour)this).StartCoroutine(ActivateTrap());
				isPlayed = false;
				isPlayedOnce = true;
			}
			if (!isPlayed && isDeactivated && isPlayedOnce)
			{
				((MonoBehaviour)this).StartCoroutine(DeactivateTrapCoroutine());
				isDeactivated = false;
			}
		}

		public void TriggerTrap(PlayerControllerB playerControllerB)
		{
			SendTrapFloorTrigger.SendAllClients(true, true, false);
		}

		public void IgnoreFallDamage(PlayerControllerB playerControllerB)
		{
			playerControllerB.fallValue -= 5f;
		}

		public void DeactivateTrap(PlayerControllerB playerControllerB)
		{
			SendTrapDeactivate.SendAllClients(true, true, false);
		}

		private IEnumerator ActivateTrap()
		{
			roomAnimator.SetBool("open", true);
			doorAudioSource.PlayOneShot(Plugin.garageDoorSlam);
			yield return (object)new WaitForSeconds(3f);
			doorAudioSource.PlayOneShot(Plugin.floorOpen);
		}

		private IEnumerator DeactivateTrapCoroutine()
		{
			roomAnimator.SetBool("unlock", true);
			doorAudioSource.PlayOneShot(Plugin.floorClose);
			yield return (object)new WaitForSeconds(1f);
			doorAudioSource.PlayOneShot(Plugin.garageSlide);
		}
	}
	public class StanleyTrigger : MonoBehaviour
	{
		public AudioSource audioSource;

		public bool isPlayed;

		private void Start()
		{
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("Stanley").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)TriggerStanley);
			audioSource = GameObject.Find("NarratorAudio").GetComponent<AudioSource>();
		}

		public void TriggerStanley(PlayerControllerB playerControllerB)
		{
			if (!isPlayed)
			{
				((MonoBehaviour)this).StartCoroutine(PlayVoice1());
				isPlayed = true;
			}
		}

		private IEnumerator PlayVoice1()
		{
			yield return (object)new WaitForSeconds(3f);
			audioSource.PlayOneShot(Plugin.stanleyVoiceline1);
		}
	}
	public class ElevatorMusic : MonoBehaviour
	{
		public AudioSource audioSource;

		public int currentMusic;

		public float musicPlayTimer;

		private void Start()
		{
			audioSource = ((Component)this).GetComponent<AudioSource>();
			audioSource.PlayOneShot(Plugin.bossaLullaby);
			musicPlayTimer = 0f;
			currentMusic = 1;
		}

		private void Update()
		{
			if (audioSource.isPlaying)
			{
				return;
			}
			musicPlayTimer += Time.deltaTime;
			if (musicPlayTimer > 0.5f)
			{
				if (currentMusic == 0)
				{
					audioSource.PlayOneShot(Plugin.bossaLullaby);
					musicPlayTimer = 0f;
					currentMusic++;
				}
				else if (currentMusic == 1)
				{
					audioSource.PlayOneShot(Plugin.shopTheme);
					musicPlayTimer = 0f;
					currentMusic++;
				}
				else if (currentMusic == 2)
				{
					audioSource.PlayOneShot(Plugin.saferoomTheme);
					musicPlayTimer = 0f;
					currentMusic = 0;
				}
			}
		}
	}
	public class ElevatorCollider : NetworkBehaviour
	{
		public Bounds checkBounds;

		public LethalClientMessage<bool> SendInElevator = new LethalClientMessage<bool>("SendInElevator", (Action<bool>)null, (Action<bool, ulong>)IsInElevatorSync);

		public List<GameObject> allPlayerColliders = new List<GameObject>();

		public Transform storageParent;

		public Transform lungPlacement;

		public Vector3 tempTargetFloorPosition;

		public Vector3 tempStartFallingPosition;

		private static void IsInElevatorSync(bool value, ulong id)
		{
			if (value)
			{
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().wasInElevator = true;
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner = true;
			}
			else
			{
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner = false;
			}
		}

		private void Start()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			((Bounds)(ref checkBounds)).size = new Vector3(4.9f, 17f, 4.9f);
			GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
			foreach (GameObject item in allPlayerObjects)
			{
				allPlayerColliders.Add(item);
			}
			lungPlacement = ((Component)Object.FindObjectOfType<PlaceLung>()).transform;
		}

		private void Update()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: 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_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_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			((Bounds)(ref checkBounds)).center = ((Component)this).transform.position;
			foreach (GameObject allPlayerCollider in allPlayerColliders)
			{
				if (!((Object)(object)allPlayerCollider.GetComponent<Collider>() != (Object)null))
				{
					continue;
				}
				BoxCollider component = allPlayerCollider.GetComponent<BoxCollider>();
				if (((Bounds)(ref checkBounds)).Intersects(((Collider)component).bounds))
				{
					if (((Component)component).gameObject.tag == "Player")
					{
						PlayerControllerB component2 = ((Component)component).GetComponent<PlayerControllerB>();
						PlayerElevatorCheck component3 = ((Component)component).GetComponent<PlayerElevatorCheck>();
						if (!((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB && !component2.isCameraDisabled)
						{
							((Component)component).transform.SetParent(((Component)this).transform.parent);
							SendInElevator.SendAllClients(true, true, false);
							component3.wasInElevator = true;
							component3.isInElevatorB = true;
						}
					}
					else if (((Component)component).gameObject.tag == "PhysicsProp")
					{
						if ((Object)(object)((Component)component).GetComponent<GrabbableObject>().playerHeldBy != (Object)null && ((Component)((Component)component).GetComponent<GrabbableObject>().playerHeldBy).GetComponent<PlayerElevatorCheck>().isInElevatorB)
						{
							tempTargetFloorPosition = ((Component)((Component)component).GetComponent<GrabbableObject>().playerHeldBy).transform.localPosition;
							tempStartFallingPosition = ((Component)((Component)component).GetComponent<GrabbableObject>()).transform.localPosition;
						}
						if (!((Component)component).GetComponent<ItemElevatorCheck>().isInElevatorB && ((Object)(object)((Component)component).transform.parent != (Object)(object)storageParent || (Object)(object)((Component)component).transform.parent != (Object)(object)lungPlacement))
						{
							((Component)component).transform.parent = ((Component)this).transform.parent;
							((Component)component).GetComponent<GrabbableObject>().targetFloorPosition = tempTargetFloorPosition;
							((Component)component).GetComponent<GrabbableObject>().startFallingPosition = tempStartFallingPosition;
							((Component)component).GetComponent<ItemElevatorCheck>().isInElevatorB = true;
						}
					}
					continue;
				}
				if (((Component)component).gameObject.tag == "Player")
				{
					if (((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB)
					{
						((Component)component).transform.SetParent(StartOfRound.Instance.playersContainer, true);
						SendInElevator.SendAllClients(false, true, false);
						((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB = false;
					}
					else if (((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB && ((Component)component).GetComponent<PlayerControllerB>().isCameraDisabled && !((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner)
					{
						((Component)component).transform.SetParent((Transform)null, true);
						((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB = false;
					}
				}
				if ((Object)(object)allPlayerCollider.GetComponent<PlayerControllerB>() != (Object)null)
				{
					PlayerControllerB component4 = ((Component)component).GetComponent<PlayerControllerB>();
					PlayerElevatorCheck component5 = ((Component)component).GetComponent<PlayerElevatorCheck>();
					if (!component5.isInElevatorB && component4.isCameraDisabled && component5.isInElevatorNotOwner)
					{
						Plugin.mls.LogInfo((object)(component4.actualClientId + " is inside of elevator check!"));
						((Component)component).transform.SetParent(((Component)this).transform.parent, true);
						component5.isInElevatorB = true;
						component5.wasInElevator = true;
					}
					else if (component5.isInElevatorB && component4.isCameraDisabled && !component5.isInElevatorNotOwner)
					{
						Plugin.mls.LogInfo((object)(component4.actualClientId + " is outside of elevator check!"));
						((Component)component).transform.SetParent((Transform)null, true);
						component5.isInElevatorB = false;
					}
				}
			}
		}
	}
	public class ElevatorSystem : NetworkBehaviour
	{
		public static LethalNetworkVariable<bool> isElevatorDowned = new LethalNetworkVariable<bool>("isElevatorDowned");

		public static LethalNetworkVariable<bool> isElevatorClosed = new LethalNetworkVariable<bool>("isElevatorClosed");

		public float elevatorTimer;

		public static LethalNetworkVariable<bool> spawnShrimpBool = new LethalNetworkVariable<bool>("spawnShrimpBool");

		public Animator doorAnimator;

		public Animator elevatorScreenDoorAnimator;

		public Animator animator;

		public AudioSource audioSource;

		public List<Animator> panelAnimators;

		public List<Animator> buttonLightAnimators;

		public bool performanceCheck;

		public GameObject storageObject;

		public bool isSetupEnd;

		private void Start()
		{
			isElevatorDowned.Value = false;
			isElevatorClosed.Value = false;
			spawnShrimpBool.Value = false;
		}

		private void LateUpdate()
		{
			//IL_00bd: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Setup();
			AnimatorStateInfo currentAnimatorStateInfo;
			if (isElevatorClosed.Value)
			{
				if (doorAnimator.GetBool("closed"))
				{
					audioSource.PlayOneShot(Plugin.ElevatorClose);
				}
				elevatorScreenDoorAnimator.SetBool("open", false);
				doorAnimator.SetBool("closed", false);
			}
			else
			{
				if (!doorAnimator.GetBool("closed"))
				{
					audioSource.PlayOneShot(Plugin.ElevatorOpen);
				}
				if (!isElevatorDowned.Value)
				{
					currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
					if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 0.4f)
					{
						currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
						if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime < 1f)
						{
							elevatorScreenDoorAnimator.SetBool("open", true);
						}
					}
				}
				doorAnimator.SetBool("closed", true);
			}
			if (isElevatorDowned.Value && !animator.GetBool("goDown"))
			{
				elevatorTimer += Time.deltaTime;
				foreach (Animator buttonLightAnimator in buttonLightAnimators)
				{
					buttonLightAnimator.SetBool("up", false);
				}
				if (elevatorTimer > 0f)
				{
					if (!isElevatorClosed.Value)
					{
						isElevatorClosed.Value = true;
					}
					if (elevatorTimer > 3f)
					{
						audioSource.PlayOneShot(Plugin.ElevatorDown);
						animator.SetBool("goDown", true);
						if (!isElevatorDowned.Value)
						{
							isElevatorDowned.Value = true;
						}
					}
				}
			}
			if (!isElevatorDowned.Value && animator.GetBool("goDown"))
			{
				foreach (Animator buttonLightAnimator2 in buttonLightAnimators)
				{
					buttonLightAnimator2.SetBool("up", true);
				}
				elevatorTimer += Time.deltaTime;
				if (elevatorTimer > 0f)
				{
					isElevatorClosed.Value = true;
					if (elevatorTimer > 3f)
					{
						audioSource.PlayOneShot(Plugin.ElevatorUp);
						animator.SetBool("goDown", false);
						if (!isElevatorDowned.Value)
						{
							isElevatorDowned.Value = false;
						}
					}
				}
			}
			if (!isElevatorClosed.Value)
			{
				return;
			}
			currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime < 1f))
			{
				return;
			}
			currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime >= 0.98f))
			{
				return;
			}
			foreach (Animator panelAnimator in panelAnimators)
			{
				if (Plugin.setKorean)
				{
					((Component)((Component)panelAnimator).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "대기 중";
				}
				else
				{
					((Component)((Component)panelAnimator).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "Idle";
				}
			}
			if (isElevatorClosed.Value)
			{
				isElevatorClosed.Value = false;
				elevatorTimer = 0f;
			}
		}

		private void Setup()
		{
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			if (isSetupEnd)
			{
				return;
			}
			animator = ((Component)((Component)this).transform.GetChild(0)).GetComponent<Animator>();
			audioSource = GameObject.Find("ElevatorSound").GetComponent<AudioSource>();
			doorAnimator = GameObject.Find("DoorBone").GetComponent<Animator>();
			elevatorScreenDoorAnimator = GameObject.Find("ElevatorScreenDoor").GetComponent<Animator>();
			Animator[] array = Object.FindObjectsOfType<Animator>();
			Animator[] array2 = array;
			foreach (Animator val in array2)
			{
				if (!(((Object)((Component)val).gameObject).name == "ElevatorPanel"))
				{
					continue;
				}
				((UnityEvent<PlayerControllerB>)(object)((Component)((Component)val).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)ElevatorUpTrigger);
				((UnityEvent<PlayerControllerB>)(object)((Component)((Component)val).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)ElevatorDownTrigger);
				((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>();
				((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().font = GameObject.Find("doorHydraulics").GetComponent<TMP_Text>().font;
				((Graphic)((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>()).material = ((Graphic)GameObject.Find("doorHydraulics").GetComponent<TMP_Text>()).material;
				((Graphic)((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>()).color = new Color(1f, 0.3444f, 0f, 1f);
				if (!PlaceLung.emergencyPowerRequires || PlaceLung.lungPlaced)
				{
					if (Plugin.setKorean)
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "대기 중";
					}
					else
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "Idle";
					}
				}
				else if (PlaceLung.emergencyPowerRequires && !PlaceLung.lungPlaced)
				{
					if (Plugin.setKorean)
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "전력 없음";
					}
					else
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "No Power";
					}
				}
				panelAnimators.Add(val);
			}
			Animator[] array3 = array;
			foreach (Animator val2 in array3)
			{
				if (((Object)((Component)val2).gameObject).name == "ButtonLights")
				{
					buttonLightAnimators.Add(val2);
				}
			}
			GameObject.Find("InsideCollider").gameObject.AddComponent<ElevatorCollider>();
			GameObject.Find("ElevatorMusic").AddComponent<ElevatorMusic>();
			ScanNodeProperties[] array4 = Object.FindObjectsOfType<ScanNodeProperties>();
			if (Plugin.setKorean)
			{
				ScanNodeProperties[] array5 = array4;
				foreach (ScanNodeProperties val3 in array5)
				{
					if (val3.headerText == "Elevator Controller")
					{
						val3.headerText = "엘리베이터 제어기";
					}
					if (val3.headerText == "Auxiliary power unit")
					{
						val3.headerText = "보조 동력 장치";
						val3.subText = "긴급 전력 공급기";
					}
				}
			}
			if (GameNetworkManager.Instance.isHostingGame)
			{
				GameObject val4 = Object.Instantiate<GameObject>(Plugin.socketInteractPrefab);
				val4.GetComponent<NetworkObject>().Spawn(false);
			}
			isElevatorDowned.Value = false;
			isElevatorClosed.Value = false;
			spawnShrimpBool.Value = false;
			isSetupEnd = true;
		}

		public void ElevatorUpTrigger(PlayerControllerB playerController)
		{
			//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)
			Plugin.mls.LogInfo((object)"pressed up button!");
			if (!isElevatorDowned.Value)
			{
				return;
			}
			AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime >= 1f))
			{
				return;
			}
			foreach (Animator panelAnimator 

plugins/LethalLevelLoader.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLevelLoader.NetcodePatcher;
using LethalLevelLoader.Tools;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("LethalLevelLoader")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A Custom API to support the manual and dynamic integration of custom levels and dungeons in Lethal Company.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+99e1e0f233232ae52ea829f2f29e91ba47ab5680")]
[assembly: AssemblyProduct("LethalLevelLoader")]
[assembly: AssemblyTitle("LethalLevelLoader")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public enum ContentType
{
	Vanilla,
	Custom,
	Any
}
internal static class HookHelper
{
	public class DisposableHookCollection
	{
		private List<ILHook> ilHooks = new List<ILHook>();

		private List<Hook> hooks = new List<Hook>();

		public void Clear()
		{
			foreach (Hook hook in hooks)
			{
				hook.Dispose();
			}
			hooks.Clear();
			foreach (ILHook ilHook in ilHooks)
			{
				ilHook.Dispose();
			}
			ilHooks.Clear();
		}

		public void ILHook<T>(string methodName, Manipulator to, Type[] parameters = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			ilHooks.Add(new ILHook((MethodBase)EzGetMethod<T>(methodName, parameters), to));
		}

		public void Hook<T>(string methodName, Delegate to, Type[] parameters = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			hooks.Add(new Hook((MethodBase)EzGetMethod<T>(methodName, parameters), to));
		}
	}

	public static MethodInfo methodof(Delegate method)
	{
		return method.Method;
	}

	public static MethodInfo EzGetMethod(Type type, string name, Type[] parameters = null)
	{
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		if (parameters == null)
		{
			return type.GetMethod(name, bindingAttr);
		}
		return type.GetMethod(name, bindingAttr, null, parameters, null);
	}

	public static MethodInfo EzGetMethod<T>(string name, Type[] parameters = null)
	{
		return EzGetMethod(typeof(T), name, parameters);
	}
}
public static class NetworkScenePatcher
{
	[CompilerGenerated]
	private static class <>O
	{
		public static Action<Action<NetworkSceneManager>, NetworkSceneManager> <0>__GenerateScenesInBuild_Hook;

		public static Func<Func<NetworkSceneManager, uint, string>, NetworkSceneManager, uint, string> <1>__SceneNameFromHash_Hook;

		public static Func<Func<NetworkSceneManager, int, string, LoadSceneMode, bool>, NetworkSceneManager, int, string, LoadSceneMode, bool> <2>__ValidateSceneBeforeLoading_Hook;

		public static Manipulator <3>__ReplaceBuildIndexByScenePath;

		public static Manipulator <4>__ReplaceScenePathByBuildIndex;

		public static Func<int, string> <5>__GetScenePathByBuildIndex;

		public static Func<string, int> <6>__GetBuildIndexByScenePath;
	}

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

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

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

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

	private static HookHelper.DisposableHookCollection hooks = new HookHelper.DisposableHookCollection();

	internal static bool patched { get; private set; }

	public static void AddScenePath(string scenePath)
	{
		if (scenePaths.Contains(scenePath))
		{
			Debug.LogError((object)("Can not add scene path " + scenePath + " to the network scene patcher! (already exists in scene paths list)"));
		}
		else
		{
			scenePaths.Add(scenePath);
		}
	}

	internal static void Patch()
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Expected O, but got Unknown
		//IL_010c: 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_0117: Expected O, but got Unknown
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Expected O, but got Unknown
		if (!patched)
		{
			patched = true;
			hooks.Hook<NetworkSceneManager>("GenerateScenesInBuild", new Action<Action<NetworkSceneManager>, NetworkSceneManager>(GenerateScenesInBuild_Hook));
			hooks.Hook<NetworkSceneManager>("SceneNameFromHash", new Func<Func<NetworkSceneManager, uint, string>, NetworkSceneManager, uint, string>(SceneNameFromHash_Hook));
			hooks.Hook<NetworkSceneManager>("ValidateSceneBeforeLoading", new Func<Func<NetworkSceneManager, int, string, LoadSceneMode, bool>, NetworkSceneManager, int, string, LoadSceneMode, bool>(ValidateSceneBeforeLoading_Hook), new Type[3]
			{
				typeof(int),
				typeof(string),
				typeof(LoadSceneMode)
			});
			HookHelper.DisposableHookCollection disposableHookCollection = hooks;
			object obj = <>O.<3>__ReplaceBuildIndexByScenePath;
			if (obj == null)
			{
				Manipulator val = ReplaceBuildIndexByScenePath;
				<>O.<3>__ReplaceBuildIndexByScenePath = val;
				obj = (object)val;
			}
			disposableHookCollection.ILHook<NetworkSceneManager>("SceneHashFromNameOrPath", (Manipulator)obj);
			HookHelper.DisposableHookCollection disposableHookCollection2 = hooks;
			object obj2 = <>O.<3>__ReplaceBuildIndexByScenePath;
			if (obj2 == null)
			{
				Manipulator val2 = ReplaceBuildIndexByScenePath;
				<>O.<3>__ReplaceBuildIndexByScenePath = val2;
				obj2 = (object)val2;
			}
			disposableHookCollection2.ILHook<NetworkSceneManager>("ValidateSceneEvent", (Manipulator)obj2);
			HookHelper.DisposableHookCollection disposableHookCollection3 = hooks;
			object obj3 = <>O.<4>__ReplaceScenePathByBuildIndex;
			if (obj3 == null)
			{
				Manipulator val3 = ReplaceScenePathByBuildIndex;
				<>O.<4>__ReplaceScenePathByBuildIndex = val3;
				obj3 = (object)val3;
			}
			disposableHookCollection3.ILHook<NetworkSceneManager>("ScenePathFromHash", (Manipulator)obj3);
		}
	}

	internal static void Unpatch()
	{
		if (patched)
		{
			patched = false;
			hooks.Clear();
		}
	}

	private static void ReplaceScenePathByBuildIndex(ILContext il)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		ILCursor val = new ILCursor(il);
		MethodInfo methodInfo = HookHelper.methodof(new Func<int, string>(GetScenePathByBuildIndex));
		while (val.TryGotoNext(new Func<Instruction, bool>[1]
		{
			(Instruction instr) => ILPatternMatchingExt.MatchCall(instr, typeof(SceneUtility), "GetScenePathByBuildIndex")
		}))
		{
			val.Remove();
			val.Emit(OpCodes.Call, (MethodBase)methodInfo);
		}
	}

	private static void ReplaceBuildIndexByScenePath(ILContext il)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		ILCursor val = new ILCursor(il);
		MethodInfo methodInfo = HookHelper.methodof(new Func<string, int>(GetBuildIndexByScenePath));
		while (val.TryGotoNext(new Func<Instruction, bool>[1]
		{
			(Instruction instr) => ILPatternMatchingExt.MatchCall(instr, typeof(SceneUtility), "GetBuildIndexByScenePath")
		}))
		{
			val.Remove();
			val.Emit(OpCodes.Call, (MethodBase)methodInfo);
		}
	}

	private static string GetScenePathByBuildIndex(int buildIndex)
	{
		if (buildIndexToScenePath.ContainsKey(buildIndex))
		{
			return buildIndexToScenePath[buildIndex];
		}
		return SceneUtility.GetScenePathByBuildIndex(buildIndex);
	}

	private static int GetBuildIndexByScenePath(string scenePath)
	{
		int num = SceneUtility.GetBuildIndexByScenePath(scenePath);
		if (num == -1 && scenePathToBuildIndex.ContainsKey(scenePath))
		{
			num = scenePathToBuildIndex[scenePath];
		}
		return num;
	}

	private static void GenerateScenesInBuild_Hook(Action<NetworkSceneManager> orig, NetworkSceneManager self)
	{
		scenePathToBuildIndex.Clear();
		buildIndexToScenePath.Clear();
		sceneHashToScenePath.Clear();
		orig(self);
		int sceneCountInBuildSettings = SceneManager.sceneCountInBuildSettings;
		for (int i = 0; i < scenePaths.Count; i++)
		{
			int num = sceneCountInBuildSettings + i;
			string text = scenePaths[i];
			uint num2 = XXHash.Hash32(text);
			self.HashToBuildIndex.Add(num2, num);
			self.BuildIndexToHash.Add(num, num2);
			scenePathToBuildIndex.Add(text, num);
			buildIndexToScenePath.Add(num, text);
			sceneHashToScenePath.Add(num2, text);
			Debug.Log((object)("Added modded scene path: " + text));
		}
	}

	private static string SceneNameFromHash_Hook(Func<NetworkSceneManager, uint, string> orig, NetworkSceneManager self, uint sceneHash)
	{
		if (sceneHash == 0)
		{
			return "No Scene";
		}
		if (sceneHashToScenePath.ContainsKey(sceneHash))
		{
			return sceneHashToScenePath[sceneHash];
		}
		return orig(self, sceneHash);
	}

	private static bool ValidateSceneBeforeLoading_Hook(Func<NetworkSceneManager, int, string, LoadSceneMode, bool> orig, NetworkSceneManager self, int sceneIndex, string sceneName, LoadSceneMode loadSceneMode)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		Debug.LogWarning((object)(orig(self, sceneIndex, sceneName, loadSceneMode) ? ("Validation check success for scene: " + sceneName) : ("Bypassed validation check for scene " + sceneName)));
		return true;
	}
}
namespace LethalLevelLoader
{
	[CreateAssetMenu(menuName = "LethalLevelLoader/ExtendedDungeonFlow")]
	public class ExtendedDungeonFlow : ScriptableObject
	{
		[Header("Extended DungeonFlow Settings")]
		public string contentSourceName = string.Empty;

		[Space(5f)]
		public string dungeonDisplayName = string.Empty;

		[Space(5f)]
		public DungeonFlow dungeonFlow;

		[Space(5f)]
		public AudioClip dungeonFirstTimeAudio;

		[Space(10f)]
		[Header("Dynamic DungeonFlow Injections Settings")]
		public List<StringWithRarity> dynamicLevelTagsList = new List<StringWithRarity>();

		[Space(5f)]
		public List<Vector2WithRarity> dynamicRoutePricesList = new List<Vector2WithRarity>();

		[Space(5f)]
		public List<StringWithRarity> dynamicCurrentWeatherList = new List<StringWithRarity>();

		[Space(5f)]
		public List<StringWithRarity> manualPlanetNameReferenceList = new List<StringWithRarity>();

		[Space(5f)]
		public List<StringWithRarity> manualContentSourceNameReferenceList = new List<StringWithRarity>();

		[Space(10f)]
		[Header("Dynamic Dungeon Size Multiplier Lerp Settings")]
		public bool enableDynamicDungeonSizeRestriction = false;

		public float dungeonSizeMin = 1f;

		public float dungeonSizeMax = 1f;

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

		[Space(10f)]
		[Header("Dynamic DungeonFlow Modification Settings")]
		public List<GlobalPropCountOverride> globalPropCountOverridesList = new List<GlobalPropCountOverride>();

		[Space(10f)]
		[Header("Misc. Settings")]
		public bool generateAutomaticConfigurationOptions = true;

		[Space(10f)]
		[Header("Experimental Settings (Currently Unused As Of LethalLevelLoader 1.1.0")]
		public GameObject mainEntrancePropPrefab;

		[Space(5f)]
		public GameObject fireExitPropPrefab;

		[Space(5f)]
		public Animator mainEntrancePropAnimator;

		[Space(5f)]
		public Animator fireExitPropAnimator;

		[HideInInspector]
		public ContentType dungeonType;

		[HideInInspector]
		public int dungeonID;

		[HideInInspector]
		public int dungeonDefaultRarity;

		[HideInInspector]
		public DungeonEvents dungeonEvents = new DungeonEvents();

		internal static ExtendedDungeonFlow Create(DungeonFlow newDungeonFlow, AudioClip newFirstTimeDungeonAudio, string contentSourceName)
		{
			ExtendedDungeonFlow extendedDungeonFlow = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			extendedDungeonFlow.dungeonFlow = newDungeonFlow;
			extendedDungeonFlow.dungeonFirstTimeAudio = newFirstTimeDungeonAudio;
			extendedDungeonFlow.contentSourceName = contentSourceName;
			return extendedDungeonFlow;
		}

		internal void Initialize(ContentType newDungeonType)
		{
			dungeonType = newDungeonType;
			GetDungeonFlowID();
			if (dungeonDisplayName == null || dungeonDisplayName == string.Empty)
			{
				dungeonDisplayName = ((Object)dungeonFlow).name;
			}
			((Object)this).name = ((Object)dungeonFlow).name.Replace("Flow", "") + "ExtendedDungeonFlow";
			if ((Object)(object)dungeonFirstTimeAudio == (Object)null)
			{
				DebugHelper.LogWarning("Custom Dungeon: " + dungeonDisplayName + " Is Missing A DungeonFirstTimeAudio Reference! Assigning Facility Audio To Prevent Errors.");
				dungeonFirstTimeAudio = RoundManager.Instance.firstTimeDungeonAudios[0];
			}
		}

		private void GetDungeonFlowID()
		{
			if (dungeonType == ContentType.Custom)
			{
				dungeonID = PatchedContent.ExtendedDungeonFlows.Count;
			}
			if (dungeonType == ContentType.Vanilla)
			{
				dungeonID = RoundManager.Instance.dungeonFlowTypes.ToList().IndexOf(dungeonFlow);
			}
		}
	}
	[Serializable]
	public class StringWithRarity
	{
		[SerializeField]
		private string _name;

		[SerializeField]
		[Range(0f, 300f)]
		private int _rarity;

		[HideInInspector]
		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				_name = value;
			}
		}

		[HideInInspector]
		public int Rarity
		{
			get
			{
				return _rarity;
			}
			set
			{
				_rarity = value;
			}
		}

		[HideInInspector]
		public StringWithRarity(string newName, int newRarity)
		{
			_name = newName;
			_rarity = newRarity;
		}
	}
	[Serializable]
	public class Vector2WithRarity
	{
		[SerializeField]
		private Vector2 _minMax;

		[SerializeField]
		private int _rarity;

		[HideInInspector]
		public float Min
		{
			get
			{
				return _minMax.x;
			}
			set
			{
				_minMax.x = value;
			}
		}

		[HideInInspector]
		public float Max
		{
			get
			{
				return _minMax.y;
			}
			set
			{
				_minMax.y = value;
			}
		}

		[HideInInspector]
		public int Rarity
		{
			get
			{
				return _rarity;
			}
			set
			{
				_rarity = value;
			}
		}

		public Vector2WithRarity(Vector2 vector2, int newRarity)
		{
			//IL_000e: 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)
			_minMax.x = vector2.x;
			_minMax.y = vector2.y;
			_rarity = newRarity;
		}

		public Vector2WithRarity(float newMin, float newMax, int newRarity)
		{
			_minMax.x = newMin;
			_minMax.y = newMax;
			_rarity = newRarity;
		}
	}
	[Serializable]
	public class GlobalPropCountOverride
	{
		public int globalPropID;

		[Range(0f, 1f)]
		public float globalPropCountScaleRate = 0f;
	}
	[Serializable]
	public class DungeonEvents
	{
		public ExtendedEvent<RoundManager> onBeforeDungeonGenerate = new ExtendedEvent<RoundManager>();

		public ExtendedEvent<List<GameObject>> onSpawnedSyncedObjects = new ExtendedEvent<List<GameObject>>();

		public ExtendedEvent<List<GameObject>> onSpawnedMapObjects = new ExtendedEvent<List<GameObject>>();

		public ExtendedEvent<List<GrabbableObject>> onSpawnedScrapObjects = new ExtendedEvent<List<GrabbableObject>>();

		public ExtendedEvent<(EnemyVent, EnemyAI)> onEnemySpawnedFromVent = new ExtendedEvent<(EnemyVent, EnemyAI)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerEnterDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerExitDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<bool> onPowerSwitchToggle = new ExtendedEvent<bool>();

		public ExtendedEvent<LungProp> onApparatusTaken = new ExtendedEvent<LungProp>();
	}
	[CreateAssetMenu(menuName = "LethalLevelLoader/ExtendedLevel")]
	public class ExtendedLevel : ScriptableObject
	{
		[Header("Extended Level Settings")]
		[Space(5f)]
		public string contentSourceName = string.Empty;

		[Space(5f)]
		public SelectableLevel selectableLevel;

		[Space(5f)]
		[SerializeField]
		private int routePrice = 0;

		[Space(5f)]
		public bool isHidden = false;

		[Space(5f)]
		public bool isLocked = false;

		[Space(5f)]
		public string lockedNodeText = string.Empty;

		[Space(10f)]
		public List<StoryLogData> storyLogs = new List<StoryLogData>();

		[Space(10f)]
		[Header("Dynamic DungeonFlow Injections Settings")]
		[Space(5f)]
		public ContentType allowedDungeonContentTypes = ContentType.Any;

		[Space(5f)]
		public List<string> levelTags = new List<string>();

		[HideInInspector]
		public ContentType levelType;

		[SerializeField]
		[TextArea]
		public string infoNodeDescripton = string.Empty;

		[HideInInspector]
		public TerminalNode routeNode;

		[HideInInspector]
		public TerminalNode routeConfirmNode;

		[HideInInspector]
		public TerminalNode infoNode;

		[Space(10f)]
		[Header("Misc. Settings")]
		[Space(5f)]
		public bool generateAutomaticConfigurationOptions = true;

		[HideInInspector]
		public LevelEvents levelEvents = new LevelEvents();

		internal bool isLethalExpansion = false;

		public int RoutePrice
		{
			get
			{
				if ((Object)(object)routeNode != (Object)null)
				{
					routePrice = routeNode.itemCost;
					routeConfirmNode.itemCost = routePrice;
					return routeNode.itemCost;
				}
				DebugHelper.LogWarning("routeNode Is Missing! Using internal value!");
				return routePrice;
			}
			set
			{
				routeNode.itemCost = value;
				routeConfirmNode.itemCost = value;
				routePrice = value;
			}
		}

		[HideInInspector]
		public string NumberlessPlanetName => GetNumberlessPlanetName(selectableLevel);

		public bool IsLoaded
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				Scene sceneByName = SceneManager.GetSceneByName(selectableLevel.sceneName);
				return ((Scene)(ref sceneByName)).isLoaded;
			}
		}

		internal static ExtendedLevel Create(SelectableLevel newSelectableLevel, ContentType newContentType)
		{
			ExtendedLevel extendedLevel = ScriptableObject.CreateInstance<ExtendedLevel>();
			extendedLevel.levelType = newContentType;
			extendedLevel.selectableLevel = newSelectableLevel;
			return extendedLevel;
		}

		internal void Initialize(string newContentSourceName, bool generateTerminalAssets)
		{
			if (levelType == ContentType.Vanilla && selectableLevel.levelID > 8)
			{
				DebugHelper.LogWarning("LethalExpansion SelectableLevel " + NumberlessPlanetName + " Found, Setting To LevelType: Custom.");
				levelType = ContentType.Custom;
				contentSourceName = "Lethal Expansion";
				levelTags.Clear();
				isLethalExpansion = true;
			}
			if (contentSourceName == string.Empty)
			{
				contentSourceName = newContentSourceName;
			}
			if (levelType == ContentType.Custom)
			{
				levelTags.Add("Custom");
			}
			if (!isLethalExpansion)
			{
				SetLevelID();
			}
			if (generateTerminalAssets)
			{
				TerminalManager.CreateLevelTerminalData(this, routePrice);
			}
			if (levelType == ContentType.Custom)
			{
				((Object)this).name = NumberlessPlanetName.StripSpecialCharacters() + "ExtendedLevel";
				((Object)selectableLevel).name = NumberlessPlanetName.StripSpecialCharacters() + "Level";
			}
		}

		internal static string GetNumberlessPlanetName(SelectableLevel selectableLevel)
		{
			if ((Object)(object)selectableLevel != (Object)null)
			{
				return new string(selectableLevel.PlanetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
			}
			return string.Empty;
		}

		internal void SetLevelID()
		{
			if (levelType == ContentType.Custom)
			{
				selectableLevel.levelID = PatchedContent.ExtendedLevels.IndexOf(this);
				if ((Object)(object)routeNode != (Object)null)
				{
					routeNode.displayPlanetInfo = selectableLevel.levelID;
				}
				if ((Object)(object)routeConfirmNode != (Object)null)
				{
					routeConfirmNode.buyRerouteToMoon = selectableLevel.levelID;
				}
			}
		}
	}
	[Serializable]
	public class LevelEvents
	{
		public ExtendedEvent onLevelLoaded = new ExtendedEvent();

		public ExtendedEvent onNighttime = new ExtendedEvent();

		public ExtendedEvent<EnemyAI> onDaytimeEnemySpawn = new ExtendedEvent<EnemyAI>();

		public ExtendedEvent<EnemyAI> onNighttimeEnemySpawn = new ExtendedEvent<EnemyAI>();

		public ExtendedEvent<StoryLog> onStoryLogCollected = new ExtendedEvent<StoryLog>();

		public ExtendedEvent<LungProp> onApparatusTaken = new ExtendedEvent<LungProp>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerEnterDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerExitDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<bool> onPowerSwitchToggle = new ExtendedEvent<bool>();
	}
	[Serializable]
	public class StoryLogData
	{
		public int storyLogID;

		public string terminalWord = string.Empty;

		public string storyLogTitle = string.Empty;

		[TextArea]
		public string storyLogDescription = string.Empty;

		[HideInInspector]
		internal int newStoryLogID;
	}
	public class MoonsCataloguePage
	{
		private List<ExtendedLevelGroup> extendedLevelGroups;

		public List<ExtendedLevelGroup> ExtendedLevelGroups => extendedLevelGroups;

		public List<ExtendedLevel> ExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevelGroup extendedLevelGroup in extendedLevelGroups)
				{
					foreach (ExtendedLevel extendedLevels in extendedLevelGroup.extendedLevelsList)
					{
						list.Add(extendedLevels);
					}
				}
				return list;
			}
		}

		public MoonsCataloguePage(List<ExtendedLevelGroup> newExtendedLevelGroupList)
		{
			extendedLevelGroups = new List<ExtendedLevelGroup>();
			extendedLevelGroups.Clear();
			foreach (ExtendedLevelGroup newExtendedLevelGroup in newExtendedLevelGroupList)
			{
				extendedLevelGroups.Add(new ExtendedLevelGroup(newExtendedLevelGroup.extendedLevelsList));
			}
		}

		public void RebuildLevelGroups(List<ExtendedLevelGroup> newExtendedLevelGroups, int splitCount)
		{
			List<ExtendedLevel> list = new List<ExtendedLevel>();
			foreach (ExtendedLevelGroup extendedLevelGroup in extendedLevelGroups)
			{
				foreach (ExtendedLevel extendedLevels in extendedLevelGroup.extendedLevelsList)
				{
					list.Add(extendedLevels);
				}
			}
			RebuildLevelGroups(list.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(List<ExtendedLevel> newExtendedLevels, int splitCount)
		{
			RebuildLevelGroups(newExtendedLevels.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(IOrderedEnumerable<ExtendedLevel> orderedExtendedLevels, int splitCount)
		{
			RebuildLevelGroups(orderedExtendedLevels.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(ExtendedLevel[] newExtendedLevels, int splitCount)
		{
			List<ExtendedLevelGroup> list = new List<ExtendedLevelGroup>();
			int num = 0;
			int num2 = 0;
			List<ExtendedLevel> list2 = new List<ExtendedLevel>();
			foreach (ExtendedLevel item in new List<ExtendedLevel>(newExtendedLevels))
			{
				list2.Add(item);
				num2++;
				num++;
				if (num == splitCount || num2 == newExtendedLevels.Length)
				{
					list.Add(new ExtendedLevelGroup(list2));
					list2.Clear();
					num = 0;
				}
			}
			extendedLevelGroups = list;
		}

		public void RefreshLevelGroups(List<ExtendedLevelGroup> newLevelGroups)
		{
			extendedLevelGroups.Clear();
			foreach (ExtendedLevelGroup newLevelGroup in newLevelGroups)
			{
				if (newLevelGroup.extendedLevelsList.Count != 0)
				{
					extendedLevelGroups.Add(new ExtendedLevelGroup(newLevelGroup.extendedLevelsList));
				}
			}
		}
	}
	[Serializable]
	public class ExtendedLevelGroup
	{
		public List<ExtendedLevel> extendedLevelsList;

		public ExtendedLevelGroup(List<ExtendedLevel> newExtendedLevelsList)
		{
			extendedLevelsList = new List<ExtendedLevel>(newExtendedLevelsList);
		}

		public ExtendedLevelGroup(List<SelectableLevel> newSelectableLevelsList)
		{
			extendedLevelsList = new List<ExtendedLevel>();
			foreach (SelectableLevel newSelectableLevels in newSelectableLevelsList)
			{
				extendedLevelsList.Add(LevelManager.GetExtendedLevel(newSelectableLevels));
			}
		}
	}
	public static class PatchedContent
	{
		public static List<ExtendedLevel> ExtendedLevels { get; internal set; } = new List<ExtendedLevel>();


		public static List<ExtendedLevel> VanillaExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Vanilla)
					{
						list.Add(extendedLevel);
					}
				}
				return list;
			}
		}

		public static List<ExtendedLevel> CustomExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Custom)
					{
						list.Add(extendedLevel);
					}
				}
				return list;
			}
		}

		public static List<SelectableLevel> SeletectableLevels
		{
			get
			{
				List<SelectableLevel> list = new List<SelectableLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					list.Add(extendedLevel.selectableLevel);
				}
				return list;
			}
		}

		public static List<SelectableLevel> MoonsCatalogue
		{
			get
			{
				List<SelectableLevel> list = new List<SelectableLevel>();
				foreach (SelectableLevel item in OriginalContent.MoonsCatalogue)
				{
					list.Add(item);
				}
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Custom)
					{
						list.Add(extendedLevel.selectableLevel);
					}
				}
				return list;
			}
		}

		public static List<ExtendedDungeonFlow> ExtendedDungeonFlows { get; internal set; } = new List<ExtendedDungeonFlow>();


		public static List<ExtendedDungeonFlow> VanillaExtendedDungeonFlows
		{
			get
			{
				List<ExtendedDungeonFlow> list = new List<ExtendedDungeonFlow>();
				foreach (ExtendedDungeonFlow extendedDungeonFlow in ExtendedDungeonFlows)
				{
					if (extendedDungeonFlow.dungeonType == ContentType.Vanilla)
					{
						list.Add(extendedDungeonFlow);
					}
				}
				return list;
			}
		}

		public static List<ExtendedDungeonFlow> CustomExtendedDungeonFlows
		{
			get
			{
				List<ExtendedDungeonFlow> list = new List<ExtendedDungeonFlow>();
				foreach (ExtendedDungeonFlow extendedDungeonFlow in ExtendedDungeonFlows)
				{
					if (extendedDungeonFlow.dungeonType == ContentType.Custom)
					{
						list.Add(extendedDungeonFlow);
					}
				}
				return list;
			}
		}

		public static List<string> AllExtendedLevelTags
		{
			get
			{
				List<string> list = new List<string>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					foreach (string levelTag in extendedLevel.levelTags)
					{
						if (!list.Contains(levelTag))
						{
							list.Add(levelTag);
						}
					}
				}
				return list;
			}
		}

		public static List<AudioMixer> AudioMixers { get; internal set; } = new List<AudioMixer>();


		public static List<AudioMixerGroup> AudioMixerGroups { get; internal set; } = new List<AudioMixerGroup>();


		public static List<AudioMixerSnapshot> AudioMixerSnapshots { get; internal set; } = new List<AudioMixerSnapshot>();


		public static List<Item> Items { get; internal set; } = new List<Item>();


		public static List<EnemyType> Enemies { get; internal set; } = new List<EnemyType>();


		public static void RegisterExtendedDungeonFlow(ExtendedDungeonFlow extendedDungeonFlow)
		{
			AssetBundleLoader.obtainedExtendedDungeonFlowsList.Add(extendedDungeonFlow);
		}

		public static void RegisterExtendedLevel(ExtendedLevel extendedLevel)
		{
			AssetBundleLoader.obtainedExtendedLevelsList.Add(extendedLevel);
		}
	}
	public static class OriginalContent
	{
		public static List<SelectableLevel> SelectableLevels { get; internal set; } = new List<SelectableLevel>();


		public static List<SelectableLevel> MoonsCatalogue { get; internal set; } = new List<SelectableLevel>();


		public static List<DungeonFlow> DungeonFlows { get; internal set; } = new List<DungeonFlow>();


		public static List<Item> Items { get; internal set; } = new List<Item>();


		public static List<ItemGroup> ItemGroups { get; internal set; } = new List<ItemGroup>();


		public static List<EnemyType> Enemies { get; internal set; } = new List<EnemyType>();


		public static List<SpawnableOutsideObject> SpawnableOutsideObjects { get; internal set; } = new List<SpawnableOutsideObject>();


		public static List<GameObject> SpawnableMapObjects { get; internal set; } = new List<GameObject>();


		public static List<AudioMixer> AudioMixers { get; internal set; } = new List<AudioMixer>();


		public static List<AudioMixerGroup> AudioMixerGroups { get; internal set; } = new List<AudioMixerGroup>();


		public static List<AudioMixerSnapshot> AudioMixerSnapshots { get; internal set; } = new List<AudioMixerSnapshot>();


		public static List<LevelAmbienceLibrary> LevelAmbienceLibraries { get; internal set; } = new List<LevelAmbienceLibrary>();


		public static List<ReverbPreset> ReverbPresets { get; internal set; } = new List<ReverbPreset>();


		public static List<TerminalKeyword> TerminalKeywords { get; internal set; } = new List<TerminalKeyword>();


		public static List<TerminalNode> TerminalNodes { get; internal set; } = new List<TerminalNode>();

	}
	internal class EventPatches
	{
		private static EnemyVent cachedSelectedVent;

		internal static void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && LevelManager.CurrentExtendedLevel.IsLoaded)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onLevelLoaded.Invoke();
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(StoryLog), "CollectLog")]
		[HarmonyPrefix]
		internal static void StoryLogCollectLog_Prefix(StoryLog __instance)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onStoryLogCollected.Invoke(__instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnRandomDaytimeEnemy")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnRandomDaytimeEnemy_Postfix(RoundManager __instance, GameObject __result)
		{
			EnemyAI param = default(EnemyAI);
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer && (Object)(object)__result != (Object)null && __result.TryGetComponent<EnemyAI>(ref param))
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onDaytimeEnemySpawn.Invoke(param);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnRandomOutsideEnemy")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnRandomOutsideEnemy_Postfix(RoundManager __instance, GameObject __result)
		{
			EnemyAI param = default(EnemyAI);
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer && (Object)(object)__result != (Object)null && __result.TryGetComponent<EnemyAI>(ref param))
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onNighttimeEnemySpawn.Invoke(param);
			}
		}

		[HarmonyPriority(201)]
		[HarmonyPatch(typeof(DungeonGenerator), "Generate")]
		[HarmonyPrefix]
		internal static void DungeonGeneratorGenerate_Prefix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onBeforeDungeonGenerate.Invoke(RoundManager.Instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SwitchPower")]
		[HarmonyPrefix]
		internal static void RoundManagerSwitchPower_Prefix(bool on)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPowerSwitchToggle.Invoke(on);
			}
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onPowerSwitchToggle.Invoke(on);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnScrapInLevel_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedScrapObjects.HasListeners)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedScrapObjects.Invoke(Object.FindObjectsOfType<GrabbableObject>().ToList());
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnSyncedProps")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnSyncedProps_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedSyncedObjects.HasListeners)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedSyncedObjects.Invoke(RoundManager.Instance.spawnedSyncedObjects);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnEnemyFromVent")]
		[HarmonyPrefix]
		internal static void RoundManagerSpawnEventFromVent_Prefix(EnemyVent vent)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				cachedSelectedVent = vent;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnEnemyGameObject")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnEventFromVent_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && (Object)(object)cachedSelectedVent != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onEnemySpawnedFromVent.Invoke((cachedSelectedVent, RoundManager.Instance.SpawnedEnemies.Last()));
				cachedSelectedVent = null;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnMapObjects")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnMapObjects_Postfix()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null))
			{
				return;
			}
			List<GameObject> list = new List<GameObject>();
			Scene sceneByName = SceneManager.GetSceneByName(LevelManager.CurrentExtendedLevel.selectableLevel.sceneName);
			GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
			foreach (GameObject val in rootGameObjects)
			{
				SpawnableMapObject[] spawnableMapObjects = LevelManager.CurrentExtendedLevel.selectableLevel.spawnableMapObjects;
				foreach (SpawnableMapObject val2 in spawnableMapObjects)
				{
					if (((Object)val).name.Sanitized().Contains(((Object)val2.prefabToSpawn).name.Sanitized()))
					{
						list.Add(val);
					}
				}
			}
			DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedMapObjects.Invoke(list);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(EntranceTeleport), "TeleportPlayerServerRpc")]
		[HarmonyPrefix]
		internal static void EntranceTeleportTeleportPlayerServerRpc_Prefix(EntranceTeleport __instance)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (__instance.isEntranceToBuilding)
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPlayerEnterDungeon.Invoke((__instance, localPlayerController));
				}
				else
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPlayerExitDungeon.Invoke((__instance, localPlayerController));
				}
			}
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				PlayerControllerB localPlayerController2 = GameNetworkManager.Instance.localPlayerController;
				if (__instance.isEntranceToBuilding)
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onPlayerEnterDungeon.Invoke((__instance, localPlayerController2));
				}
				else
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onPlayerExitDungeon.Invoke((__instance, localPlayerController2));
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(LungProp), "EquipItem")]
		[HarmonyPrefix]
		internal static void LungPropEquipItem_Postfix(LungProp __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onApparatusTaken.Invoke(__instance);
				}
				if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onApparatusTaken.Invoke(__instance);
				}
			}
		}
	}
	public class ExtendedEvent<T>
	{
		public delegate void ParameterEvent(T param);

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event ParameterEvent onParameterEvent;

		public void Invoke(T param)
		{
			this.onParameterEvent?.Invoke(param);
		}

		public void AddListener(ParameterEvent listener)
		{
			onParameterEvent += listener;
			Listeners++;
		}

		public void RemoveListener(ParameterEvent listener)
		{
			onParameterEvent -= listener;
			Listeners--;
		}
	}
	public class ExtendedEvent
	{
		public delegate void Event();

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event Event onEvent;

		public void Invoke()
		{
			this.onEvent?.Invoke();
		}

		public void AddListener(Event listener)
		{
			onEvent += listener;
			Listeners++;
		}

		public void RemoveListener(Event listener)
		{
			onEvent -= listener;
			Listeners--;
		}
	}
	public static class Extensions
	{
		public static List<Tile> GetTiles(this DungeonFlow dungeonFlow)
		{
			List<Tile> list = new List<Tile>();
			foreach (GraphNode node in dungeonFlow.Nodes)
			{
				foreach (TileSet tileSet in node.TileSets)
				{
					list.AddRange(GetTilesInTileSet(tileSet));
				}
			}
			foreach (GraphLine line in dungeonFlow.Lines)
			{
				foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
				{
					foreach (TileSet branchCapTileSet in dungeonArchetype.BranchCapTileSets)
					{
						list.AddRange(GetTilesInTileSet(branchCapTileSet));
					}
					foreach (TileSet tileSet2 in dungeonArchetype.TileSets)
					{
						list.AddRange(GetTilesInTileSet(tileSet2));
					}
				}
			}
			foreach (Tile item in new List<Tile>(list))
			{
				if ((Object)(object)item == (Object)null)
				{
					list.Remove(item);
				}
			}
			return list;
		}

		public static List<Tile> GetTilesInTileSet(TileSet tileSet)
		{
			List<Tile> list = new List<Tile>();
			if (tileSet.TileWeights != null && tileSet.TileWeights.Weights != null)
			{
				foreach (GameObjectChance weight in tileSet.TileWeights.Weights)
				{
					Tile[] componentsInChildren = weight.Value.GetComponentsInChildren<Tile>();
					foreach (Tile item in componentsInChildren)
					{
						list.Add(item);
					}
				}
			}
			return list;
		}

		public static List<RandomMapObject> GetRandomMapObjects(this DungeonFlow dungeonFlow)
		{
			List<RandomMapObject> list = new List<RandomMapObject>();
			foreach (Tile tile in dungeonFlow.GetTiles())
			{
				RandomMapObject[] componentsInChildren = ((Component)tile).gameObject.GetComponentsInChildren<RandomMapObject>();
				foreach (RandomMapObject item in componentsInChildren)
				{
					list.Add(item);
				}
			}
			return list;
		}

		public static List<SpawnSyncedObject> GetSpawnSyncedObjects(this DungeonFlow dungeonFlow)
		{
			List<SpawnSyncedObject> list = new List<SpawnSyncedObject>();
			foreach (Tile tile in dungeonFlow.GetTiles())
			{
				Doorway[] componentsInChildren = ((Component)tile).gameObject.GetComponentsInChildren<Doorway>();
				foreach (Doorway val in componentsInChildren)
				{
					foreach (GameObjectWeight connectorPrefabWeight in val.ConnectorPrefabWeights)
					{
						SpawnSyncedObject[] componentsInChildren2 = connectorPrefabWeight.GameObject.GetComponentsInChildren<SpawnSyncedObject>();
						foreach (SpawnSyncedObject item in componentsInChildren2)
						{
							list.Add(item);
						}
					}
					foreach (GameObjectWeight blockerPrefabWeight in val.BlockerPrefabWeights)
					{
						SpawnSyncedObject[] componentsInChildren3 = blockerPrefabWeight.GameObject.GetComponentsInChildren<SpawnSyncedObject>();
						foreach (SpawnSyncedObject item2 in componentsInChildren3)
						{
							list.Add(item2);
						}
					}
				}
				SpawnSyncedObject[] componentsInChildren4 = ((Component)tile).gameObject.GetComponentsInChildren<SpawnSyncedObject>();
				foreach (SpawnSyncedObject item3 in componentsInChildren4)
				{
					list.Add(item3);
				}
			}
			return list;
		}

		public static void AddReferences(this CompatibleNoun compatibleNoun, TerminalKeyword firstNoun, TerminalNode firstResult)
		{
			compatibleNoun.noun = firstNoun;
			compatibleNoun.result = firstResult;
		}

		public static void AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword newNoun, TerminalNode newResult)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (terminalKeyword.compatibleNouns == null)
			{
				terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[0];
			}
			CompatibleNoun val = new CompatibleNoun();
			val.noun = newNoun;
			val.result = newResult;
			terminalKeyword.compatibleNouns = CollectionExtensions.AddItem<CompatibleNoun>((IEnumerable<CompatibleNoun>)terminalKeyword.compatibleNouns, val).ToArray();
		}

		public static void AddCompatibleNoun(this TerminalNode terminalNode, TerminalKeyword newNoun, TerminalNode newResult)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (terminalNode.terminalOptions == null)
			{
				terminalNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[0];
			}
			CompatibleNoun val = new CompatibleNoun();
			val.noun = newNoun;
			val.result = newResult;
			terminalNode.terminalOptions = CollectionExtensions.AddItem<CompatibleNoun>((IEnumerable<CompatibleNoun>)terminalNode.terminalOptions, val).ToArray();
		}

		public static void Add(this IntWithRarity intWithRarity, int id, int rarity)
		{
			intWithRarity.id = id;
			intWithRarity.rarity = rarity;
		}

		public static string Sanitized(this string currentString)
		{
			return new string(currentString.SkipToLetters().RemoveWhitespace().ToLowerInvariant());
		}

		public static string RemoveWhitespace(this string input)
		{
			return new string((from c in input.ToCharArray()
				where !char.IsWhiteSpace(c)
				select c).ToArray());
		}

		public static string SkipToLetters(this string input)
		{
			return new string(input.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
		}

		public static string StripSpecialCharacters(this string input)
		{
			string text = string.Empty;
			for (int i = 0; i < input.Length; i++)
			{
				char c = input[i];
				if ((!".,?!@#$%^&*()_+-=';:'\"".ToCharArray().Contains(c) && char.IsLetterOrDigit(c)) || c.ToString() == " ")
				{
					text += c;
				}
			}
			return text;
		}
	}
	internal static class Patches
	{
		internal const int harmonyPriority = 200;

		internal static string delayedSceneLoadingName = string.Empty;

		internal static List<string> allSceneNamesCalledToLoad = new List<string>();

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		internal static void PreInitSceneScriptAwake_Prefix(PreInitSceneScript __instance)
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				AssetBundleLoader.CreateLoadingBundlesHeaderText(__instance);
				AudioSource val = default(AudioSource);
				if (((Component)__instance).TryGetComponent<AudioSource>(ref val))
				{
					OriginalContent.AudioMixers.Add(val.outputAudioMixerGroup.audioMixer);
				}
				AssetBundleLoader.LoadBundles(__instance);
				AssetBundleLoader.onBundlesFinishedLoading += AssetBundleLoader.LoadContentInBundles;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(PreInitSceneScript), "ChooseLaunchOption")]
		[HarmonyPrefix]
		internal static bool PreInitSceneScriptChooseLaunchOption_Prefix()
		{
			return true;
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(SceneManager), "LoadScene", new Type[] { typeof(string) })]
		[HarmonyPrefix]
		internal static bool SceneManagerLoadScene(string sceneName)
		{
			//IL_002b: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			if (allSceneNamesCalledToLoad.Count == 0)
			{
				List<string> list = allSceneNamesCalledToLoad;
				Scene activeScene = SceneManager.GetActiveScene();
				list.Add(((Scene)(ref activeScene)).name);
			}
			SceneManager.GetSceneByName(sceneName);
			if (true)
			{
				allSceneNamesCalledToLoad.Add(sceneName);
			}
			if (sceneName == "MainMenu" && !allSceneNamesCalledToLoad.Contains("InitSceneLaunchOptions"))
			{
				DebugHelper.LogError("SceneManager has been told to load Main Menu without ever loading InitSceneLaunchOptions. This will break LethalLevelLoader. This is likely due to a \"Skip to Main Menu\" mod.");
				return false;
			}
			if (AssetBundleLoader.loadingStatus == AssetBundleLoader.LoadingStatus.Loading)
			{
				DebugHelper.LogWarning("SceneManager has attempted to load " + sceneName + " Scene before AssetBundles have finished loading. Pausing request until LethalLeveLoader is ready to proceed.");
				delayedSceneLoadingName = sceneName;
				AssetBundleLoader.onBundlesFinishedLoading -= LoadMainMenu;
				AssetBundleLoader.onBundlesFinishedLoading += LoadMainMenu;
				return false;
			}
			return true;
		}

		internal static void LoadMainMenu()
		{
			DebugHelper.LogWarning("Proceeding with the loading of " + delayedSceneLoadingName + " Scene as LethalLevelLoader has finished loading AssetBundles.");
			if (delayedSceneLoadingName != string.Empty)
			{
				SceneManager.LoadScene(delayedSceneLoadingName);
			}
			delayedSceneLoadingName = string.Empty;
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPrefix]
		internal static void GameNetworkManagerStart_Prefix(GameNetworkManager __instance)
		{
			if (Plugin.hasVanillaBeenPatched)
			{
				return;
			}
			foreach (NetworkPrefab prefab in ((Component)__instance).GetComponent<NetworkManager>().NetworkConfig.Prefabs.m_Prefabs)
			{
				if (((Object)prefab.Prefab).name.Contains("EntranceTeleport") && (Object)(object)prefab.Prefab.GetComponent<AudioSource>() != (Object)null)
				{
					OriginalContent.AudioMixers.Add(prefab.Prefab.GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				}
			}
			GameObject val = NetworkPrefabs.CreateNetworkPrefab("LethalLevelLoaderNetworkManagerTest");
			val.AddComponent<LethalLevelLoaderNetworkManager>();
			val.GetComponent<NetworkObject>().DontDestroyWithOwner = true;
			val.GetComponent<NetworkObject>().SceneMigrationSynchronization = true;
			val.GetComponent<NetworkObject>().DestroyWithScene = false;
			Object.DontDestroyOnLoad((Object)(object)val);
			LethalLevelLoaderNetworkManager.networkingManagerPrefab = val;
			AssetBundleLoader.RegisterCustomContent(((Component)__instance).GetComponent<NetworkManager>());
			LethalLevelLoaderNetworkManager.RegisterPrefabs(((Component)__instance).GetComponent<NetworkManager>());
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		internal static void StartOfRoundAwake_Prefix(StartOfRound __instance)
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				ContentExtractor.TryScrapeVanillaItems(__instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		internal static void RoundManagerAwake_Postfix(RoundManager __instance)
		{
			if (((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().IsServer)
			{
				LethalLevelLoaderNetworkManager component = Object.Instantiate<GameObject>(LethalLevelLoaderNetworkManager.networkingManagerPrefab).GetComponent<LethalLevelLoaderNetworkManager>();
				((Component)component).GetComponent<NetworkObject>().Spawn(false);
			}
			RoundManager.Instance.firstTimeDungeonAudios = CollectionExtensions.AddItem<AudioClip>((IEnumerable<AudioClip>)RoundManager.Instance.firstTimeDungeonAudios.ToList(), RoundManager.Instance.firstTimeDungeonAudios[0]).ToArray();
			if (Plugin.hasVanillaBeenPatched)
			{
				return;
			}
			ContentExtractor.TryScrapeVanillaContent(__instance);
			TerminalManager.CacheTerminalReferences();
			AssetBundleLoader.CreateVanillaExtendedDungeonFlows();
			AssetBundleLoader.CreateVanillaExtendedLevels(StartOfRound.Instance);
			AssetBundleLoader.InitializeBundles();
			string text = "LethalLevelLoader Loaded The Following ExtendedLevels:\n";
			foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
			{
				text = text + (PatchedContent.ExtendedLevels.IndexOf(extendedLevel) + 1) + ". " + extendedLevel.selectableLevel.PlanetName + " (" + extendedLevel.levelType.ToString() + ")\n";
			}
			DebugHelper.Log(text);
			text = "LethalLevelLoader Loaded The Following ExtendedDungeonFlows:\n";
			foreach (ExtendedDungeonFlow extendedDungeonFlow in PatchedContent.ExtendedDungeonFlows)
			{
				text = text + (PatchedContent.ExtendedDungeonFlows.IndexOf(extendedDungeonFlow) + 1) + ". " + extendedDungeonFlow.dungeonDisplayName + " (" + ((Object)extendedDungeonFlow.dungeonFlow).name + ") (" + extendedDungeonFlow.dungeonType.ToString() + ")\n";
			}
			DebugHelper.Log(text);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Start")]
		[HarmonyPrefix]
		internal static void RoundManagerStart_Prefix()
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				foreach (ExtendedLevel customExtendedLevel in PatchedContent.CustomExtendedLevels)
				{
					ContentRestorer.RestoreVanillaLevelAssetReferences(customExtendedLevel);
				}
				foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
				{
					ContentRestorer.RestoreVanillaDungeonAssetReferences(customExtendedDungeonFlow);
				}
				TerminalManager.CreateMoonsFilterTerminalAssets();
				ConfigLoader.BindConfigs();
				SceneManager.sceneLoaded += OnSceneLoaded;
				SceneManager.sceneLoaded += EventPatches.OnSceneLoaded;
			}
			AudioSource[] array = Resources.FindObjectsOfTypeAll<AudioSource>();
			foreach (AudioSource val in array)
			{
				val.spatialize = false;
			}
			LevelManager.ValidateLevelLists();
			LevelManager.PatchVanillaLevelLists();
			DungeonManager.PatchVanillaDungeonLists();
			LevelManager.RefreshCustomExtendedLevelIDs();
			TerminalManager.CreateExtendedLevelGroups();
			if (LevelManager.invalidSaveLevelID != -1 && StartOfRound.Instance.levels.Length > LevelManager.invalidSaveLevelID)
			{
				DebugHelper.Log("Setting CurrentLevel to previously saved ID that was not loaded at the time of save loading.");
				DebugHelper.Log(LevelManager.invalidSaveLevelID + " / " + StartOfRound.Instance.levels.Length);
				StartOfRound.Instance.ChangeLevelServerRpc(LevelManager.invalidSaveLevelID, TerminalManager.Terminal.groupCredits);
				LevelManager.invalidSaveLevelID = -1;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Start")]
		[HarmonyPostfix]
		internal static void RoundManagerStart_Postfix()
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				ContentExtractor.TryScrapeCustomContent();
				Plugin.hasVanillaBeenPatched = true;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(StartOfRound), "ChangeLevel")]
		[HarmonyPrefix]
		internal static void StartOfRoundChangeLevel_Prefix(ref int levelID)
		{
			if (levelID >= StartOfRound.Instance.levels.Length)
			{
				DebugHelper.LogWarning("Lethal Company attempted to load a saved current level that has not yet been loaded");
				DebugHelper.LogWarning(levelID + " / " + StartOfRound.Instance.levels.Length);
				LevelManager.invalidSaveLevelID = levelID;
				levelID = 0;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		internal static void TerminalStart_Postfix()
		{
			LevelManager.RefreshLethalExpansionMoons();
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "ParseWord")]
		[HarmonyPostfix]
		internal static void TerminalParseWord_Postfix(Terminal __instance, ref TerminalKeyword __result, string playerWord)
		{
			if ((Object)(object)__result != (Object)null)
			{
				TerminalKeyword val = TerminalManager.TryFindAlternativeNoun(__instance, __result, playerWord);
				if ((Object)(object)val != (Object)null)
				{
					__result = val;
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "RunTerminalEvents")]
		[HarmonyPrefix]
		internal static bool TerminalRunTerminalEvents_Prefix(TerminalNode node)
		{
			return TerminalManager.RunLethalLevelLoaderTerminalEvents(node);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
		[HarmonyPrefix]
		internal static void TerminalLoadNewNode_Prefix(Terminal __instance, ref TerminalNode node)
		{
			if ((Object)(object)node == (Object)(object)TerminalManager.moonsKeyword.specialKeywordResult)
			{
				TerminalManager.RefreshExtendedLevelGroups();
				node.displayText = TerminalManager.GetMoonsTerminalText();
			}
			else
			{
				if (!((Object)(object)__instance.currentNode == (Object)(object)TerminalManager.moonsKeyword.specialKeywordResult))
				{
					return;
				}
				foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
				{
					if ((Object)(object)extendedLevel.routeNode == (Object)(object)node && extendedLevel.isLocked)
					{
						TerminalManager.SwapRouteNodeToLockedNode(extendedLevel, ref node);
					}
				}
			}
		}

		internal static void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
		{
			//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)
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && LevelManager.CurrentExtendedLevel.IsLoaded && LevelManager.CurrentExtendedLevel.levelType == ContentType.Custom && !LevelManager.CurrentExtendedLevel.isLethalExpansion)
			{
				Scene sceneByName = SceneManager.GetSceneByName(LevelManager.CurrentExtendedLevel.selectableLevel.sceneName);
				GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
				foreach (GameObject val in rootGameObjects)
				{
					LevelLoader.UpdateStoryLogs(LevelManager.CurrentExtendedLevel, val);
					ContentRestorer.RestoreAudioAssetReferencesInParent(val);
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(DungeonGenerator), "Generate")]
		[HarmonyPrefix]
		internal static void DungeonGeneratorGenerate_Prefix(DungeonGenerator __instance)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				DungeonLoader.PrepareDungeon();
			}
			LevelManager.LogDayHistory();
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Generator_OnGenerationStatusChanged")]
		[HarmonyPrefix]
		internal static bool OnGenerationStatusChanged_Prefix(RoundManager __instance, GenerationStatus status)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			DebugHelper.Log(((object)(GenerationStatus)(ref status)).ToString());
			if ((int)status == 6 && !__instance.dungeonCompletedGenerating)
			{
				__instance.FinishGeneratingLevel();
				__instance.dungeonGenerator.Generator.OnGenerationStatusChanged -= new GenerationStatusDelegate(__instance.Generator_OnGenerationStatusChanged);
				Debug.Log((object)"Dungeon has finished generating on this client after multiple frames");
			}
			return false;
		}

		[HarmonyPatch(typeof(RoundManager), "GenerateNewLevelClientRpc")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> GenerateNewLevelClientRpcTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).SearchForward((Func<CodeInstruction, bool>)((CodeInstruction instructions) => CodeInstructionExtensions.Calls(instructions, AccessTools.Method(typeof(RoundManager), "GenerateNewFloor", (Type[])null, (Type[])null)))).SetInstruction(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patches), "InjectHostDungeonFlowSelection", (Type[])null, (Type[])null))).Advance(-1)
				.SetInstruction(new CodeInstruction(OpCodes.Nop, (object)null));
			return val.InstructionEnumeration();
		}

		[HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> GenerateNewFloorTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).SearchForward((Func<CodeInstruction, bool>)((CodeInstruction instructions) => CodeInstructionExtensions.Calls(instructions, AccessTools.Method(typeof(RuntimeDungeon), "Generate", (Type[])null, (Type[])null)))).SetInstruction(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patches), "InjectHostDungeonSizeSelection", (Type[])null, (Type[])null))).Advance(-1)
				.SetInstruction(new CodeInstruction(OpCodes.Nop, (object)null));
			return val.InstructionEnumeration();
		}

		public static void InjectHostDungeonSizeSelection(RoundManager roundManager)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				LethalLevelLoaderNetworkManager.Instance.GetDungeonFlowSizeServerRpc();
			}
			else
			{
				roundManager.dungeonGenerator.Generate();
			}
		}

		internal static void InjectHostDungeonFlowSelection()
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				DungeonManager.TryAddCurrentVanillaLevelDungeonFlow(RoundManager.Instance.dungeonGenerator.Generator, LevelManager.CurrentExtendedLevel);
				DungeonLoader.SelectDungeon();
			}
			else
			{
				RoundManager.Instance.GenerateNewFloor();
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Dungeon), "RoundManager_Start")]
		[HarmonyPrefix]
		internal static bool Dungeon_Start_Prefix(orig_Start orig, RoundManager self)
		{
			DebugHelper.LogWarning("Disabling LethalLib Dungeon.RoundManager_Start() Function To Prevent Conflicts");
			orig.Invoke(self);
			return false;
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Dungeon), "RoundManager_GenerateNewFloor")]
		[HarmonyPrefix]
		internal static bool Dungeon_GenerateNewFloor_Prefix(orig_GenerateNewFloor orig, RoundManager self)
		{
			DebugHelper.LogWarning("Disabling LethalLib Dungeon.RoundManager_GenerateNewFloor() Function To Prevent Conflicts");
			orig.Invoke(self);
			return false;
		}
	}
	public enum PreviewInfoType
	{
		Price,
		Difficulty,
		Weather,
		History,
		All,
		None,
		Vanilla,
		Override
	}
	public enum SortInfoType
	{
		Price,
		Difficulty,
		Tag,
		LastTraveled,
		None
	}
	public enum FilterInfoType
	{
		Price,
		Weather,
		Tag,
		TraveledThisQuota,
		TraveledThisRun,
		None
	}
	public enum SimulateInfoType
	{
		Percentage,
		Rarity
	}
	public static class Settings
	{
		public static PreviewInfoType levelPreviewInfoType = PreviewInfoType.Weather;

		public static SortInfoType levelPreviewSortType = SortInfoType.None;

		public static FilterInfoType levelPreviewFilterType = FilterInfoType.None;

		public static SimulateInfoType levelSimulateInfoType = SimulateInfoType.Percentage;

		public static bool allDungeonFlowsRequireMatching = false;

		public static string GetOverridePreviewInfo(ExtendedLevel extendedLevel)
		{
			return string.Empty;
		}
	}
	[Serializable]
	public class ExtendedDungeonFlowWithRarity
	{
		public ExtendedDungeonFlow extendedDungeonFlow;

		public int rarity;

		public ExtendedDungeonFlowWithRarity(ExtendedDungeonFlow newExtendedDungeonFlow, int newRarity)
		{
			extendedDungeonFlow = newExtendedDungeonFlow;
			rarity = newRarity;
		}

		public bool UpdateRarity(int newRarity)
		{
			if (newRarity > rarity)
			{
				rarity = newRarity;
				return true;
			}
			return false;
		}
	}
	public static class DungeonLoader
	{
		internal static void SelectDungeon()
		{
			RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow = null;
			if (((NetworkBehaviour)LethalLevelLoaderNetworkManager.Instance).IsServer)
			{
				LethalLevelLoaderNetworkManager.Instance.GetRandomExtendedDungeonFlowServerRpc();
			}
		}

		internal static void PrepareDungeon()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			DungeonGenerator generator = RoundManager.Instance.dungeonGenerator.Generator;
			ExtendedLevel currentExtendedLevel = LevelManager.CurrentExtendedLevel;
			ExtendedDungeonFlow currentExtendedDungeonFlow = DungeonManager.CurrentExtendedDungeonFlow;
			PatchFireEscapes(generator, currentExtendedLevel, SceneManager.GetSceneByName(currentExtendedLevel.selectableLevel.sceneName));
			PatchDynamicGlobalProps(generator, currentExtendedDungeonFlow);
		}

		public static float GetClampedDungeonSize()
		{
			float num = LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier * RoundManager.Instance.mapSizeMultiplier;
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.enableDynamicDungeonSizeRestriction)
			{
				ExtendedDungeonFlow currentExtendedDungeonFlow = DungeonManager.CurrentExtendedDungeonFlow;
				ExtendedLevel currentExtendedLevel = LevelManager.CurrentExtendedLevel;
				if (currentExtendedLevel.selectableLevel.factorySizeMultiplier > currentExtendedDungeonFlow.dungeonSizeMax)
				{
					num = Mathf.Lerp(currentExtendedLevel.selectableLevel.factorySizeMultiplier, currentExtendedDungeonFlow.dungeonSizeMax, currentExtendedDungeonFlow.dungeonSizeLerpPercentage) * RoundManager.Instance.mapSizeMultiplier;
				}
				else if (currentExtendedLevel.selectableLevel.factorySizeMultiplier < currentExtendedDungeonFlow.dungeonSizeMin)
				{
					num = Mathf.Lerp(currentExtendedLevel.selectableLevel.factorySizeMultiplier, currentExtendedDungeonFlow.dungeonSizeMin, currentExtendedDungeonFlow.dungeonSizeLerpPercentage) * RoundManager.Instance.mapSizeMultiplier;
				}
				DebugHelper.Log("CurrentLevel: " + LevelManager.CurrentExtendedLevel.NumberlessPlanetName + " DungeonSize Is: " + LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier + " | Overrriding DungeonSize To: " + num / RoundManager.Instance.mapSizeMultiplier + " (" + num + ")");
			}
			else
			{
				DebugHelper.Log("CurrentLevel: " + LevelManager.CurrentExtendedLevel.NumberlessPlanetName + " DungeonSize Is: " + LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier + " | Leaving DungeonSize As: " + num / RoundManager.Instance.mapSizeMultiplier + " (" + num + ")");
			}
			return num;
		}

		internal static void PatchDungeonSize(DungeonGenerator dungeonGenerator, ExtendedLevel extendedLevel, ExtendedDungeonFlow extendedDungeonFlow)
		{
		}

		internal static List<EntranceTeleport> GetEntranceTeleports(Scene scene)
		{
			List<EntranceTeleport> list = new List<EntranceTeleport>();
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			foreach (GameObject val in rootGameObjects)
			{
				EntranceTeleport[] componentsInChildren = val.GetComponentsInChildren<EntranceTeleport>();
				foreach (EntranceTeleport item in componentsInChildren)
				{
					list.Add(item);
				}
			}
			return list;
		}

		internal static void PatchFireEscapes(DungeonGenerator dungeonGenerator, ExtendedLevel extendedLevel, Scene scene)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Expected O, but got Unknown
			string text = "Fire Exit Patch Report, Details Below;\n\n";
			if (!DungeonManager.TryGetExtendedDungeonFlow(dungeonGenerator.DungeonFlow, out var returnExtendedDungeonFlow))
			{
				return;
			}
			List<EntranceTeleport> list = (from o in GetEntranceTeleports(scene)
				orderby o.entranceId
				select o).ToList();
			foreach (EntranceTeleport item in list)
			{
				item.entranceId = list.IndexOf(item);
				item.dungeonFlowId = returnExtendedDungeonFlow.dungeonID;
			}
			text = text + "EntranceTeleport's Found, " + extendedLevel.NumberlessPlanetName + " Contains " + list.Count + " Entrances! ( " + (list.Count - 1) + " Fire Escapes) \n";
			text = text + "Main Entrance: " + ((Object)((Component)list[0]).gameObject).name + " (Entrance ID: " + list[0].entranceId + ") (Dungeon ID: " + list[0].dungeonFlowId + ")\n";
			foreach (EntranceTeleport item2 in list)
			{
				if (item2.entranceId != 0)
				{
					text = text + "Alternate Entrance: " + ((Object)((Component)item2).gameObject).name + " (Entrance ID: " + item2.entranceId + ") (Dungeon ID: " + item2.dungeonFlowId + ")\n";
				}
			}
			foreach (GlobalPropSettings globalProp in dungeonGenerator.DungeonFlow.GlobalProps)
			{
				if (globalProp.ID == 1231)
				{
					text = text + "Found Fire Escape GlobalProp: (ID: 1231), Modifying Spawnrate Count From (" + globalProp.Count.Min + "," + globalProp.Count.Max + ") To (" + (list.Count - 1) + "," + (list.Count - 1) + ")\n";
					globalProp.Count = new IntRange(list.Count - 1, list.Count - 1);
					break;
				}
			}
			DebugHelper.Log(text + "\n");
		}

		public static void PatchDynamicGlobalProps(DungeonGenerator dungeonGenerator, ExtendedDungeonFlow extendedDungeonFlow)
		{
			foreach (GlobalPropCountOverride globalPropCountOverrides in extendedDungeonFlow.globalPropCountOverridesList)
			{
				foreach (GlobalPropSettings globalProp in dungeonGenerator.DungeonFlow.GlobalProps)
				{
					if (globalPropCountOverrides.globalPropID == globalProp.ID)
					{
						globalProp.Count.Min = globalProp.Count.Min * Mathf.RoundToInt(Mathf.Lerp(1f, dungeonGenerator.LengthMultiplier / RoundManager.Instance.mapSizeMultiplier, globalPropCountOverrides.globalPropCountScaleRate));
						globalProp.Count.Max = globalProp.Count.Max * Mathf.RoundToInt(Mathf.Lerp(1f, dungeonGenerator.LengthMultiplier / RoundManager.Instance.mapSizeMultiplier, globalPropCountOverrides.globalPropCountScaleRate));
					}
				}
			}
		}
	}
	public class LevelLoader
	{
		internal static List<MeshCollider> customLevelMeshCollidersList = new List<MeshCollider>();

		internal static async void EnableMeshColliders()
		{
			List<MeshCollider> instansiatedCustomLevelMeshColliders = new List<MeshCollider>();
			int counter = 0;
			MeshCollider[] array = Object.FindObjectsOfType<MeshCollider>();
			foreach (MeshCollider meshCollider in array)
			{
				if (((Object)((Component)meshCollider).gameObject).name.Contains(" (LLL Tracked)"))
				{
					instansiatedCustomLevelMeshColliders.Add(meshCollider);
				}
			}
			Task[] meshColliderEnableTasks = new Task[instansiatedCustomLevelMeshColliders.Count];
			foreach (MeshCollider meshCollider2 in instansiatedCustomLevelMeshColliders)
			{
				meshColliderEnableTasks[counter] = EnableMeshCollider(meshCollider2);
				counter++;
			}
			await Task.WhenAll(meshColliderEnableTasks);
		}

		internal static async Task EnableMeshCollider(MeshCollider meshCollider)
		{
			((Collider)meshCollider).enabled = true;
			((Object)((Component)meshCollider).gameObject).name.Replace(" (LLL Tracked)", "");
			await Task.Yield();
		}

		internal static void UpdateStoryLogs(ExtendedLevel extendedLevel, GameObject sceneRootObject)
		{
			StoryLog[] componentsInChildren = sceneRootObject.GetComponentsInChildren<StoryLog>();
			foreach (StoryLog val in componentsInChildren)
			{
				foreach (StoryLogData storyLog in extendedLevel.storyLogs)
				{
					if (val.storyLogID == storyLog.storyLogID)
					{
						val.storyLogID = storyLog.newStoryLogID;
					}
				}
			}
		}
	}
	public class DungeonManager
	{
		public static ExtendedDungeonFlow CurrentExtendedDungeonFlow
		{
			get
			{
				ExtendedDungeonFlow result = null;
				if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.dungeonGenerator != (Object)null && TryGetExtendedDungeonFlow(RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow, out var returnExtendedDungeonFlow))
				{
					result = returnExtendedDungeonFlow;
				}
				return result;
			}
		}

		internal static void PatchVanillaDungeonLists()
		{
			foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
			{
				customExtendedDungeonFlow.dungeonID = RoundManager.Instance.dungeonFlowTypes.Length;
				RoundManager.Instance.dungeonFlowTypes = CollectionExtensions.AddItem<DungeonFlow>((IEnumerable<DungeonFlow>)RoundManager.Instance.dungeonFlowTypes, customExtendedDungeonFlow.dungeonFlow).ToArray();
				if ((Object)(object)customExtendedDungeonFlow.dungeonFirstTimeAudio != (Object)null)
				{
					RoundManager.Instance.firstTimeDungeonAudios = CollectionExtensions.AddItem<AudioClip>((IEnumerable<AudioClip>)RoundManager.Instance.firstTimeDungeonAudios, customExtendedDungeonFlow.dungeonFirstTimeAudio).ToArray();
				}
			}
		}

		internal static void AddExtendedDungeonFlow(ExtendedDungeonFlow extendedDungeonFlow)
		{
			PatchedContent.ExtendedDungeonFlows.Add(extendedDungeonFlow);
		}

		internal static void TryAddCurrentVanillaLevelDungeonFlow(DungeonGenerator dungeonGenerator, ExtendedLevel currentExtendedLevel)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			if ((Object)(object)dungeonGenerator.DungeonFlow != (Object)null && !RoundManager.Instance.dungeonFlowTypes.ToList().Contains(dungeonGenerator.DungeonFlow))
			{
				DebugHelper.Log("Level: " + currentExtendedLevel.selectableLevel.PlanetName + " Contains DungeonFlow: " + ((Object)dungeonGenerator.DungeonFlow).name + " In DungeonGenerator That Was Not Found In RoundManager, Adding!");
				AssetBundleLoader.CreateVanillaExtendedDungeonFlow(dungeonGenerator.DungeonFlow);
				if (TryGetExtendedDungeonFlow(dungeonGenerator.DungeonFlow, out var returnExtendedDungeonFlow))
				{
					IntWithRarity val = new IntWithRarity();
					val.id = returnExtendedDungeonFlow.dungeonID;
					val.rarity = 300;
					currentExtendedLevel.selectableLevel.dungeonFlowTypes = CollectionExtensions.AddItem<IntWithRarity>((IEnumerable<IntWithRarity>)currentExtendedLevel.selectableLevel.dungeonFlowTypes, val).ToArray();
				}
			}
		}

		internal static List<ExtendedDungeonFlowWithRarity> GetValidExtendedDungeonFlows(ExtendedLevel extendedLevel, bool debugResults)
		{
			string text = "Trying To Find All Matching DungeonFlows For Level: " + extendedLevel.NumberlessPlanetName + "\n";
			List<ExtendedDungeonFlowWithRarity> list = new List<ExtendedDungeonFlowWithRarity>();
			List<ExtendedDungeonFlowWithRarity> list2 = new List<ExtendedDungeonFlowWithRarity>();
			if (extendedLevel.allowedDungeonContentTypes == ContentType.Vanilla || extendedLevel.allowedDungeonContentTypes == ContentType.Any)
			{
				IntWithRarity[] dungeonFlowTypes = extendedLevel.selectableLevel.dungeonFlowTypes;
				foreach (IntWithRarity val in dungeonFlowTypes)
				{
					if (TryGetExtendedDungeonFlow(RoundManager.Instance.dungeonFlowTypes[val.id], out var returnExtendedDungeonFlow))
					{
						if (!Settings.allDungeonFlowsRequireMatching)
						{
							list.Add(new ExtendedDungeonFlowWithRarity(returnExtendedDungeonFlow, val.rarity));
						}
						else
						{
							list2.Add(new ExtendedDungeonFlowWithRarity(returnExtendedDungeonFlow, val.rarity));
						}
					}
				}
			}
			if (extendedLevel.allowedDungeonContentTypes == ContentType.Custom || extendedLevel.allowedDungeonContentTypes == ContentType.Any)
			{
				foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
				{
					list2.Add(new ExtendedDungeonFlowWithRarity(customExtendedDungeonFlow, 0));
				}
			}
			text += "Potential DungeonFlows Collected, List Below: \n";
			foreach (ExtendedDungeonFlowWithRarity item in list.Concat(list2))
			{
				text = text + item.extendedDungeonFlow.dungeonDisplayName + " - " + item.rarity + ", ";
			}
			text = text + "\n\nSelectableLevel - " + extendedLevel.selectableLevel.PlanetName + " Level Tags: ";
			foreach (string levelTag in extendedLevel.levelTags)
			{
				text = text + levelTag + ", ";
			}
			text += "\n";
			foreach (ExtendedDungeonFlowWithRarity item2 in list)
			{
				text = text + "\nDungeonFlow " + (list.IndexOf(item2) + 1) + ". : " + ((Object)item2.extendedDungeonFlow.dungeonFlow).name + " - Matched " + extendedLevel.NumberlessPlanetName + " With A Rarity Of: " + item2.rarity + " Based On The Levels DungeonFlowTypes!\n";
			}
			foreach (ExtendedDungeonFlowWithRarity item3 in new List<ExtendedDungeonFlowWithRarity>(list2))
			{
				string text2 = string.Empty;
				ExtendedDungeonFlow extendedDungeonFlow = item3.extendedDungeonFlow;
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(extendedLevel.contentSourceName, extendedDungeonFlow.manualContentSourceNameReferenceList)))
				{
					text2 = " Based On Content Source Name!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(extendedLevel.NumberlessPlanetName, extendedDungeonFlow.manualPlanetNameReferenceList)))
				{
					text2 = " Based On Planet Name!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingWithinRanges(extendedLevel.RoutePrice, extendedDungeonFlow.dynamicRoutePricesList)))
				{
					text2 = " Based On Route Price!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedStrings(extendedLevel.levelTags, extendedDungeonFlow.dynamicLevelTagsList)))
				{
					text2 = " Based On Level Tags!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(((object)(LevelWeatherType)(ref extendedLevel.selectableLevel.currentWeather)).ToString(), extendedDungeonFlow.dynamicCurrentWeatherList)))
				{
					text2 = " Based On Current Weather!";
				}
				if (text2 != string.Empty)
				{
					text = text + "\nDungeonFlow " + (list2.IndexOf(item3) + 1) + ". : " + ((Object)extendedDungeonFlow.dungeonFlow).name + " - Matched " + extendedLevel.NumberlessPlanetName + " With A Rarity Of: " + item3.rarity + text2 + "\n";
				}
				if (item3.rarity != 0)
				{
					list.Add(item3);
				}
			}
			if (debugResults)
			{
				DebugHelper.Log(text + "\nMatching DungeonFlows Collected, Count Is: " + list.Count + "\n\n");
			}
			return list;
		}

		internal static void RefreshDungeonFlowIDs()
		{
			DebugHelper.Log("Re-Adjusting DungeonFlowTypes Array For Late Arriving Vanilla DungeonFlow");
			List<DungeonFlow> list = new List<DungeonFlow>();
			foreach (ExtendedDungeonFlow vanillaExtendedDungeonFlow in PatchedContent.VanillaExtendedDungeonFlows)
			{
				vanillaExtendedDungeonFlow.dungeonID = list.Count;
				list.Add(vanillaExtendedDungeonFlow.dungeonFlow);
			}
			foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
			{
				customExtendedDungeonFlow.dungeonID = list.Count;
				list.Add(customExtendedDungeonFlow.dungeonFlow);
			}
			RoundManager.Instance.dungeonFlowTypes = list.ToArray();
		}

		internal static int GetHighestRarityViaMatchingWithinRanges(int comparingValue, List<Vector2WithRarity> matchingVectors)
		{
			int num = 0;
			foreach (Vector2WithRarity matchingVector in matchingVectors)
			{
				if (matchingVector.Rarity >= num && (float)comparingValue >= matchingVector.Min && (float)comparingValue <= matchingVector.Max)
				{
					num = matchingVector.Rarity;
				}
			}
			return num;
		}

		internal static int GetHighestRarityViaMatchingNormalizedString(string comparingString, List<StringWithRarity> matchingStrings)
		{
			return GetHighestRarityViaMatchingNormalizedStrings(new List<string> { comparingString }, matchingStrings);
		}

		internal static int GetHighestRarityViaMatchingNormalizedStrings(List<string> comparingStrings, List<StringWithRarity> matchingStrings)
		{
			int num = 0;
			foreach (StringWithRarity matchingString in matchingStrings)
			{
				foreach (string item in new List<string>(comparingStrings))
				{
					if (matchingString.Rarity >= num && (matchingString.Name.Sanitized().Contains(item.Sanitized()) || item.Sanitized().Contains(matchingString.Name.Sanitized())))
					{
						num = matchingString.Rarity;
					}
				}
			}
			return num;
		}

		internal static bool TryGetExtendedDungeonFlow(DungeonFlow dungeonFlow, out ExtendedDungeonFlow returnExtendedDungeonFlow, ContentType contentType = ContentType.Any)
		{
			returnExtendedDungeonFlow = null;
			List<ExtendedDungeonFlow> list = null;
			if ((Object)(object)dungeonFlow == (Object)null)
			{
				return false;
			}
			switch (contentType)
			{
			case ContentType.Any:
				list = PatchedContent.ExtendedDungeonFlows;
				break;
			case ContentType.Custom:
				list = PatchedContent.CustomExtendedDungeonFlows;
				break;
			case ContentType.Vanilla:
				list = PatchedContent.VanillaExtendedDungeonFlows;
				break;
			}
			foreach (ExtendedDungeonFlow item in list)
			{
				if ((Object)(object)item.dungeonFlow == (Object)(object)dungeonFlow)
				{
					returnExtendedDungeonFlow = item;
				}
			}
			return (Object)(object)returnExtendedDungeonFlow != (Object)null;
		}
	}
	public class LethalLevelLoaderNetworkManager : NetworkBehaviour
	{
		public static GameObject networkingManagerPrefab;

		private static LethalLevelLoaderNetworkManager _instance;

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

		public static bool networkHasStarted;

		public static LethalLevelLoaderNetworkManager Instance
		{
			get
			{
				if ((Object)(object)_instance == (Object)null)
				{
					_instance = Object.FindObjectOfType<LethalLevelLoaderNetworkManager>();
				}
				if ((Object)(object)_instance == (Object)null)
				{
					DebugHelper.LogWarning("LethalLevelLoaderNetworkManager Could Not Be Found! Returning Null!");
				}
				return _instance;
			}
			set
			{
				_instance = value;
			}
		}

		public override void OnNetworkSpawn()
		{
			((NetworkBehaviour)this).OnNetworkSpawn();
			((Object)((Component)this).gameObject).name = "LethalLevelLoaderNetworkManager";
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		[ServerRpc]
		public void GetRandomExtendedDungeonFlowServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(12573863u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 12573863u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			DebugHelper.Log("Getting Random DungeonFlows!");
			List<ExtendedDungeonFlowWithRarity> validExtendedDungeonFlows = DungeonManager.GetValidExtendedDungeonFlows(LevelManager.CurrentExtendedLevel, debugResults: true);
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			if (validExtendedDungeonFlows.Count == 0)
			{
				DebugHelper.LogError("No ExtendedDungeonFlow's could be found! This should only happen if the Host's requireMatchesOnAllDungeonFlows is set to true!");
				DebugHelper.LogError("Loading Facility DungeonFlow to prevent infinite loading!");
				list.Add(0);
				list2.Add(300);
			}
			else
			{
				foreach (ExtendedDungeonFlowWithRarity item in validExtendedDungeonFlows)
				{
					list.Add(RoundManager.Instance.dungeonFlowTypes.ToList().IndexOf(item.extendedDungeonFlow.dungeonFlow));
					list2.Add(item.rarity);
				}
			}
			SetRandomExtendedDungeonFlowClientRpc(list.ToArray(), list2.ToArray());
		}

		[ClientRpc]
		public void SetRandomExtendedDungeonFlowClientRpc(int[] dungeonFlowIDs, int[] rarities)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_00d3: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: 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_00fd: 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_0174: Expected O, but got Unknown
			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(1934987400u, val, (RpcDelivery)0);
				bool flag = dungeonFlowIDs != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(dungeonFlowIDs, default(ForPrimitives));
				}
				bool flag2 = rarities != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(rarities, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1934987400u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				DebugHelper.Log("Setting Random DungeonFlows!");
				List<IntWithRarity> list = new List<IntWithRarity>();
				List<IntWithRarity> list2 = new List<IntWithRarity>();
				for (int i = 0; i < dungeonFlowIDs.Length; i++)
				{
					IntWithRarity val3 = new IntWithRarity();
					val3.Add(dungeonFlowIDs[i], rarities[i]);
					list.Add(val3);
				}
				list2 = new List<IntWithRarity>(LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes.ToList());
				LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes = list.ToArray();
				RoundManager.Instance.GenerateNewFloor();
				LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes = list2.ToArray();
			}
		}

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

		[ClientRpc]
		public void SetDungeonFlowSizeClientRpc(float hostSize)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1778200789u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref hostSize, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1778200789u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					RoundManager.Instance.dungeonGenerator.Generator.LengthMultiplier = hostSize;
					RoundManager.Instance.dungeonGenerator.Generate();
				}
			}
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!networkHasStarted)
			{
				queuedNetworkPrefabs.Add(prefab);
			}
			else
			{
				DebugHelper.Log("Attempted To Register NetworkPrefab: " + ((object)prefab)?.ToString() + " After GameNetworkManager Has Started!");
			}
		}

		internal static void RegisterPrefabs(NetworkManager networkManager)
		{
			List<GameObject> list = new List<GameObject>();
			foreach (NetworkPrefab prefab in networkManager.NetworkConfig.Prefabs.m_Prefabs)
			{
				list.Add(prefab.Prefab);
			}
			int num = 0;
			foreach (GameObject queuedNetworkPrefab in queuedNetworkPrefabs)
			{
				if (!list.Contains(queuedNetworkPrefab))
				{
					networkManager.AddNetworkPrefab(queuedNetworkPrefab);
					list.Add(queuedNetworkPrefab);
				}
				else
				{
					num++;
				}
			}
			DebugHelper.Log("Skipped Registering " + num + " NetworkObjects As They Were Already Registered.");
			networkHasStarted = true;
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_LethalLevelLoaderNetworkManager()
		{
			//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
			NetworkManager.__rpc_func_table.Add(12573863u, new RpcReceiveHandler(__rpc_handler_12573863));
			NetworkManager.__rpc_func_table.Add(1934987400u, new RpcReceiveHandler(__rpc_handler_1934987400));
			NetworkManager.__rpc_func_table.Add(1367970965u, new RpcReceiveHandler(__rpc_handler_1367970965));
			NetworkManager.__rpc_func_table.Add(1778200789u, new RpcReceiveHandler(__rpc_handler_1778200789));
		}

		private static void __rpc_handler_12573863(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;
				((LethalLevelLoaderNetworkManager)(object)target).GetRandomExtendedDungeonFlowServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1934987400(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_0074: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_009d: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				int[] dungeonFlowIDs = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref dungeonFlowIDs, default(ForPrimitives));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				int[] rarities = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref rarities, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LethalLevelLoaderNetworkManager)(object)target).SetRandomExtendedDungeonFlowClientRpc(dungeonFlowIDs, rarities);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1367970965(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;
				((LethalLevelLoaderNetworkManager)(object)target).GetDungeonFlowSizeServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1778200789(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)
			{
				float dungeonFlowSizeClientRpc = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref dungeonFlowSizeClientRpc, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LethalLevelLoaderNetworkManager)(object)target).SetDungeonFlowSizeClientRpc(dungeonFlowSizeClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "LethalLevelLoaderNetworkManager";
		}
	}
	public class LevelManager
	{
		public static List<DayHistory> dayHistoryList = new List<DayHistory>();

		public static int daysTotal;

		public static int quotasTotal;

		public static int invalidSaveLevelID = -1;

		public static ExtendedLevel CurrentExtendedLevel
		{
			get
			{
				ExtendedLevel result = null;
				if ((Object)(object)StartOfRound.Instance != (Object)null && TryGetExtendedLevel(StartOfRound.Instance.currentLevel, out var returnExtendedLevel))
				{
					result = returnExtendedLevel;
				}
				return result;
			}
		}

		internal static void ValidateLevelLists()
		{
			List<SelectableLevel> list = new List<SelectableLevel>(OriginalContent.SelectableLevels);
			List<SelectableLevel> list2 = new List<SelectableLevel>(OriginalContent.MoonsCatalogue);
			List<SelectableLevel> list3 = new List<SelectableLevel>(StartOfRound.Instance.levels);
			foreach (SelectableLevel item in new List<SelectableLevel>(list))
			{
				if (item.levelID > 8)
				{
					list.Remove(item);
				}
			}
			foreach (SelectableLevel item2 in new List<SelectableLevel>(list2))
			{
				if (item2.levelID > 8)
				{
					list2.Remove(item2);
				}
			}
			foreach (SelectableLevel item3 in new List<SelectableLevel>(list3))
			{
				if (item3.levelID > 8)
				{
					list3.Remove(item3);
				}
			}
			OriginalContent.SelectableLevels = list;
			OriginalContent.MoonsCatalogue = list2;
			PatchVanillaLevelLists();
		}

		internal static void PatchVanillaLevelLists()
		{
			StartOfRound.Instance.levels = PatchedContent.SeletectableLevels.ToArray();
			TerminalManager.Terminal.moonsCatalogueList = PatchedContent.MoonsCatalogue.ToArray();
		}

		internal static void RefreshCustomExtendedLevelIDs()
		{
			foreach (ExtendedLevel item in new List<ExtendedLevel>(PatchedContent.CustomExtendedLevels))
			{
				if (!item.isLethalExpansion)
				{
					item.SetLevelID();
				}
			}
		}

		internal static void RefreshLethalExpansionMoons()
		{
			foreach (ExtendedLevel customExtendedLevel in PatchedContent.CustomExtendedLevels)
			{
				if (!customExtendedLevel.isLethalExpansion)
				{
					continue;
				}
				CompatibleNoun[] compatibleNouns = TerminalManager.routeKeyword.compatibleNouns;
				foreach (CompatibleNoun val in compatibleNouns)
				{
					if (((Object)val.noun).name.ToLower().Contains(customExtendedLevel.NumberlessPlanetName.ToLower()))
					{
						customExtendedLevel.routeNode = val.result;
						customExtendedLevel.routeConfirmNode = val.result.terminalOptions[1].result;
						customExtendedLevel.RoutePrice = customExtendedLevel.routeNode.itemCost;
						break;
					}
				}
			}
			RefreshCustomExtendedLevelIDs();
		}

		public static bool TryGetExtendedLevel(SelectableLevel selectableLevel, out ExtendedLevel returnExtendedLevel, ContentType levelType = ContentType.Any)
		{
			returnExtendedLevel = null;
			List<ExtendedLevel> list = null;
			if ((Object)(object)selectableLevel == (Object)null)
			{
				return false;
			}
			switch (levelType)
			{
			case ContentType.Any:
				list = PatchedContent

plugins/LethalLib.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.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.14.2.0")]
[assembly: AssemblyInformationalVersion("0.14.2+553a3b4022b798db3343e7463a3d6d5d90b37d0e")]
[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.14.2")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.14.2";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		public static ConfigEntry<bool> extendedLogging;

		private void Awake()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_0092: 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!!");
			extendedLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging");
			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.14.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);
							if (Plugin.extendedLogging.Value)
							{
								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);
								if (Plugin.extendedLogging.Value)
								{
									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 hook_Start <2>__QuickMenuManager_Start;
		}

		private static bool addedToDebug = false;

		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
			//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>__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;
			object obj3 = <>O.<2>__QuickMenuManager_Start;
			if (obj3 == null)
			{
				hook_Start val3 = QuickMenuManager_Start;
				<>O.<2>__QuickMenuManager_Start = val3;
				obj3 = (object)val3;
			}
			QuickMenuManager.Start += (hook_Start)obj3;
		}

		private static void QuickMenuManager_Start(orig_Start orig, QuickMenuManager self)
		{
			//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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			if (addedToDebug)
			{
				orig.Invoke(self);
				return;
			}
			SelectableLevel testAllEnemiesLevel = self.testAllEnemiesLevel;
			List<SpawnableEnemyWithRarity> enemies = testAllEnemiesLevel.Enemies;
			List<SpawnableEnemyWithRarity> daytimeEnemies = testAllEnemiesLevel.DaytimeEnemies;
			List<SpawnableEnemyWithRarity> outsideEnemies = testAllEnemiesLevel.OutsideEnemies;
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (enemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
				{
					continue;
				}
				SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
				{
					enemyType = spawnableEnemy.enemy,
					rarity = spawnableEnemy.rarity
				};
				switch (spawnableEnemy.spawnType)
				{
				case SpawnType.Default:
					if (!enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						enemies.Add(item);
					}
					break;
				case SpawnType.Daytime:
					if (!daytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						daytimeEnemies.Add(item);
					}
					break;
				case SpawnType.Outside:
					if (!outsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						outsideEnemies.Add(item);
					}
					break;
				}
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {spawnableEnemy.enemy.enemyName} to DebugList [{spawnableEnemy.spawnType}]");
				}
			}
			addedToDebug = true;
			orig.Invoke(self);
		}

		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);
							if (Plugin.extendedLogging.Value)
							{
								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);
							if (Plugin.extendedLogging.Value)
							{
								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);
							if (Plugin.extendedLogging.Value)
							{
								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;
				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 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_0855: Unknown result type (might be due to invalid IL or missing references)
			//IL_085a: Unknown result type (might be due to invalid IL or missing references)
			//IL_088f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0898: Expected O, but got Unknown
			//IL_089a: Unknown result type (might be due to invalid IL or missing references)
			//IL_089f: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_08dc: Expected O, but got Unknown
			//IL_093f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0944: Unknown result type (might be due to invalid IL or missing references)
			//IL_094c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0959: Expected O, but got Unknown
			//IL_09e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_09eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a00: 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);
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)scrapItem.item).name + " to " + name));
						}
					}
				}
			}
			foreach (ScrapItem scrapItem2 in scrapItems)
			{
				if (instance.allItemsList.itemsList.Contains(scrapItem2.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					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))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					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))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					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;
				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;
				}
				val4.buyItemIndex = buyItemIndex;
				val4.isConfirmationNode = false;
				val4.itemCost = item.price;
				val4.playSyncedClip = 0;
				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;
				}
				val5.buyItemIndex = buyItemIndex;
				val5.isConfirmationNode = true;
				val5.overrideOptions = true;
				val5.itemCost = item.price;
				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);
				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;
				}
				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);
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {itemName} to terminal (Item price: {val5.itemCost}, Item Index: {val5.buyItemIndex}, Terminal keyword: {val6.word})");
				}
			}
			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();
						if (Plugin.extendedLogging.Value)
						{
							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();
						if (Plugin.extendedLogging.Value)
						{
							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_0473: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b6: Expected O, but got Unknown
			//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fa: Expected O, but got Unknown
			//IL_0576: 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_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_0595: Expected O, but got Unknown
			//IL_0621: Unknown result type (might be due to invalid IL or missing references)
			//IL_0626: Unknown result type (might be due to invalid IL or missing references)
			//IL_0633: Unknown result type (might be due to invalid IL or missing references)
			//IL_0640: Expected O, but got Unknown
			StartOfR

plugins/LethalNetworkAPI/LethalNetworkAPI.dll

Decompiled 9 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.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalNetworkAPI.NetcodePatcher;
using LethalNetworkAPI.Networking;
using LethalNetworkAPI.Serializable;
using Microsoft.CodeAnalysis;
using OdinSerializer;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RegisterFormatter(typeof(NetworkBehaviourReferenceFormatter), 0)]
[assembly: RegisterFormatter(typeof(NetworkObjectReferenceFormatter), 0)]
[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("Xilophor")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Easily create networked mods.")]
[assembly: AssemblyFileVersion("2.1.6.0")]
[assembly: AssemblyInformationalVersion("2.1.6+2b8f80905fe30276fc377fd0534a4383a6ae9dc2")]
[assembly: AssemblyProduct("LethalNetworkAPI")]
[assembly: AssemblyTitle("LethalNetworkAPI")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Xilophor/LethalNetworkAPI")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.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 LethalNetworkAPI
{
	public sealed class LethalClientEvent : LNetworkEvent
	{
		public event Action? OnReceived;

		public event Action<ulong>? OnReceivedFromClient;

		public LethalClientEvent(string identifier, Action? onReceived = null, Action<ulong>? onReceivedFromClient = null)
			: base(identifier)
		{
			NetworkHandler.OnClientEvent += ReceiveClientEvent;
			NetworkHandler.OnSyncedClientEvent += ReceiveSyncedClientEvent;
			OnReceived += onReceived;
			OnReceivedFromClient += onReceivedFromClient;
		}

		public void InvokeServer()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull())
			{
				NetworkHandler.Instance.EventServerRpc(Identifier);
			}
		}

		public void InvokeAllClients(bool includeLocalClient = true, bool waitForServerResponse = false)
		{
			//IL_001b: 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)
			if (!IsNetworkHandlerNull())
			{
				NetworkHandler.Instance.EventServerRpc(Identifier, toOtherClients: true, includeLocalClient && waitForServerResponse);
				if (includeLocalClient && !waitForServerResponse)
				{
					this.OnReceivedFromClient?.Invoke(NetworkManager.Singleton.LocalClientId);
				}
			}
		}

		public void InvokeAllClientsSynced()
		{
			//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_002b: 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)
			if (!IsNetworkHandlerNull())
			{
				NetworkTime localTime = NetworkManager.Singleton.LocalTime;
				double time = ((NetworkTime)(ref localTime)).Time;
				NetworkHandler.Instance.SyncedEventServerRpc(Identifier, time);
				ReceiveClientEvent(Identifier, NetworkManager.Singleton.LocalClientId);
			}
		}

		private void ReceiveClientEvent(string identifier, ulong originatorClientId)
		{
			if (!(identifier != Identifier))
			{
				if (originatorClientId == 99999)
				{
					this.OnReceived?.Invoke();
				}
				else
				{
					this.OnReceivedFromClient?.Invoke(originatorClientId);
				}
			}
		}

		private void ReceiveSyncedClientEvent(string identifier, double time, ulong originatorClientId)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!(identifier != Identifier) && !((Object)(object)NetworkHandler.Instance == (Object)null))
			{
				NetworkTime serverTime = NetworkManager.Singleton.ServerTime;
				double num = time - ((NetworkTime)(ref serverTime)).Time;
				((MonoBehaviour)NetworkHandler.Instance).StartCoroutine(WaitAndInvokeEvent((float)num, originatorClientId));
			}
		}

		private IEnumerator WaitAndInvokeEvent(float timeToWait, ulong originatorClientId)
		{
			if (timeToWait > 0f)
			{
				yield return (object)new WaitForSeconds(timeToWait);
			}
			ReceiveClientEvent(Identifier, originatorClientId);
		}
	}
	public sealed class LethalServerEvent : LNetworkEvent
	{
		public event Action<ulong>? OnReceived;

		public LethalServerEvent(string identifier, Action<ulong>? onReceived = null)
			: base(identifier)
		{
			NetworkHandler.OnServerEvent += ReceiveServerEvent;
			NetworkHandler.OnSyncedServerEvent += ReceiveSyncedServerEvent;
			OnReceived += onReceived;
		}

		public void InvokeClient(ulong clientId)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				NetworkHandler.Instance.EventClientRpc(Identifier, 99999uL, GenerateClientParams(clientId));
			}
		}

		public void InvokeClients(IEnumerable<ulong> clientIds)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				NetworkHandler.Instance.EventClientRpc(Identifier, 99999uL, GenerateClientParams(clientIds));
			}
		}

		public void InvokeAllClients(bool receiveOnHost = true)
		{
			//IL_0048: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				if (receiveOnHost)
				{
					NetworkHandler.Instance.EventClientRpc(Identifier, 99999uL);
				}
				else
				{
					NetworkHandler.Instance.EventClientRpc(Identifier, 99999uL, GenerateClientParamsExceptHost());
				}
			}
		}

		private void ReceiveServerEvent(string identifier, ulong originClientId)
		{
			if (!(identifier != Identifier))
			{
				this.OnReceived?.Invoke(originClientId);
			}
		}

		private void ReceiveSyncedServerEvent(string identifier, double time, ulong originatorClientId)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!(identifier != Identifier) && !IsNetworkHandlerNull())
			{
				NetworkTime serverTime = NetworkManager.Singleton.ServerTime;
				double num = time - ((NetworkTime)(ref serverTime)).Time;
				NetworkHandler.Instance.SyncedEventClientRpc(identifier, time, originatorClientId, GenerateClientParamsExcept(originatorClientId));
				((MonoBehaviour)NetworkHandler.Instance).StartCoroutine(WaitAndInvokeEvent((float)num, originatorClientId));
			}
		}

		private IEnumerator WaitAndInvokeEvent(float timeToWait, ulong clientId)
		{
			if (timeToWait > 0f)
			{
				yield return (object)new WaitForSeconds(timeToWait);
			}
			this.OnReceived?.Invoke(clientId);
		}
	}
	public abstract class LNetworkEvent : LethalNetwork
	{
		protected LNetworkEvent(string identifier)
			: base("evt." + identifier, "Event")
		{
		}
	}
	public abstract class LethalNetwork
	{
		internal readonly string Identifier;

		private readonly string _networkType;

		protected LethalNetwork(string identifier, string networkType, int frameIndex = 3)
		{
			try
			{
				MethodBase method = new StackTrace().GetFrame(frameIndex).GetMethod();
				Assembly assembly = method.ReflectedType.Assembly;
				Type type2 = AccessTools.GetTypesFromAssembly(assembly).First((Type type) => type.GetCustomAttributes(typeof(BepInPlugin), inherit: false).Any());
				Identifier = MetadataHelper.GetMetadata(type2).GUID + "." + identifier;
				_networkType = networkType;
			}
			catch (Exception arg)
			{
				LethalNetworkAPIPlugin.Logger.LogError((object)$"Unable to find plugin info for calling mod for {_networkType.ToLower()} with identifier \"{Identifier}\". Are you using BepInEx? \n Stacktrace: {arg}");
			}
		}

		protected bool IsNetworkHandlerNull(bool log = true)
		{
			if ((Object)(object)NetworkHandler.Instance != (Object)null)
			{
				return false;
			}
			if (log)
			{
				LethalNetworkAPIPlugin.Logger.LogError((object)string.Format("Unable to invoke the {1} with identifier \"{0}\". Is the player in a lobby?", _networkType.ToLower(), Identifier));
			}
			return true;
		}

		protected bool IsHostOrServer(bool log = true)
		{
			if ((Object)(object)NetworkManager.Singleton == (Object)null)
			{
				return false;
			}
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				return true;
			}
			if (log)
			{
				LethalNetworkAPIPlugin.Logger.LogError((object)$"The client {NetworkManager.Singleton.LocalClientId} cannot use server methods. {_networkType} Identifier: \"{Identifier}\"");
			}
			return false;
		}

		private bool DoClientsExist(IEnumerable<ulong> clientIds, bool log = true)
		{
			if (clientIds.Any())
			{
				return true;
			}
			if (log)
			{
				LethalNetworkAPIPlugin.Logger.LogError((object)$"None of the specified clients {clientIds} are connected. {_networkType} Identifier: \"{Identifier}\"");
			}
			return false;
		}

		private ClientRpcParams GenerateClientParams(IEnumerable<ulong> clientIds, bool allExcept)
		{
			//IL_00d0: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: 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)
			ulong[] enumerable = (clientIds as ulong[]) ?? clientIds.ToArray();
			NativeArray<ulong> val = default(NativeArray<ulong>);
			if (!enumerable.Any() && allExcept)
			{
				val..ctor(NetworkManager.Singleton.ConnectedClientsIds.Where((ulong i) => i != 0).ToArray(), (Allocator)4);
			}
			else if (allExcept)
			{
				val..ctor(NetworkManager.Singleton.ConnectedClientsIds.Where((ulong i) => enumerable.All((ulong j) => i != j)).ToArray(), (Allocator)4);
			}
			else
			{
				val..ctor(enumerable.Where((ulong i) => NetworkManager.Singleton.ConnectedClientsIds.Contains(i)).ToArray(), (Allocator)4);
			}
			if (!DoClientsExist((IEnumerable<ulong>)(object)val))
			{
				return default(ClientRpcParams);
			}
			ClientRpcParams result = default(ClientRpcParams);
			result.Send = new ClientRpcSendParams
			{
				TargetClientIdsNativeArray = val
			};
			return result;
		}

		protected ClientRpcParams GenerateClientParams(IEnumerable<ulong> clientIds)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return GenerateClientParams(clientIds, allExcept: false);
		}

		protected ClientRpcParams GenerateClientParams(ulong clientId)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return GenerateClientParams(new <>z__ReadOnlyArray<ulong>(new ulong[1] { clientId }), allExcept: false);
		}

		protected ClientRpcParams GenerateClientParamsExcept(IEnumerable<ulong> clientIds)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return GenerateClientParams(clientIds, allExcept: true);
		}

		protected ClientRpcParams GenerateClientParamsExcept(ulong clientId)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return GenerateClientParams(new <>z__ReadOnlyArray<ulong>(new ulong[1] { clientId }), allExcept: true);
		}

		protected ClientRpcParams GenerateClientParamsExceptHost()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return GenerateClientParams(Array.Empty<ulong>(), allExcept: true);
		}
	}
	[BepInPlugin("LethalNetworkAPI", "LethalNetworkAPI", "2.1.6")]
	public class LethalNetworkAPIPlugin : BaseUnityPlugin
	{
		public static LethalNetworkAPIPlugin Instance;

		private static Harmony _harmony;

		internal static ManualLogSource Logger { get; private set; }

		private void Awake()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			Instance = this;
			Logger = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("LethalNetworkAPI");
			NetcodePatcher();
			_harmony.PatchAll(typeof(NetworkObjectManager));
			Logger.LogInfo((object)"LethalNetworkAPI v2.1.6 has Loaded.");
		}

		private static void NetcodePatcher()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
	public static class LethalNetworkExtensions
	{
		public static PlayerControllerB? GetPlayerController(this ulong clientId)
		{
			return StartOfRound.Instance.allPlayerScripts[StartOfRound.Instance.ClientPlayerList[clientId]];
		}

		[Obsolete("GetPlayerFromId is deprecated, please use GetPlayerController instead.")]
		public static PlayerControllerB? GetPlayerFromId(this ulong clientId)
		{
			return clientId.GetPlayerController();
		}

		public static ulong GetClientId(this PlayerControllerB player)
		{
			return player.actualClientId;
		}

		public static LethalNetworkVariable<TData>? GetNetworkVariable<TData>(this NetworkBehaviour networkBehaviour, string identifier, bool serverOwned = false)
		{
			return ((Component)networkBehaviour).gameObject.NetworkVariable<TData>(identifier, serverOwned);
		}

		public static LethalNetworkVariable<TData>? GetNetworkVariable<TData>(this NetworkObject networkObject, string identifier, bool serverOwned = false)
		{
			return ((Component)networkObject).gameObject.NetworkVariable<TData>(identifier, serverOwned);
		}

		public static LethalNetworkVariable<TData>? GetNetworkVariable<TData>(this GameObject gameObject, string identifier, bool serverOwned = false)
		{
			return gameObject.NetworkVariable<TData>(identifier, serverOwned);
		}

		private static LethalNetworkVariable<TData>? NetworkVariable<TData>(this GameObject gameObject, string identifier, bool serverOwned)
		{
			string identifier2 = identifier;
			NetworkObject networkObjectComp = default(NetworkObject);
			if (!gameObject.TryGetComponent<NetworkObject>(ref networkObjectComp))
			{
				LethalNetworkAPIPlugin.Logger.LogError((object)$"Unable to find the network object component. Are you adding variable \"{identifier2}\" to a network object?");
				return null;
			}
			LethalNetworkVariable<TData> lethalNetworkVariable = (LethalNetworkVariable<TData>)NetworkHandler.Instance.ObjectNetworkVariableList.FirstOrDefault((ILethalNetVar i) => ((LethalNetworkVariable<TData>)i).Identifier == $"{identifier2}.{networkObjectComp.GlobalObjectIdHash}");
			if (lethalNetworkVariable != null)
			{
				return lethalNetworkVariable;
			}
			lethalNetworkVariable = new LethalNetworkVariable<TData>($"{identifier2}.{networkObjectComp.GlobalObjectIdHash}", networkObjectComp, serverOwned, 3);
			NetworkHandler.Instance.ObjectNetworkVariableList.Add(lethalNetworkVariable);
			return lethalNetworkVariable;
		}
	}
	public sealed class LethalClientMessage<TData> : LNetworkMessage
	{
		public event Action<TData>? OnReceived;

		public event Action<TData, ulong>? OnReceivedFromClient;

		public LethalClientMessage(string identifier, Action<TData>? onReceived = null, Action<TData, ulong>? onReceivedFromClient = null)
			: base(identifier)
		{
			NetworkHandler.OnClientMessage += ReceiveMessage;
			OnReceived += onReceived;
			OnReceivedFromClient += onReceivedFromClient;
		}

		public void SendServer(TData data)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull())
			{
				NetworkHandler.Instance.MessageServerRpc(Identifier, LethalNetworkSerializer.Serialize(data));
			}
		}

		public void SendAllClients(TData data, bool includeLocalClient = true, bool waitForServerResponse = false)
		{
			//IL_0021: 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)
			if (!IsNetworkHandlerNull())
			{
				NetworkHandler.Instance.MessageServerRpc(Identifier, LethalNetworkSerializer.Serialize(data), toOtherClients: true, includeLocalClient && waitForServerResponse);
				if (includeLocalClient && !waitForServerResponse)
				{
					this.OnReceivedFromClient?.Invoke(data, NetworkManager.Singleton.LocalClientId);
				}
			}
		}

		private void ReceiveMessage(string identifier, byte[] data, ulong originatorClient)
		{
			if (!(identifier != Identifier))
			{
				if (originatorClient == 99999)
				{
					this.OnReceived?.Invoke(LethalNetworkSerializer.Deserialize<TData>(data));
				}
				else
				{
					this.OnReceivedFromClient?.Invoke(LethalNetworkSerializer.Deserialize<TData>(data), originatorClient);
				}
			}
		}
	}
	public class LethalServerMessage<TData> : LNetworkMessage
	{
		public event Action<TData, ulong>? OnReceived;

		public LethalServerMessage(string identifier, Action<TData, ulong>? onReceived = null)
			: base(identifier)
		{
			NetworkHandler.OnServerMessage += ReceiveServerMessage;
			OnReceived += onReceived;
		}

		public void SendClient(TData data, ulong clientId)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				NetworkHandler.Instance.MessageClientRpc(Identifier, LethalNetworkSerializer.Serialize(data), 99999uL, GenerateClientParams(clientId));
			}
		}

		public void SendClients(TData data, IEnumerable<ulong> clientIds)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				NetworkHandler.Instance.MessageClientRpc(Identifier, LethalNetworkSerializer.Serialize(data), 99999uL, GenerateClientParams(clientIds));
			}
		}

		public void SendAllClients(TData data, bool receiveOnHost = true)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				if (receiveOnHost)
				{
					NetworkHandler.Instance.MessageClientRpc(Identifier, LethalNetworkSerializer.Serialize(data), 99999uL);
				}
				else
				{
					NetworkHandler.Instance.MessageClientRpc(Identifier, LethalNetworkSerializer.Serialize(data), 99999uL, GenerateClientParamsExceptHost());
				}
			}
		}

		private void ReceiveServerMessage(string identifier, byte[] data, ulong originClientId)
		{
			if (!(identifier != Identifier))
			{
				this.OnReceived?.Invoke(LethalNetworkSerializer.Deserialize<TData>(data), originClientId);
			}
		}
	}
	public abstract class LNetworkMessage : LethalNetwork
	{
		protected LNetworkMessage(string identifier)
			: base("msg." + identifier, "Message")
		{
		}
	}
	internal static class TextDefinitions
	{
		internal const string NotInLobbyMessage = "Unable to send the {0} with identifier \"{1}\" and data {{{2}}}. Is the player in a lobby?";

		internal const string UnableToFindGuid = "Unable to find plugin info for calling mod for {0} with identifier \"{1}\". Are you using BepInEx? \n Stacktrace: {2}";

		internal const string NotServerInfo = "The client {0} cannot use server methods. {1} Identifier: \"{2}\"";

		internal const string NotInLobbyEvent = "Unable to invoke the {1} with identifier \"{0}\". Is the player in a lobby?";

		internal const string NetworkHandlerDoesNotExist = "The NetworkHandler does not exist. This shouldn't occur!";

		internal const string TargetClientNotConnected = "The specified client {0} is not connected. {1} Identifier: \"{2}\"";

		internal const string TargetClientsNotConnected = "None of the specified clients {0} are connected. {1} Identifier: \"{2}\"";

		internal const string UnableToLocateNetworkObjectComponent = "Unable to find the network object component. Are you adding variable \"{0}\" to a network object?";
	}
	internal interface ILethalNetVar
	{
	}
	public sealed class LethalNetworkVariable<TData> : LethalNetwork, ILethalNetVar
	{
		private readonly bool _public;

		private readonly NetworkObject? _ownerObject;

		private bool _isDirty;

		private TData _value;

		public TData Value
		{
			get
			{
				return _value;
			}
			set
			{
				if (IsOwner && (value != null || _value != null) && (value == null || !value.Equals(_value)))
				{
					_value = value;
					_isDirty = true;
					this.OnValueChanged?.Invoke(_value);
				}
			}
		}

		private bool IsOwner
		{
			get
			{
				if (_public)
				{
					return true;
				}
				if ((Object)(object)NetworkManager.Singleton == (Object)null)
				{
					return true;
				}
				if (_ownerObject == null && NetworkManager.Singleton.IsServer)
				{
					return true;
				}
				if (_ownerObject != null)
				{
					return _ownerObject.OwnerClientId == NetworkManager.Singleton.LocalClientId;
				}
				return false;
			}
		}

		public event Action<TData>? OnValueChanged;

		public LethalNetworkVariable(string identifier)
			: this(identifier, (NetworkObject?)null, serverOwned: true, 2)
		{
		}

		internal LethalNetworkVariable(string identifier, NetworkObject? owner, bool serverOwned, int frameIndex)
			: base(identifier, "Variable", frameIndex + 1)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			_ownerObject = ((!serverOwned) ? owner : null);
			NetworkHandler.OnVariableUpdate += ReceiveUpdate;
			NetworkHandler.NetworkTick += OnNetworkTick;
			NetworkHandler.NetworkSpawn += delegate
			{
				if (!IsNetworkHandlerNull() && IsHostOrServer(log: false))
				{
					NetworkHandler.OnPlayerJoin += OnPlayerJoin;
					NetworkHandler.NetworkDespawn += ClearSubscriptions;
				}
			};
			NetworkHandler.GetVariableValue += delegate(string id, ulong clientId)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				if (!(id != Identifier) && !IsNetworkHandlerNull() && IsHostOrServer())
				{
					NetworkHandler.Instance.UpdateVariableClientRpc(Identifier, LethalNetworkSerializer.Serialize(_value), GenerateClientParams(clientId));
				}
			};
			if (typeof(LethalNetworkVariable<TData>).GetCustomAttributes(typeof(PublicNetworkVariableAttribute), inherit: true).Any())
			{
				_public = true;
			}
			if (!IsNetworkHandlerNull(log: false))
			{
				if (IsHostOrServer())
				{
					NetworkHandler.OnPlayerJoin += OnPlayerJoin;
				}
				else
				{
					NetworkHandler.Instance.GetVariableValueServerRpc(Identifier);
				}
			}
		}

		private void OnPlayerJoin(ulong clientId)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsHostOrServer())
			{
				NetworkHandler.Instance.UpdateVariableClientRpc(Identifier, LethalNetworkSerializer.Serialize(_value), GenerateClientParams(clientId));
			}
		}

		private void ClearSubscriptions()
		{
			NetworkHandler.OnPlayerJoin -= OnPlayerJoin;
			NetworkHandler.NetworkDespawn -= ClearSubscriptions;
		}

		private void SendUpdate()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!IsNetworkHandlerNull() && IsOwner)
			{
				NetworkHandler.Instance.UpdateVariableServerRpc(Identifier, LethalNetworkSerializer.Serialize(_value));
			}
		}

		private void ReceiveUpdate(string identifier, byte[] data)
		{
			if (!(identifier != Identifier))
			{
				TData val = LethalNetworkSerializer.Deserialize<TData>(data);
				if (val != null)
				{
					_value = val;
					this.OnValueChanged?.Invoke(val);
				}
			}
		}

		private void OnNetworkTick()
		{
			if (_isDirty && _value != null)
			{
				SendUpdate();
				_isDirty = false;
			}
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public class PublicNetworkVariableAttribute : Attribute
	{
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalNetworkAPI";

		public const string PLUGIN_NAME = "LethalNetworkAPI";

		public const string PLUGIN_VERSION = "2.1.6";
	}
}
namespace LethalNetworkAPI.Serializable
{
	internal static class LethalNetworkSerializer
	{
		internal static byte[] Serialize<T>(T value)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (value == null)
			{
				return Array.Empty<byte>();
			}
			object obj = value;
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if (val != null)
			{
				return SerializationUtility.SerializeValue<NetworkObjectReference>(NetworkObjectReference.op_Implicit(val), (DataFormat)0, (SerializationContext)null);
			}
			object obj2 = value;
			NetworkObject val2 = (NetworkObject)((obj2 is NetworkObject) ? obj2 : null);
			if (val2 != null)
			{
				return SerializationUtility.SerializeValue<NetworkObjectReference>(NetworkObjectReference.op_Implicit(val2), (DataFormat)0, (SerializationContext)null);
			}
			object obj3 = value;
			NetworkBehaviour val3 = (NetworkBehaviour)((obj3 is NetworkBehaviour) ? obj3 : null);
			if (val3 != null)
			{
				return SerializationUtility.SerializeValue<NetworkBehaviourReference>(NetworkBehaviourReference.op_Implicit(val3), (DataFormat)0, (SerializationContext)null);
			}
			return SerializationUtility.SerializeValue<T>(value, (DataFormat)0, (SerializationContext)null);
		}

		internal static T Deserialize<T>(byte[] data)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			if (data.Length == 0)
			{
				return default(T);
			}
			T val = default(T);
			if (!(val is GameObject))
			{
				if (!(val is NetworkObject))
				{
					if (val is NetworkBehaviour)
					{
						return (T)(object)NetworkBehaviourReference.op_Implicit(SerializationUtility.DeserializeValue<NetworkBehaviourReference>(data, (DataFormat)0, (DeserializationContext)null));
					}
					return SerializationUtility.DeserializeValue<T>(data, (DataFormat)0, (DeserializationContext)null);
				}
				return (T)(object)NetworkObjectReference.op_Implicit(SerializationUtility.DeserializeValue<NetworkObjectReference>(data, (DataFormat)0, (DeserializationContext)null));
			}
			return (T)(object)NetworkObjectReference.op_Implicit(SerializationUtility.DeserializeValue<NetworkObjectReference>(data, (DataFormat)0, (DeserializationContext)null));
		}
	}
	public class NetworkBehaviourReferenceFormatter : MinimalBaseFormatter<NetworkBehaviourReference>
	{
		private static readonly Serializer<ushort> UInt16Serializer = Serializer.Get<ushort>();

		private static readonly Serializer<NetworkObjectReference> NetworkObjectReferenceSerializer = Serializer.Get<NetworkObjectReference>();

		protected override void Read(ref NetworkBehaviourReference value, IDataReader reader)
		{
			//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)
			value.m_NetworkObjectReference = NetworkObjectReferenceSerializer.ReadValue(reader);
			value.m_NetworkBehaviourId = UInt16Serializer.ReadValue(reader);
		}

		protected override void Write(ref NetworkBehaviourReference value, IDataWriter writer)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			NetworkObjectReferenceSerializer.WriteValue(value.m_NetworkObjectReference, writer);
			UInt16Serializer.WriteValue(value.m_NetworkBehaviourId, writer);
		}
	}
	internal class NetworkObjectReferenceFormatter : MinimalBaseFormatter<NetworkObjectReference>
	{
		private static readonly Serializer<ulong> UInt64Serializer = Serializer.Get<ulong>();

		protected override void Read(ref NetworkObjectReference value, IDataReader reader)
		{
			((NetworkObjectReference)(ref value)).NetworkObjectId = UInt64Serializer.ReadValue(reader);
		}

		protected override void Write(ref NetworkObjectReference value, IDataWriter writer)
		{
			UInt64Serializer.WriteValue(((NetworkObjectReference)(ref value)).NetworkObjectId, writer);
		}
	}
}
namespace LethalNetworkAPI.Networking
{
	internal class NetworkHandler : NetworkBehaviour
	{
		internal readonly List<ILethalNetVar> ObjectNetworkVariableList = new List<ILethalNetVar>();

		internal static NetworkHandler? Instance { get; private set; }

		internal static event Action? NetworkSpawn;

		internal static event Action? NetworkDespawn;

		internal static event Action? NetworkTick;

		internal static event Action<ulong>? OnPlayerJoin;

		internal static event Action<string, byte[], ulong>? OnServerMessage;

		internal static event Action<string, byte[], ulong>? OnClientMessage;

		internal static event Action<string, byte[]>? OnVariableUpdate;

		internal static event Action<string, ulong>? GetVariableValue;

		internal static event Action<string, ulong>? OnServerEvent;

		internal static event Action<string, ulong>? OnClientEvent;

		internal static event Action<string, double, ulong>? OnSyncedServerEvent;

		internal static event Action<string, double, ulong>? OnSyncedClientEvent;

		public override void OnNetworkSpawn()
		{
			if ((Object)(object)Instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			Instance = this;
			NetworkHandler.NetworkSpawn?.Invoke();
			((NetworkBehaviour)this).NetworkManager.NetworkTickSystem.Tick += NetworkHandler.NetworkTick;
			NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnectedCallback;
		}

		internal void Clean()
		{
			NetworkHandler.NetworkDespawn?.Invoke();
			NetworkHandler.OnPlayerJoin = null;
			NetworkHandler.NetworkDespawn = null;
			Instance = null;
		}

		private void OnClientConnectedCallback(ulong client)
		{
			NetworkHandler.OnPlayerJoin?.Invoke(client);
		}

		[ServerRpc(RequireOwnership = false)]
		internal void MessageServerRpc(string identifier, byte[] data, bool toOtherClients = false, bool sendToOriginator = false, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: 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_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: 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_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: 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_021f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3629803754u, serverRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				bool flag2 = data != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(data, default(ForPrimitives));
				}
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref toOtherClients, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref sendToOriginator, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 3629803754u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			ServerRpcParams serverRpcParams2 = serverRpcParams;
			if (!toOtherClients)
			{
				NetworkHandler.OnServerMessage?.Invoke(identifier, data, serverRpcParams2.Receive.SenderClientId);
			}
			else if (!sendToOriginator)
			{
				NativeArray<ulong> val2 = default(NativeArray<ulong>);
				val2..ctor(NetworkManager.Singleton.ConnectedClientsIds.Where((ulong i) => i != serverRpcParams2.Receive.SenderClientId).ToArray(), (Allocator)4);
				if (((IEnumerable<ulong>)(object)val2).Any())
				{
					MessageClientRpc(identifier, data, serverRpcParams2.Receive.SenderClientId, new ClientRpcParams
					{
						Send = new ClientRpcSendParams
						{
							TargetClientIdsNativeArray = val2
						}
					});
				}
			}
			else
			{
				MessageClientRpc(identifier, data, serverRpcParams2.Receive.SenderClientId);
			}
		}

		[ClientRpc]
		internal void MessageClientRpc(string identifier, byte[] data, ulong originatorClient = 99999uL, ClientRpcParams clientRpcParams = default(ClientRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: 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))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(3740138170u, clientRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				bool flag2 = data != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(data, default(ForPrimitives));
				}
				BytePacker.WriteValueBitPacked(val, originatorClient);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 3740138170u, clientRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkHandler.OnClientMessage?.Invoke(identifier, data, originatorClient);
				clientRpcParams.Send.TargetClientIdsNativeArray?.Dispose();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void EventServerRpc(string identifier, bool toOtherClients = false, bool sendToOriginator = false, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0136: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: 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_018c: 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)
			//IL_01b8: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1959733556u, serverRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref toOtherClients, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref sendToOriginator, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 1959733556u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			ServerRpcParams serverRpcParams2 = serverRpcParams;
			if (!toOtherClients)
			{
				NetworkHandler.OnServerEvent?.Invoke(identifier, serverRpcParams2.Receive.SenderClientId);
			}
			else if (!sendToOriginator)
			{
				NativeArray<ulong> val2 = default(NativeArray<ulong>);
				val2..ctor(NetworkManager.Singleton.ConnectedClientsIds.Where((ulong i) => i != serverRpcParams2.Receive.SenderClientId).ToArray(), (Allocator)4);
				if (((IEnumerable<ulong>)(object)val2).Any())
				{
					EventClientRpc(identifier, serverRpcParams2.Receive.SenderClientId, new ClientRpcParams
					{
						Send = new ClientRpcSendParams
						{
							TargetClientIdsNativeArray = val2
						}
					});
				}
			}
			else
			{
				EventClientRpc(identifier, serverRpcParams2.Receive.SenderClientId);
			}
		}

		[ClientRpc]
		internal void EventClientRpc(string identifier, ulong originatorClient = 99999uL, ClientRpcParams clientRpcParams = default(ClientRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_00af: 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_012e: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(53735464u, clientRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				BytePacker.WriteValueBitPacked(val, originatorClient);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 53735464u, clientRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkHandler.OnClientEvent?.Invoke(identifier, originatorClient);
				clientRpcParams.Send.TargetClientIdsNativeArray?.Dispose();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void SyncedEventServerRpc(string identifier, double time, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2669215490u, serverRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				((FastBufferWriter)(ref val)).WriteValueSafe<double>(ref time, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 2669215490u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				NetworkHandler.OnSyncedServerEvent?.Invoke(identifier, time, serverRpcParams.Receive.SenderClientId);
			}
		}

		[ClientRpc]
		internal void SyncedEventClientRpc(string identifier, double time, ulong originatorClient, ClientRpcParams clientRpcParams = default(ClientRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(899832842u, clientRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				((FastBufferWriter)(ref val)).WriteValueSafe<double>(ref time, default(ForPrimitives));
				BytePacker.WriteValueBitPacked(val, originatorClient);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 899832842u, clientRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkHandler.OnSyncedClientEvent?.Invoke(identifier, time, originatorClient);
				clientRpcParams.Send.TargetClientIdsNativeArray?.Dispose();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void UpdateVariableServerRpc(string identifier, byte[] data, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_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_014b: 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_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_019d: 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)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1359429614u, serverRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				bool flag2 = data != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(data, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 1359429614u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ServerRpcParams serverRpcParams2 = serverRpcParams;
				if (serverRpcParams2.Receive.SenderClientId != 0L)
				{
					NetworkHandler.OnVariableUpdate?.Invoke(identifier, data);
				}
				NativeArray<ulong> val2 = default(NativeArray<ulong>);
				val2..ctor(NetworkManager.Singleton.ConnectedClientsIds.Where((ulong i) => i != serverRpcParams2.Receive.SenderClientId).ToArray(), (Allocator)4);
				if (((IEnumerable<ulong>)(object)val2).Any())
				{
					UpdateVariableClientRpc(identifier, data, new ClientRpcParams
					{
						Send = new ClientRpcSendParams
						{
							TargetClientIdsNativeArray = val2
						}
					});
				}
			}
		}

		[ClientRpc]
		internal void UpdateVariableClientRpc(string identifier, byte[] data, ClientRpcParams clientRpcParams = default(ClientRpcParams))
		{
			//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)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: 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))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1641402893u, clientRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				bool flag2 = data != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(data, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 1641402893u, clientRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkHandler.OnVariableUpdate?.Invoke(identifier, data);
				clientRpcParams.Send.TargetClientIdsNativeArray?.Dispose();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void GetVariableValueServerRpc(string identifier, ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_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)
			//IL_0104: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2442151635u, serverRpcParams, (RpcDelivery)0);
				bool flag = identifier != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(identifier, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 2442151635u, serverRpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				NetworkHandler.GetVariableValue?.Invoke(identifier, serverRpcParams.Receive.SenderClientId);
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkHandler()
		{
			//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
			NetworkManager.__rpc_func_table.Add(3629803754u, new RpcReceiveHandler(__rpc_handler_3629803754));
			NetworkManager.__rpc_func_table.Add(3740138170u, new RpcReceiveHandler(__rpc_handler_3740138170));
			NetworkManager.__rpc_func_table.Add(1959733556u, new RpcReceiveHandler(__rpc_handler_1959733556));
			NetworkManager.__rpc_func_table.Add(53735464u, new RpcReceiveHandler(__rpc_handler_53735464));
			NetworkManager.__rpc_func_table.Add(2669215490u, new RpcReceiveHandler(__rpc_handler_2669215490));
			NetworkManager.__rpc_func_table.Add(899832842u, new RpcReceiveHandler(__rpc_handler_899832842));
			NetworkManager.__rpc_func_table.Add(1359429614u, new RpcReceiveHandler(__rpc_handler_1359429614));
			NetworkManager.__rpc_func_table.Add(1641402893u, new RpcReceiveHandler(__rpc_handler_1641402893));
			NetworkManager.__rpc_func_table.Add(2442151635u, new RpcReceiveHandler(__rpc_handler_2442151635));
		}

		private static void __rpc_handler_3629803754(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_0067: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] data = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref data, default(ForPrimitives));
				}
				bool toOtherClients = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref toOtherClients, default(ForPrimitives));
				bool sendToOriginator = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sendToOriginator, default(ForPrimitives));
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).MessageServerRpc(identifier, data, toOtherClients, sendToOriginator, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3740138170(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_0067: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00bd: 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)
			//IL_00e3: 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_0096: 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 identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] data = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref data, default(ForPrimitives));
				}
				ulong originatorClient = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref originatorClient);
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).MessageClientRpc(identifier, data, originatorClient, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1959733556(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_0067: 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_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)
			//IL_0091: 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)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				bool toOtherClients = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref toOtherClients, default(ForPrimitives));
				bool sendToOriginator = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sendToOriginator, default(ForPrimitives));
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).EventServerRpc(identifier, toOtherClients, sendToOriginator, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_53735464(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_005b: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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 identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				ulong originatorClient = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref originatorClient);
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).EventClientRpc(identifier, originatorClient, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2669215490(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_0067: 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_0076: 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)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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 identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				double time = default(double);
				((FastBufferReader)(ref reader)).ReadValueSafe<double>(ref time, default(ForPrimitives));
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SyncedEventServerRpc(identifier, time, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_899832842(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_0067: 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_0076: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: 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 identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				double time = default(double);
				((FastBufferReader)(ref reader)).ReadValueSafe<double>(ref time, default(ForPrimitives));
				ulong originatorClient = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref originatorClient);
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).SyncedEventClientRpc(identifier, time, originatorClient, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1359429614(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_0067: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] data = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref data, default(ForPrimitives));
				}
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).UpdateVariableServerRpc(identifier, data, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1641402893(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_0067: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] data = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref data, default(ForPrimitives));
				}
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).UpdateVariableClientRpc(identifier, data, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2442151635(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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_007a: 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 = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string identifier = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref identifier, false);
				}
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).GetVariableValueServerRpc(identifier, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string? __getTypeName()
		{
			return "NetworkHandler";
		}
	}
	[HarmonyPatch]
	[HarmonyPriority(800)]
	[HarmonyWrapSafe]
	internal class NetworkObjectManager
	{
		private static GameObject _networkPrefab;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		private static void Init()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			if (!((Object)(object)_networkPrefab != (Object)null))
			{
				GameObject val = new GameObject("NetworkAPIContainer")
				{
					hideFlags = (HideFlags)61
				};
				val.SetActive(false);
				_networkPrefab = MakePrefab<NetworkHandler>("LethalNetworkAPI.Handler", val, 889887688u);
			}
		}

		private static GameObject MakePrefab<T>(string name, GameObject parent, uint overrideGuid = 0u) where T : NetworkBehaviour
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent.transform);
			val.AddComponent<NetworkObject>();
			val.AddComponent<T>();
			((Object)val).hideFlags = (HideFlags)61;
			if (overrideGuid != 0)
			{
				val.GetComponent<NetworkObject>().GlobalObjectIdHash = overrideGuid;
			}
			else
			{
				uint globalObjectIdHash = BitConverter.ToUInt32(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetExecutingAssembly().GetName().Name + name)), 0);
				val.GetComponent<NetworkObject>().GlobalObjectIdHash = globalObjectIdHash;
			}
			NetworkManager.Singleton.AddNetworkPrefab(val);
			return val;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		private static void SpawnNetworkHandler()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				GameObject val = Object.Instantiate<GameObject>(_networkPrefab, Vector3.zero, Quaternion.identity, ((Component)StartOfRound.Instance).transform);
				val.GetComponent<NetworkObject>().Spawn(false);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		private static void OnDisconnect()
		{
			NetworkHandler.Instance.Clean();
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int IReadOnlyCollection<T>.Count => _items.Length;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Length;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyArray(T[] items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return ((ICollection<T>)_items).Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		((ICollection<T>)_items).CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return ((IList<T>)_items).IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
namespace LethalNetworkAPI.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

plugins/LethalVocabulary.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Speech.Recognition;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalVocabulary.NetcodePatcher;
using Microsoft.CodeAnalysis;
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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalVocabulary")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A mod for Lethal Company that makes your vocabulary a little more... lethal.")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2")]
[assembly: AssemblyProduct("LethalVocabulary")]
[assembly: AssemblyTitle("LethalVocabulary")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalVocabulary
{
	public class Config
	{
		private static readonly string CustomWordTip = "Words must be separated by a comma (,). Capitalization does not matter. Words in ALL CAPS will not trigger a penalty unless EnableExtendedWords is enabled.";

		public static ConfigEntry<bool> EnableExtendedWords;

		public static ConfigEntry<int> CategoriesPerMoon;

		public static ConfigEntry<string> SnareFleaWords;

		public static ConfigEntry<string> BunkerSpiderWords;

		public static ConfigEntry<string> HoardingBugWords;

		public static ConfigEntry<string> BrackenWords;

		public static ConfigEntry<string> ThumperWords;

		public static ConfigEntry<string> HygrodereWords;

		public static ConfigEntry<string> GhostGirlWords;

		public static ConfigEntry<string> SporeLizardWords;

		public static ConfigEntry<string> NutcrackerWords;

		public static ConfigEntry<string> CoilHeadWords;

		public static ConfigEntry<string> JesterWords;

		public static ConfigEntry<string> MaskedWords;

		public static ConfigEntry<string> EyelessDogWords;

		public static ConfigEntry<string> ForestKeeperWords;

		public static ConfigEntry<string> EarthLeviathanWords;

		public static ConfigEntry<string> BaboonHawkWords;

		public Config(ConfigFile cfg)
		{
			EnableExtendedWords = cfg.Bind<bool>("Gameplay", "EnableExtendedWords", false, "Words in ALL CAPS are considered \"extended words\" and will not be included unless this setting is true");
			CategoriesPerMoon = cfg.Bind<int>("Gameplay", "CategoriesPerMoon", 1, "The number of categories that will be banned per moon.");
			SnareFleaWords = cfg.Bind<string>("Categories.Entities", "Snare Flea", "snare,flea,fleas,centipede,centipedes,FACE,HUGGER,HUGGERS,HEAD,CRAB,CRABS", CategoryDescriptionFor("Snare Flea"));
			BunkerSpiderWords = cfg.Bind<string>("Categories.Entities", "Bunker Spider", "bunker,spider,spiders,web,webs,ARACHNID,ARACHNIDS", CategoryDescriptionFor("Bunker Spider"));
			HoardingBugWords = cfg.Bind<string>("Categories.Entities", "Hoarding Bug", "hoard,hoarding,bug,bugs,loot", CategoryDescriptionFor("Hoarding Bug"));
			BrackenWords = cfg.Bind<string>("Categories.Entities", "Bracken", "bracken,flower", CategoryDescriptionFor("Bracken"));
			ThumperWords = cfg.Bind<string>("Categories.Entities", "Thumper", "thumper,thumpers,crawler,crawlers", CategoryDescriptionFor("Thumper"));
			HygrodereWords = cfg.Bind<string>("Categories.Entities", "Hygrodere (Slime)", "hygrodere,hygroderes,slime,slimes", CategoryDescriptionFor("Hygrodere (Slime)"));
			GhostGirlWords = cfg.Bind<string>("Categories.Entities", "Ghost Girl", "ghost,ghosts,girl,girls,haunt,haunted", CategoryDescriptionFor("Ghost Girl"));
			SporeLizardWords = cfg.Bind<string>("Categories.Entities", "Spore Lizard", "spore,spores,lizard,lizards", CategoryDescriptionFor("Spore Lizard"));
			NutcrackerWords = cfg.Bind<string>("Categories.Entities", "Nutcracker", "nut,nuts,cracker,crackers,shotgun,gun,soldier", CategoryDescriptionFor("Nutcracker"));
			CoilHeadWords = cfg.Bind<string>("Categories.Entities", "Coil Head", "coil,coils,head,heads", CategoryDescriptionFor("Coil Head"));
			JesterWords = cfg.Bind<string>("Categories.Entities", "Jester", "jester,winding", CategoryDescriptionFor("Jester"));
			MaskedWords = cfg.Bind<string>("Categories.Entities", "Masked", "mask,masked,mimic,mimics", CategoryDescriptionFor("Masked"));
			EyelessDogWords = cfg.Bind<string>("Categories.Entities", "Eyeless Dog", "eye,eyes,eyeless,dog,dogs", CategoryDescriptionFor("Eyeless Dog"));
			ForestKeeperWords = cfg.Bind<string>("Categories.Entities", "Forest Keeper (Giant)", "forest,keeper,keepers,giant,giants", CategoryDescriptionFor("Forest Keeper (Giant)"));
			EarthLeviathanWords = cfg.Bind<string>("Categories.Entities", "Earth Leviathan (Worm)", "earth,leviathan,leviathans,worm,worms", CategoryDescriptionFor("Earth Leviathan (Worm)"));
			BaboonHawkWords = cfg.Bind<string>("Categories.Entities", "Baboon Hawk", "baboon,baboons,hawk,hawks", CategoryDescriptionFor("Baboon Hawk"));
		}

		private static string CategoryDescriptionFor(string category)
		{
			return "Words that count as mentioning the " + category + "\n" + CustomWordTip;
		}
	}
	public class PenaltyManager : NetworkBehaviour
	{
		public static PenaltyManager Instance;

		private void Awake()
		{
			Instance = this;
		}

		[ServerRpc(RequireOwnership = false)]
		public void PunishPlayerServerRpc(ulong clientId)
		{
			//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2979100391u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, clientId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2979100391u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					PunishPlayerClientRpc(clientId);
				}
			}
		}

		[ClientRpc]
		public void PunishPlayerClientRpc(ulong clientId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: 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(2420793007u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, clientId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2420793007u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((Object)(object)StartOfRound.Instance == (Object)null))
				{
					GameObject val3 = StartOfRound.Instance.allPlayerObjects[clientId];
					Landmine.SpawnExplosion(val3.transform.position, true, 1f, 0f);
				}
			}
		}

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

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

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

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

		protected internal override string __getTypeName()
		{
			return "PenaltyManager";
		}
	}
	[BepInPlugin("LethalVocabulary", "LethalVocabulary", "0.1.2")]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin Instance;

		private static Harmony _harmony;

		public static ManualLogSource logger;

		public GameObject penaltyManagerPrefab;

		public bool roundInProgress;

		public readonly HashSet<string> ClientBannedCategories = new HashSet<string>();

		public readonly HashSet<string> ClientBannedWords = new HashSet<string>();

		public Dictionary<string, HashSet<string>> ClientCategories = new Dictionary<string, HashSet<string>>();

		private SpeechRecognizer _speechRecognizer;

		public static Config Config { get; internal set; }

		private void Awake()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			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);
					}
				}
			}
			Instance = this;
			_harmony = new Harmony("LethalVocabulary");
			logger = ((BaseUnityPlugin)this).Logger;
			Config = new Config(((BaseUnityPlugin)this).Config);
			_speechRecognizer = new SpeechRecognizer();
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lethalvocabularybundle");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			penaltyManagerPrefab = val.LoadAsset<GameObject>("Assets/LethalVocabulary/PenaltyManager.prefab");
			penaltyManagerPrefab.AddComponent<PenaltyManager>();
			ClientCategories = GetCategoriesFromConfig(Config.EnableExtendedWords.Value);
			_speechRecognizer.AddSpeechRecognizedHandler(delegate(object _, SpeechRecognizedEventArgs e)
			{
				string text2 = ((RecognizedPhrase)((RecognitionEventArgs)e).Result).Text;
				float confidence = ((RecognizedPhrase)((RecognitionEventArgs)e).Result).Confidence;
				if (roundInProgress && !(confidence < 0.85f) && !((Object)(object)RoundManager.Instance == (Object)null))
				{
					PlayerControllerB localPlayerController = RoundManager.Instance.playersManager.localPlayerController;
					if (!((Object)(object)localPlayerController == (Object)null) && !localPlayerController.isPlayerDead && StringHasWords(text2, ClientBannedWords))
					{
						PenaltyManager.Instance.PunishPlayerServerRpc(((NetworkBehaviour)localPlayerController).NetworkManager.LocalClientId);
					}
				}
			});
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalVocabulary is loaded!");
		}

		public void StartRound()
		{
			if (roundInProgress)
			{
				return;
			}
			ClientBannedCategories.UnionWith(PickRandomCategories(Math.Max(1, Config.CategoriesPerMoon.Value)));
			foreach (string clientBannedCategory in ClientBannedCategories)
			{
				ClientBannedWords.UnionWith(ClientCategories[clientBannedCategory]);
			}
			DisplayHUDTip("Don't talk about...", string.Join(", ", ClientBannedCategories), warning: false);
			((BaseUnityPlugin)this).Logger.LogError((object)string.Join(", ", ClientBannedWords));
			roundInProgress = true;
		}

		public void EndRound()
		{
			roundInProgress = false;
			ClientBannedCategories.Clear();
			ClientBannedWords.Clear();
		}

		public string[] PickRandomCategories(int amount)
		{
			List<string> list = ClientCategories.Keys.ToList();
			List<string> list2 = new List<string>();
			for (int i = 0; i < Math.Min(amount, list.Count); i++)
			{
				int index = Random.RandomRangeInt(0, list.Count);
				list2.Add(list[index]);
				list.RemoveAt(index);
			}
			return list2.ToArray();
		}

		public static string[] GetAllWordsFromConfig(bool getExtendedWords)
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (KeyValuePair<string, HashSet<string>> item in GetCategoriesFromConfig(getExtendedWords))
			{
				hashSet.UnionWith(item.Value);
			}
			return hashSet.ToArray();
		}

		public static Dictionary<string, HashSet<string>> GetCategoriesFromConfig(bool getExtendedWords)
		{
			Dictionary<string, HashSet<string>> dictionary = new Dictionary<string, HashSet<string>>();
			dictionary.Add("Snare Flea", ProcessCategoryWords(Config.SnareFleaWords.Value, getExtendedWords));
			dictionary.Add("Bunker Spider", ProcessCategoryWords(Config.BunkerSpiderWords.Value, getExtendedWords));
			dictionary.Add("Hoarding Bug", ProcessCategoryWords(Config.HoardingBugWords.Value, getExtendedWords));
			dictionary.Add("Bracken", ProcessCategoryWords(Config.BrackenWords.Value, getExtendedWords));
			dictionary.Add("Thumper", ProcessCategoryWords(Config.ThumperWords.Value, getExtendedWords));
			dictionary.Add("Hygrodere (Slime)", ProcessCategoryWords(Config.HygrodereWords.Value, getExtendedWords));
			dictionary.Add("Ghost Girl", ProcessCategoryWords(Config.GhostGirlWords.Value, getExtendedWords));
			dictionary.Add("Spore Lizard", ProcessCategoryWords(Config.SporeLizardWords.Value, getExtendedWords));
			dictionary.Add("Nutcracker", ProcessCategoryWords(Config.NutcrackerWords.Value, getExtendedWords));
			dictionary.Add("Coil Head", ProcessCategoryWords(Config.CoilHeadWords.Value, getExtendedWords));
			dictionary.Add("Jester", ProcessCategoryWords(Config.JesterWords.Value, getExtendedWords));
			dictionary.Add("Masked", ProcessCategoryWords(Config.MaskedWords.Value, getExtendedWords));
			dictionary.Add("Eyeless Dog", ProcessCategoryWords(Config.EyelessDogWords.Value, getExtendedWords));
			dictionary.Add("Forest Keeper", ProcessCategoryWords(Config.ForestKeeperWords.Value, getExtendedWords));
			dictionary.Add("Earth Leviathan (Worm)", ProcessCategoryWords(Config.EarthLeviathanWords.Value, getExtendedWords));
			dictionary.Add("Baboon Hawk", ProcessCategoryWords(Config.BaboonHawkWords.Value, getExtendedWords));
			return dictionary;
		}

		private static HashSet<string> ProcessCategoryWords(string categoryWords, bool includeExtendedWords)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] array = categoryWords.Split(",");
			foreach (string text in array)
			{
				if (!StringIsAllUpper(text) || includeExtendedWords)
				{
					hashSet.Add(text.ToLower());
				}
			}
			return hashSet;
		}

		public static bool StringHasWords(string @string, HashSet<string> words)
		{
			return words.Any((string word) => @string.Contains(word));
		}

		public static void DisplayHUDTip(string title, string body, bool warning)
		{
			if ((Object)(object)HUDManager.Instance == (Object)null)
			{
				logger.LogInfo((object)"Failed to display tip, no active HUDManager");
			}
			else
			{
				HUDManager.Instance.DisplayTip(title, body, warning, false, "LC_Tip1");
			}
		}

		private static bool StringIsAllUpper(string word)
		{
			return word.All((char c) => !char.IsLetter(c) || char.IsUpper(c));
		}
	}
	public class SpeechRecognizer
	{
		private static readonly Grammar CommonWords = new Grammar(new GrammarBuilder(new Choices(new string[55]
		{
			"cog", "heck", "some", "something", "ok", "way", "main", "fire", "exit", "hello",
			"lyrics", "uh", "oh", "hi", "sing", "sky", "forever", "for", "see", "fly",
			"word", "what", "hey", "hm", "mine", "turret", "door", "lock", "locked", "explode",
			"exploded", "dead", "end", "pipe", "steam", "smoke", "scrap", "flash", "stun", "light",
			"shovel", "stop", "sign", "yield", "boom", "boombox", "box", "ladder", "emergency", "pro",
			"tzp", "inhale", "use", "drop", "miss"
		})));

		private readonly SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();

		public SpeechRecognizer()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			_recognizer.SetInputToDefaultAudioDevice();
			_recognizer.LoadGrammar(CommonWords);
			_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(Plugin.GetAllWordsFromConfig(getExtendedWords: true)))));
			_recognizer.RecognizeAsync((RecognizeMode)1);
		}

		public void AddSpeechRecognizedHandler(EventHandler<SpeechRecognizedEventArgs> eventHandler)
		{
			_recognizer.SpeechRecognized += eventHandler;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalVocabulary";

		public const string PLUGIN_NAME = "LethalVocabulary";

		public const string PLUGIN_VERSION = "0.1.2";
	}
}
namespace LethalVocabulary.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class GameNetworkManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void AddPenaltyManager(ref GameNetworkManager __instance)
		{
			((Component)__instance).GetComponent<NetworkManager>().AddNetworkPrefab(Plugin.Instance.penaltyManagerPrefab);
		}

		[HarmonyPostfix]
		[HarmonyPatch("StartDisconnect")]
		private static void PerformDisconnectOperations(ref GameNetworkManager __instance)
		{
			Plugin.Instance.EndRound();
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	public class HUDManagerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("SubmitChat_performed")]
		private static void CheckSubmittedChat(ref HUDManager __instance)
		{
			string @string = __instance.chatTextField.text.ToLower();
			if (Plugin.Instance.roundInProgress && Plugin.StringHasWords(@string, Plugin.Instance.ClientBannedWords))
			{
				PenaltyManager.Instance.PunishPlayerServerRpc(((NetworkBehaviour)__instance).NetworkManager.LocalClientId);
				__instance.chatTextField.text = "";
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	public class RoundManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("FinishGeneratingNewLevelClientRpc")]
		private static void PickNewBannedCategories(ref RoundManager __instance)
		{
			Plugin.Instance.StartRound();
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public class StartOfRoundPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void SpawnPenaltyManagerPrefab(ref StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsHost)
			{
				GameObject val = Object.Instantiate<GameObject>(Plugin.Instance.penaltyManagerPrefab);
				val.GetComponent<NetworkObject>().Spawn(false);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("EndOfGameClientRpc")]
		private static void PerformEndOfGameOperations()
		{
			Plugin.Instance.EndRound();
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public class TerminalPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("ParsePlayerSentence")]
		private static void CheckSubmittedCommand(ref Terminal __instance)
		{
			string text = ((TMP_Text)__instance.inputFieldText).text.ToLower();
			if (Plugin.Instance.roundInProgress && Plugin.StringHasWords(text, Plugin.Instance.ClientBannedWords))
			{
				PenaltyManager.Instance.PunishPlayerServerRpc(((NetworkBehaviour)__instance).NetworkManager.LocalClientId);
				if (text.StartsWith("transmit"))
				{
					((TMP_Text)__instance.inputFieldText).text = "";
				}
			}
		}
	}
}
namespace LethalVocabulary.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

plugins/Peepers.dll

Decompiled 9 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using LCPeeper.Properties;
using Peepers.NetcodePatcher;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Peepers")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Adds a new non-lethal monster to the game with unique mechanics and interactions.")]
[assembly: AssemblyFileVersion("0.9.6.0")]
[assembly: AssemblyInformationalVersion("0.9.6")]
[assembly: AssemblyProduct("Peepers")]
[assembly: AssemblyTitle("Peepers")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.9.6.0")]
[module: UnverifiableCode]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace LCPeeper
{
	[BepInPlugin("x753.Peepers", "Peepers", "0.9.6")]
	public class Peeper : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class GameNetworkManagerPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch()
			{
				((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(PeeperPrefab);
			}
		}

		private const string modGUID = "x753.Peepers";

		private const string modName = "Peepers";

		private const string modVersion = "0.9.6";

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

		private static Peeper Instance;

		public static GameObject PeeperPrefab;

		public static EnemyType PeeperType;

		public static TerminalNode PeeperFile;

		public static int PeeperCreatureID = 0;

		public static List<PeeperAI> PeeperList = new List<PeeperAI>();

		public static List<string> ignoreEnemies = new List<string> { "Peeper", "Manticoil", "Docile Locust Bees", "Girl" };

		public static float PeeperSpawnChance;

		public static int PeeperMinGroupSize;

		public static int PeeperMaxGroupSize;

		public static float PeeperWeight;

		private void Awake()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.peeper);
			PeeperPrefab = val.LoadAsset<GameObject>("Assets/PeeperPrefab.prefab");
			PeeperType = val.LoadAsset<EnemyType>("Assets/PeeperType.asset");
			PeeperFile = val.LoadAsset<TerminalNode>("Assets/PeeperFile.asset");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Peepers is loaded!");
			PeeperSpawnChance = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Rate", "Hourly Spawn Chance (%)", 10f, "Chance of a group of peepers spawning each hour").Value;
			PeeperMinGroupSize = ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Minimum Peeper Group Size", 2, "The minimum number of peepers in a single group").Value;
			PeeperMaxGroupSize = ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Peeper Group Size", 4, "The maximum number of peepers in a single group").Value;
			PeeperWeight = ((BaseUnityPlugin)this).Config.Bind<float>("Peeper Settings", "Peeper Weight (lb)", 10f, "The weight of a single peeper in pounds.").Value / 105f;
			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(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch(Terminal __instance)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			Terminal val = Object.FindObjectOfType<Terminal>();
			if (!Object.op_Implicit((Object)(object)val.enemyFiles.Find((TerminalNode node) => node.creatureName == "Peepers")))
			{
				Peeper.PeeperCreatureID = val.enemyFiles.Count;
				Peeper.PeeperFile.creatureFileID = Peeper.PeeperCreatureID;
				val.enemyFiles.Add(Peeper.PeeperFile);
				TerminalKeyword val2 = val.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
				TerminalKeyword val3 = ScriptableObject.CreateInstance<TerminalKeyword>();
				val3.word = "peepers";
				val3.isVerb = false;
				val3.defaultVerb = val2;
				List<CompatibleNoun> list = val2.compatibleNouns.ToList();
				list.Add(new CompatibleNoun
				{
					noun = val3,
					result = Peeper.PeeperFile
				});
				val2.compatibleNouns = list.ToArray();
				List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
				list2.Add(val3);
				val.terminalNodes.allKeywords = list2.ToArray();
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		[HarmonyPatch("AdvanceHourAndSpawnNewBatchOfEnemies")]
		[HarmonyPrefix]
		private static void AdvanceHourAndSpawnNewBatchOfEnemiesPatch(RoundManager __instance)
		{
			//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)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			float num = Random.Range(0f, 100f);
			if (num > Peeper.PeeperSpawnChance)
			{
				return;
			}
			GameObject[] array = GameObject.FindGameObjectsWithTag("OutsideAINode");
			Vector3 position = array[__instance.AnomalyRandom.Next(0, array.Length)].transform.position;
			position = __instance.GetRandomNavMeshPositionInRadius(position, 4f, default(NavMeshHit));
			int num2 = 0;
			bool flag = false;
			for (int i = 0; i < array.Length - 1; i++)
			{
				for (int j = 0; j < __instance.spawnDenialPoints.Length; j++)
				{
					flag = true;
					if (Vector3.Distance(position, __instance.spawnDenialPoints[j].transform.position) < 8f)
					{
						num2 = (num2 + 1) % array.Length;
						position = array[num2].transform.position;
						position = __instance.GetRandomNavMeshPositionInRadius(position, 4f, default(NavMeshHit));
						flag = false;
						break;
					}
				}
				if (flag)
				{
					break;
				}
			}
			int num3 = Random.Range(Peeper.PeeperMinGroupSize, Peeper.PeeperMaxGroupSize);
			for (int k = 0; k <= num3; k++)
			{
				RoundManager.Instance.SpawnEnemyGameObject(position, 0f, -1, Peeper.PeeperType);
				EnemyType peeperType = Peeper.PeeperType;
				peeperType.numberSpawned++;
				RoundManager instance = RoundManager.Instance;
				instance.currentDaytimeEnemyPower++;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePatch(ref StartOfRound __instance)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			SelectableLevel[] levels = __instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity e) => (Object)(object)e.enemyType == (Object)(object)Peeper.PeeperType))
				{
					int rarity = 0;
					val.DaytimeEnemies.Add(new SpawnableEnemyWithRarity
					{
						enemyType = Peeper.PeeperType,
						rarity = rarity
					});
					break;
				}
			}
		}

		[HarmonyPatch("EndOfGame")]
		[HarmonyPrefix]
		private static void EndOfGamePatch(StartOfRound __instance, int bodiesInsured = 0, int connectedPlayersOnServer = 0, int scrapCollected = 0)
		{
			foreach (PeeperAI peeper in Peeper.PeeperList)
			{
				if (peeper.isAttached && (Object)(object)peeper.attachedPlayer != (Object)null && !peeper.attachedPlayer.isPlayerDead)
				{
					peeper.IsWeighted = false;
				}
			}
			Peeper.PeeperList = new List<PeeperAI>();
			PeeperAI.UsedAttachTargets = new List<Transform>();
		}
	}
	[HarmonyPatch(typeof(StunGrenadeItem))]
	internal class StunGrenadeItemPatch
	{
		[HarmonyPatch("StunExplosion")]
		[HarmonyPostfix]
		private static void StunExplosion(StunGrenadeItem __instance, Vector3 explosionPosition, bool affectAudio, float flashSeverityMultiplier, float enemyStunTime, float flashSeverityDistanceRolloff = 1f, bool isHeldItem = false, PlayerControllerB playerHeldBy = null, PlayerControllerB playerThrownBy = null, float addToFlashSeverity = 0f)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (!(Vector3.Distance(((Component)localPlayerController).transform.position, explosionPosition) < 16f) || (Vector3.Distance(((Component)localPlayerController).transform.position, explosionPosition) > 5f && (!isHeldItem || !((Object)(object)playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController)) && Physics.Linecast(explosionPosition + Vector3.up * 0.5f, ((Component)localPlayerController.gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)))
			{
				return;
			}
			List<PeeperAI> list = new List<PeeperAI>(Peeper.PeeperList);
			foreach (PeeperAI item in list)
			{
				if ((Object)(object)item.attachedPlayer == (Object)(object)localPlayerController && ((NetworkBehaviour)item).IsOwner)
				{
					((EnemyAI)item).KillEnemyOnOwnerClient(false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI))]
	internal class SpringManAIPatcher
	{
		[HarmonyPrefix]
		[HarmonyPatch("DoAIInterval")]
		private static void DoAllIntervalPrefix(ref SpringManAI __instance)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (PeeperAI.HasLineOfSightToPeeper(((Component)__instance).transform.position))
			{
				((EnemyAI)__instance).currentBehaviourStateIndex = 1;
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch("Update")]
		private static IEnumerable<CodeInstruction> Update_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			MethodInfo method = typeof(PeeperAI).GetMethod("HasLineOfSightToPeeper", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = typeof(SpringManAI).GetMethod("get_transform");
			MethodInfo method3 = typeof(Transform).GetMethod("get_position");
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 1; i < list.Count; i++)
			{
				if (!(list[i - 1].opcode != OpCodes.Ldc_I4_0) && !(list[i].opcode != OpCodes.Stloc_1))
				{
					list.Insert(i, new CodeInstruction(OpCodes.Or, (object)null));
					list.Insert(i, new CodeInstruction(OpCodes.Call, (object)method));
					list.Insert(i, new CodeInstruction(OpCodes.Callvirt, (object)method3));
					list.Insert(i, new CodeInstruction(OpCodes.Call, (object)method2));
					list.Insert(i, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					break;
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(SprayPaintItem))]
	internal class SprayPaintItemPatch
	{
		private static FieldInfo SprayMatIndex = typeof(SprayPaintItem).GetField("sprayCanMatsIndex", BindingFlags.Instance | BindingFlags.NonPublic);

		[HarmonyPatch("SprayPaintClientRpc")]
		[HarmonyPrefix]
		private static void SprayPaintClientRpcPatch(SprayPaintItem __instance, Vector3 sprayPos, Vector3 sprayRot)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Ray val = default(Ray);
				((Ray)(ref val))..ctor(sprayPos, sprayRot);
				RaycastHit val2 = default(RaycastHit);
				if (!Physics.Raycast(val, ref val2, 4f, 524288, (QueryTriggerInteraction)2) || !((Object)(object)((RaycastHit)(ref val2)).collider != (Object)null) || !(((Object)((RaycastHit)(ref val2)).collider).name == "PeeperSprayCollider"))
				{
					return;
				}
				PeeperAI component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform.parent.parent.parent.parent.parent.parent.parent).GetComponent<PeeperAI>();
				if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)component.attachedPlayer))
				{
					((Renderer)component.peeperMesh).materials[0].color = __instance.sprayCanMats[(int)SprayMatIndex.GetValue(__instance)].color;
					if (component.isAttached)
					{
						component.EjectFromPlayerServerRpc(component.attachedPlayer.actualClientId);
					}
				}
			}
			catch (Exception)
			{
			}
		}
	}
	[HarmonyPatch(typeof(FlashlightItem))]
	internal class FlashlightItemPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePatch(FlashlightItem __instance)
		{
			//IL_0031: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: 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)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)__instance).IsOwner || __instance.flashlightTypeID != 2 || !((GrabbableObject)__instance).isBeingUsed)
			{
				return;
			}
			Transform transform = ((Component)__instance.flashlightBulb).transform;
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(transform.position, transform.forward);
			RaycastHit[] array = Physics.RaycastAll(val, 32f, 1 << LayerMask.NameToLayer("ScanNode"));
			RaycastHit[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				RaycastHit val2 = array2[i];
				if (!(((Object)((RaycastHit)(ref val2)).collider).name == "PeeperScanNode"))
				{
					continue;
				}
				float num = Vector3.Angle(-((Ray)(ref val)).direction, ((RaycastHit)(ref val2)).transform.forward);
				if (num < 55f)
				{
					PeeperAI component = ((Component)((RaycastHit)(ref val2)).transform.parent.parent.parent.parent.parent.parent.parent).GetComponent<PeeperAI>();
					if ((Object)(object)component.attachedPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)
					{
						break;
					}
					if (((NetworkBehaviour)component).IsOwner)
					{
						((EnemyAI)component).KillEnemyOnOwnerClient(false);
					}
					else
					{
						component.KillEnemyNetworked();
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("KillPlayer")]
		[HarmonyPrefix]
		private static void KillPlayerPatch(PlayerControllerB __instance, Vector3 bodyVelocity, bool spawnBody = true, CauseOfDeath causeOfDeath = 0, int deathAnimation = 0)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			List<PeeperAI> list = new List<PeeperAI>(Peeper.PeeperList);
			foreach (PeeperAI item in list)
			{
				if ((Object)(object)item.attachedPlayer == (Object)(object)__instance && ((NetworkBehaviour)item).IsOwner)
				{
					if ((int)causeOfDeath == 11 || (int)causeOfDeath == 3)
					{
						((EnemyAI)item).KillEnemyOnOwnerClient(false);
					}
					else
					{
						item.EjectFromPlayerServerRpc(__instance.playerClientId);
					}
				}
			}
		}

		[HarmonyPatch("DamagePlayer")]
		[HarmonyPrefix]
		private static void DamagePlayerPatch(PlayerControllerB __instance, int damageNumber, bool hasDamageSFX = true, bool callRPC = true, CauseOfDeath causeOfDeath = 0, int deathAnimation = 0, bool fallDamage = false, Vector3 force = default(Vector3))
		{
			List<PeeperAI> list = new List<PeeperAI>(Peeper.PeeperList);
			foreach (PeeperAI item in list)
			{
				if ((Object)(object)item.attachedPlayer == (Object)(object)__instance)
				{
					item.EjectFromPlayerServerRpc(__instance.playerClientId);
				}
			}
		}

		[HarmonyPatch("IShockableWithGun.ShockWithGun")]
		[HarmonyPrefix]
		private static void DamagePlayerPatch(PlayerControllerB __instance, PlayerControllerB shockedByPlayer)
		{
			List<PeeperAI> list = new List<PeeperAI>(Peeper.PeeperList);
			foreach (PeeperAI item in list)
			{
				if ((Object)(object)item.attachedPlayer == (Object)(object)__instance && ((NetworkBehaviour)item).IsOwner)
				{
					((EnemyAI)item).KillEnemyOnOwnerClient(false);
				}
			}
		}

		[HarmonyPatch("DropAllHeldItems")]
		[HarmonyPostfix]
		private static void DamagePlayeDropAllHeldItemsPatch(PlayerControllerB __instance, bool itemsFall = true, bool disconnecting = false)
		{
			if (__instance.carryWeight != 1f)
			{
				return;
			}
			List<PeeperAI> list = new List<PeeperAI>(Peeper.PeeperList);
			foreach (PeeperAI item in list)
			{
				if ((Object)(object)item.attachedPlayer == (Object)(object)__instance && item.isAttached && !((EnemyAI)item).isEnemyDead)
				{
					__instance.carryWeight += Peeper.PeeperWeight;
				}
			}
		}
	}
	public class PeeperAI : EnemyAI
	{
		[Header("General")]
		public GameObject creatureModel;

		public SkinnedMeshRenderer peeperMesh;

		public ScanNodeProperties scanNode;

		[Header("AI and Pathfinding")]
		public AISearchRoutine searchForPlayers;

		public float maxSearchAndRoamRadius = 100f;

		public float searchPrecisionValue = 5f;

		private int sightRange = 30;

		[Header("Constraints and Transforms")]
		public Transform attachTargetTransform;

		public static List<Transform> UsedAttachTargets = new List<Transform>();

		public Vector3 attachTargetTranslationOffset;

		public Vector3 attachTargetRotationOffset;

		public Transform eyeTransform;

		public Transform eyeOriginalTransform;

		public bool isAttached;

		public PlayerControllerB attachedPlayer;

		[Header("Colliders and Physics")]
		public SphereCollider attachCollider;

		public SphereCollider physicsCollider;

		public SphereCollider hitboxCollider;

		public Rigidbody physicsRigidbody;

		[Header("State Handling and Sync")]
		public float stateTimer;

		public float stateTimer2;

		public int stateCounter;

		[Header("Audio")]
		public AudioSource AttachSFXSource;

		public AudioClip walkSFX;

		public AudioClip runSFX;

		public AudioClip[] spotSFX;

		public AudioClip[] jumpSFX;

		public AudioClip[] attachSFX;

		public AudioClip[] deathSFX;

		public AudioClip[] ejectSFX;

		public AudioClip[] zapSFX;

		public AudioClip[] whisperSFX;

		public static float NextWhisperTime;

		[Header("Materials")]
		public Material baseMat;

		public Material paintedMat;

		public Material deadMat;

		public ParticleSystem deathParticles;

		[Header("Ragdoll")]
		private bool ragdollFrozen;

		public Rigidbody[] ragdollRigidbodies;

		public Collider[] ragdollColliders;

		private Vector3 agentLocalVelocity;

		private Vector3 previousPosition;

		private float velX;

		private float velZ;

		private float velXZ;

		private float footstepTimer;

		private Vector3 deathDirection = Vector3.zero;

		private float blinkTimer;

		private float blinkInterval;

		private bool isWeightedInternal;

		public bool IsWeighted
		{
			get
			{
				return isWeightedInternal;
			}
			set
			{
				if (value && !isWeightedInternal)
				{
					PlayerControllerB obj = attachedPlayer;
					obj.carryWeight += Peeper.PeeperWeight;
				}
				else if (!value && isWeightedInternal)
				{
					PlayerControllerB obj2 = attachedPlayer;
					obj2.carryWeight += 0f - Peeper.PeeperWeight;
					if (attachedPlayer.carryWeight < 1f)
					{
						attachedPlayer.carryWeight = 1f;
					}
				}
				isWeightedInternal = value;
			}
		}

		public override void Start()
		{
			((EnemyAI)this).Start();
			searchForPlayers.searchWidth = maxSearchAndRoamRadius;
			searchForPlayers.searchPrecision = searchPrecisionValue;
			Peeper.PeeperList.Add(this);
			AudioMixer diageticMixer = SoundManager.Instance.diageticMixer;
			base.creatureVoice.outputAudioMixerGroup = diageticMixer.FindMatchingGroups("SFX")[0];
			base.creatureSFX.outputAudioMixerGroup = diageticMixer.FindMatchingGroups("SFX")[0];
			AttachSFXSource.outputAudioMixerGroup = diageticMixer.FindMatchingGroups("SFX")[0];
			scanNode.creatureScanID = Peeper.PeeperCreatureID;
			SwitchBehaviourState(2);
		}

		public override void DoAIInterval()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (base.inSpecialAnimation)
			{
				return;
			}
			((EnemyAI)this).DoAIInterval();
			if (StartOfRound.Instance.livingPlayers == 0 || base.isEnemyDead)
			{
				return;
			}
			if (base.currentBehaviourStateIndex != 0)
			{
				if (searchForPlayers.inProgress)
				{
					((EnemyAI)this).StopSearch(searchForPlayers, true);
					base.movingTowardsTargetPlayer = true;
				}
			}
			else if (!searchForPlayers.inProgress)
			{
				((EnemyAI)this).StartSearch(((Component)this).transform.position, searchForPlayers);
			}
		}

		public override void FinishedCurrentSearchRoutine()
		{
			((EnemyAI)this).FinishedCurrentSearchRoutine();
			searchForPlayers.searchWidth = Mathf.Clamp(searchForPlayers.searchWidth + 20f, 1f, maxSearchAndRoamRadius);
		}

		private void CalculateAnimationDirection()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			agentLocalVelocity = ((Component)this).transform.InverseTransformDirection(Vector3.ClampMagnitude(((Component)this).transform.position - previousPosition, 1f) / (Time.deltaTime * 2f));
			velX = Mathf.Lerp(velX, agentLocalVelocity.x, 5f * Time.deltaTime);
			velZ = Mathf.Lerp(velZ, 0f - agentLocalVelocity.z, 5f * Time.deltaTime);
			previousPosition = ((Component)this).transform.position;
			velXZ = Mathf.Sqrt(velX * velX + velZ * velZ);
			base.creatureAnimator.SetFloat("Speed", velXZ);
			float num = ((base.currentBehaviourStateIndex != 1 && base.currentBehaviourStateIndex != 5) ? 0.3335f : 0.3f);
			footstepTimer += Time.deltaTime;
			if (footstepTimer < num)
			{
				return;
			}
			footstepTimer = 0f;
			if ((double)velXZ > 0.15)
			{
				if (base.currentBehaviourStateIndex == 1)
				{
					PlayCreatureSFX(2);
				}
				else
				{
					PlayCreatureSFX(1);
				}
			}
		}

		private void PutCreatureOnGround()
		{
			//IL_0006: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (!(base.agent.velocity.y > 5f))
			{
				base.creatureAnimator.SetBool("Grounded", true);
				base.creatureAnimator.SetBool("Jump", false);
				Ray val = default(Ray);
				((Ray)(ref val))..ctor(((Component)this).transform.position + Vector3.up, Vector3.down);
				RaycastHit val2 = default(RaycastHit);
				if (Physics.Raycast(val, ref val2, 2f, LayerMask.GetMask(new string[2] { "Room", "Colliders" }), (QueryTriggerInteraction)1))
				{
					creatureModel.transform.localPosition = new Vector3(0f, 0f - ((RaycastHit)(ref val2)).distance + 1f, 0f);
				}
			}
		}

		public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			//IL_0027: 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_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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			((EnemyAI)this).HitEnemy(force, playerWhoHit, false);
			base.enemyHP -= force;
			if ((Object)(object)playerWhoHit != (Object)null)
			{
				Vector3 val = ((Component)this).transform.position - ((Component)playerWhoHit).transform.position;
				deathDirection = ((Vector3)(ref val)).normalized;
			}
			if (base.enemyHP <= 0 && ((NetworkBehaviour)this).IsOwner)
			{
				((EnemyAI)this).KillEnemyOnOwnerClient(false);
			}
		}

		public override void SetEnemyStunned(bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null)
		{
			base.enemyHP--;
			if (base.enemyHP <= 0 && ((NetworkBehaviour)this).IsOwner)
			{
				((EnemyAI)this).KillEnemyOnOwnerClient(false);
			}
		}

		public void KillEnemyNetworked()
		{
			if (((NetworkBehaviour)this).IsServer)
			{
				KillEnemyClientRpc();
			}
			else
			{
				KillEnemyServerRpc();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void KillEnemyServerRpc()
		{
			//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(1087886824u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1087886824u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					KillEnemyClientRpc();
				}
			}
		}

		[ClientRpc]
		public void KillEnemyClientRpc()
		{
			//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(2756874777u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2756874777u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((EnemyAI)this).KillEnemy(false);
				}
			}
		}

		public override void KillEnemy(bool destroy = false)
		{
			//IL_004e: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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)
			((EnemyAI)this).KillEnemy(false);
			base.creatureVoice.Stop();
			base.creatureSFX.Stop();
			PlayCreatureSFX(5);
			SwitchBehaviourState(7);
			base.isEnemyDead = true;
			Peeper.PeeperList.Remove(this);
			creatureModel.transform.localPosition = Vector3.zero;
			if (isAttached && (Object)(object)attachedPlayer != (Object)null)
			{
				EjectFromPlayer(attachedPlayer);
			}
			Color color = ((Renderer)peeperMesh).material.color;
			((Renderer)peeperMesh).materials = (Material[])(object)new Material[1] { deadMat };
			((Renderer)peeperMesh).materials[0].color = color;
			deathParticles.Play();
			((Behaviour)base.creatureAnimator).enabled = false;
			physicsRigidbody.isKinematic = true;
			Rigidbody[] array = ragdollRigidbodies;
			foreach (Rigidbody val in array)
			{
				val.isKinematic = false;
				if (deathDirection != Vector3.zero)
				{
					val.AddForce(15f * deathDirection, (ForceMode)1);
				}
			}
			Collider[] array2 = ragdollColliders;
			foreach (Collider val2 in array2)
			{
				val2.enabled = true;
			}
			peeperMesh.SetBlendShapeWeight(0, 0f);
			peeperMesh.SetBlendShapeWeight(1, 350f);
		}

		public void SwitchBehaviourState(int state)
		{
			SwitchBehaviourStateLocally(state);
			SwitchBehaviourStateServerRpc(state);
		}

		[ServerRpc(RequireOwnership = false)]
		public void SwitchBehaviourStateServerRpc(int state)
		{
			//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(316864934u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, state);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 316864934u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					SwitchBehaviourStateClientRpc(state);
				}
			}
		}

		[ClientRpc]
		public void SwitchBehaviourStateClientRpc(int state)
		{
			//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(4022924503u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, state);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4022924503u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					SwitchBehaviourStateLocally(state);
				}
			}
		}

		public void SwitchBehaviourStateLocally(int state)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: 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_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0604: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0731: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e4: Unknown result type (might be due to invalid IL or missing references)
			stateTimer = 0f;
			stateTimer2 = 0f;
			stateCounter = 0;
			switch (state)
			{
			case 0:
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				base.agent.speed = 2f;
				base.creatureAnimator.SetBool("Jump", false);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.inSpecialAnimation = false;
				((Behaviour)base.agent).enabled = true;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = new Vector3(0f, 0.5f, 0f);
				break;
			case 1:
				base.agent.speed = 6f;
				base.creatureAnimator.SetBool("Jump", false);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.inSpecialAnimation = false;
				((Behaviour)base.agent).enabled = true;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = new Vector3(0f, 0.5f, 0f);
				break;
			case 2:
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				base.agent.speed = 0f;
				base.creatureAnimator.SetBool("Jump", false);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.creatureAnimator.SetBool("Grounded", true);
				base.inSpecialAnimation = false;
				((Behaviour)base.agent).enabled = true;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = new Vector3(0f, 0.5f, 0f);
				break;
			case 3:
			{
				base.agent.speed = 0f;
				creatureModel.transform.localPosition = Vector3.zero;
				base.creatureAnimator.SetBool("Jump", true);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.creatureAnimator.SetBool("Grounded", false);
				base.inSpecialAnimation = true;
				((Behaviour)base.agent).enabled = false;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = true;
				physicsRigidbody.isKinematic = false;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 2f;
				hitboxCollider.center = Vector3.zero;
				SphereCollider obj3 = physicsCollider;
				((Collider)obj3).includeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj3).includeLayers) & -524289);
				SphereCollider obj4 = physicsCollider;
				((Collider)obj4).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj4).excludeLayers) | 0x80000);
				break;
			}
			case 4:
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				creatureModel.transform.localPosition = Vector3.zero;
				base.agent.speed = 0f;
				base.creatureAnimator.SetBool("Jump", true);
				base.creatureAnimator.SetBool("Attached", true);
				base.creatureAnimator.SetBool("Dead", false);
				base.creatureAnimator.SetBool("Grounded", false);
				base.inSpecialAnimation = true;
				((Behaviour)base.agent).enabled = false;
				base.enemyType.canBeStunned = false;
				((Collider)attachCollider).enabled = false;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = false;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = Vector3.zero;
				NextWhisperTime = Time.time + 10f;
				break;
			case 5:
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				base.agent.speed = 0f;
				base.creatureAnimator.SetBool("Jump", false);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.creatureAnimator.SetBool("Grounded", true);
				base.inSpecialAnimation = false;
				((Behaviour)base.agent).enabled = true;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = new Vector3(0f, 0.5f, 0f);
				break;
			case 6:
			{
				stateTimer = Random.Range(0f, 1f);
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				base.agent.speed = 0f;
				creatureModel.transform.localPosition = Vector3.zero;
				base.creatureAnimator.SetBool("Jump", true);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				base.creatureAnimator.SetBool("Grounded", false);
				base.inSpecialAnimation = true;
				((Behaviour)base.agent).enabled = false;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = false;
				((Collider)physicsCollider).enabled = true;
				physicsRigidbody.isKinematic = false;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = Vector3.zero;
				SphereCollider obj = physicsCollider;
				((Collider)obj).includeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj).includeLayers) | 0x80000);
				SphereCollider obj2 = physicsCollider;
				((Collider)obj2).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj2).excludeLayers) & -524289);
				break;
			}
			case 7:
				base.targetPlayer = null;
				base.movingTowardsTargetPlayer = false;
				base.agent.speed = 0f;
				creatureModel.transform.localPosition = Vector3.zero;
				base.creatureAnimator.SetBool("Jump", false);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", true);
				base.creatureAnimator.SetBool("Grounded", false);
				base.inSpecialAnimation = true;
				((Behaviour)base.agent).enabled = false;
				base.enemyType.canBeStunned = false;
				((Collider)attachCollider).enabled = false;
				((Collider)physicsCollider).enabled = false;
				physicsRigidbody.isKinematic = true;
				((Collider)hitboxCollider).enabled = false;
				hitboxCollider.radius = 0.5f;
				hitboxCollider.center = Vector3.zero;
				break;
			}
			((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(state);
		}

		private void LateUpdate()
		{
			//IL_0020: 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_0047: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: 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_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: 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_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: 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_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_027e: Unknown result type (might be due to invalid IL or missing references)
			if (base.isEnemyDead)
			{
				return;
			}
			if (isAttached)
			{
				((Component)this).transform.position = attachTargetTransform.position;
				((Component)this).transform.rotation = attachTargetTransform.rotation;
				((Component)this).transform.Rotate(attachTargetRotationOffset);
				((Component)this).transform.Translate(0f, 0f, attachTargetTranslationOffset.z, (Space)1);
				((Component)this).transform.Translate(0f, attachTargetTranslationOffset.y, 0f, attachTargetTransform);
			}
			int currentBehaviourStateIndex = base.currentBehaviourStateIndex;
			if (currentBehaviourStateIndex == 4)
			{
				blinkTimer += Time.deltaTime;
				if (blinkTimer > blinkInterval)
				{
					base.creatureAnimator.SetTrigger("Blink");
					blinkInterval = Random.Range(2f, 12f);
					blinkTimer = 0f;
				}
			}
			if (base.isEnemyDead || (Object)(object)attachedPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				return;
			}
			PlayerControllerB val = null;
			float num = 7f;
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				if (!((Object)(object)val2 == (Object)(object)attachedPlayer))
				{
					float num2 = Vector3.Distance(eyeTransform.position, ((Component)val2.gameplayCamera).transform.position);
					Vector3 val3 = ((Component)val2).transform.position - eyeTransform.position;
					float num3 = Vector3.Angle(eyeOriginalTransform.forward, val3);
					if (num2 < num && num3 < 70f)
					{
						val = val2;
						num = num2;
					}
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				Transform transform = ((Component)val.gameplayCamera).transform;
				float num4 = Vector3.Distance(eyeTransform.position, transform.position);
				if (num4 < 7f)
				{
					Vector3 val4 = transform.position - eyeTransform.position;
					Quaternion val5 = Quaternion.LookRotation(val4, eyeTransform.up);
					Quaternion val6 = Quaternion.RotateTowards(eyeOriginalTransform.rotation, val5, 40f);
					float num5 = Quaternion.Angle(val5, eyeOriginalTransform.rotation);
					if (num5 < 90f)
					{
						eyeTransform.rotation = Quaternion.RotateTowards(eyeTransform.rotation, val6, 120f * Time.deltaTime);
						return;
					}
				}
			}
			eyeTransform.rotation = Quaternion.RotateTowards(eyeTransform.rotation, eyeOriginalTransform.rotation, 20f * Time.deltaTime);
		}

		public override void Update()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: 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)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0403: Unknown result type (might be due to invalid IL or missing references)
			//IL_0414: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			((EnemyAI)this).Update();
			if (base.isEnemyDead)
			{
				base.currentBehaviourStateIndex = 7;
			}
			else if (base.currentBehaviourStateIndex == 0 || base.currentBehaviourStateIndex == 1 || base.currentBehaviourStateIndex == 5)
			{
				CalculateAnimationDirection();
			}
			if (base.currentBehaviourStateIndex == 0)
			{
				PutCreatureOnGround();
				if (!((NetworkBehaviour)this).IsOwner)
				{
					return;
				}
				stateTimer += Time.deltaTime;
				if (!(stateTimer < 0.15f))
				{
					stateTimer = 0f;
					PlayerControllerB val = ((EnemyAI)this).CheckLineOfSightForClosestPlayer(70f, sightRange, 3, 0f);
					if (!((Object)(object)val == (Object)null) && !(Vector3.Distance(base.eye.position, ((Component)val.gameplayCamera).transform.position) > (float)sightRange))
					{
						PlayCreatureSFXServerRpc(0);
						BeginChasingPlayerServerRpc((int)val.playerClientId);
						SwitchBehaviourState(1);
					}
				}
			}
			else if (base.currentBehaviourStateIndex == 1)
			{
				PutCreatureOnGround();
				if (!((NetworkBehaviour)this).IsOwner)
				{
					return;
				}
				if (stateTimer2 < 0.5f)
				{
					stateTimer2 += Time.deltaTime;
					return;
				}
				if ((Object)(object)base.targetPlayer != (Object)null && Vector3.Distance(((Component)base.targetPlayer.playerGlobalHead).transform.position, base.eye.position) < 8f)
				{
					Vector3 val2 = ((Component)base.targetPlayer.playerGlobalHead).transform.position - base.eye.position;
					val2.y = 0f;
					Vector3 forward = base.eye.forward;
					forward.y = 0f;
					if (Vector3.Angle(forward, val2) < 15f)
					{
						PlayCreatureSFXServerRpc(3);
						SwitchBehaviourState(3);
						JumpAtPlayerServerRpc(base.targetPlayer.playerClientId);
						return;
					}
				}
				stateTimer += Time.deltaTime;
				if (stateTimer < 0.15f)
				{
					return;
				}
				stateTimer = 0f;
				PlayerControllerB val3 = ((EnemyAI)this).CheckLineOfSightForClosestPlayer(70f, sightRange, 3, 0f);
				if ((Object)(object)val3 == (Object)null || Vector3.Distance(base.eye.position, ((Component)val3.gameplayCamera).transform.position) > (float)sightRange)
				{
					stateCounter++;
					if (stateCounter >= 8)
					{
						stateCounter = 0;
						SwitchBehaviourState(0);
					}
				}
				else if ((Object)(object)val3 != (Object)(object)GameNetworkManager.Instance.localPlayerController)
				{
					BeginChasingPlayerServerRpc((int)val3.playerClientId);
				}
			}
			else if (base.currentBehaviourStateIndex == 2)
			{
				PutCreatureOnGround();
				if (!((NetworkBehaviour)this).IsOwner)
				{
					return;
				}
				stateTimer += Time.deltaTime;
				if (stateTimer > 5.5f)
				{
					stateTimer = 0f;
					if ((Object)(object)base.targetPlayer != (Object)null)
					{
						SwitchBehaviourState(1);
					}
					else
					{
						SwitchBehaviourState(0);
					}
				}
				stateTimer2 += Time.deltaTime;
				if (!(stateTimer2 < 0.5f))
				{
					stateTimer2 = 0f;
					PlayerControllerB val4 = ((EnemyAI)this).CheckLineOfSightForClosestPlayer(70f, sightRange, 3, 0f);
					if (!((Object)(object)val4 == (Object)null) && !(Vector3.Distance(base.eye.position, ((Component)val4.gameplayCamera).transform.position) > (float)sightRange))
					{
						BeginChasingPlayerServerRpc((int)val4.playerClientId);
					}
				}
			}
			else if (base.currentBehaviourStateIndex == 3)
			{
				if (!((NetworkBehaviour)this).IsOwner)
				{
					((Component)this).transform.position = base.serverPosition;
					return;
				}
				((EnemyAI)this).SyncPositionToClients();
				if (stateCounter == 0)
				{
					stateTimer += Time.deltaTime;
					if (stateTimer > 2.5f)
					{
						hitboxCollider.radius = 0.5f;
						SphereCollider obj = physicsCollider;
						((Collider)obj).includeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj).includeLayers) | 0x80000);
						SphereCollider obj2 = physicsCollider;
						((Collider)obj2).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj2).excludeLayers) & -524289);
						stateCounter = 1;
					}
				}
				stateTimer2 += Time.deltaTime;
				if (!(stateTimer2 < 5f))
				{
					stateTimer2 = 0f;
					PlayCreatureSFXServerRpc(0, 0.5f);
					SwitchBehaviourState(5);
				}
			}
			else if (base.currentBehaviourStateIndex == 4)
			{
				if (((NetworkBehaviour)this).IsOwner)
				{
					((EnemyAI)this).SyncPositionToClients();
				}
				stateTimer += Time.deltaTime;
				if (stateTimer < 1f)
				{
					return;
				}
				stateTimer = 0f;
				if (Time.time < NextWhisperTime)
				{
					return;
				}
				NextWhisperTime = Time.time + 10f;
				Collider[] array = Physics.OverlapSphere(((Component)this).transform.position, 16f, LayerMask.GetMask(new string[1] { "Enemies" }), (QueryTriggerInteraction)2);
				Collider[] array2 = array;
				foreach (Collider val5 in array2)
				{
					EnemyAI componentInParent = ((Component)val5).gameObject.GetComponentInParent<EnemyAI>();
					if ((Object)(object)componentInParent != (Object)null && !Peeper.ignoreEnemies.Contains(componentInParent.enemyType.enemyName))
					{
						PlayCreatureSFXServerRpc(7);
						NextWhisperTime = Time.time + Random.Range(6f, 12f);
						return;
					}
				}
				NextWhisperTime = Time.time + 1f;
			}
			else if (base.currentBehaviourStateIndex == 5)
			{
				PutCreatureOnGround();
				if (((NetworkBehaviour)this).IsOwner)
				{
					stateTimer += Time.deltaTime;
					if (!(stateTimer < 1.2f))
					{
						stateTimer = 0f;
						SwitchBehaviourState(0);
					}
				}
			}
			else if (base.currentBehaviourStateIndex == 6)
			{
				if (!((NetworkBehaviour)this).IsOwner)
				{
					((Component)this).transform.position = base.serverPosition;
					return;
				}
				((EnemyAI)this).SyncPositionToClients();
				stateTimer += Time.deltaTime;
				if (!(stateTimer < 5f))
				{
					stateTimer = 4.5f;
					Vector3 velocity = physicsRigidbody.velocity;
					if (!(((Vector3)(ref velocity)).sqrMagnitude > 10f))
					{
						PlayCreatureSFXServerRpc(0, 0.5f);
						SwitchBehaviourState(5);
					}
				}
			}
			else
			{
				if (base.currentBehaviourStateIndex != 7 || ragdollFrozen)
				{
					return;
				}
				stateTimer += Time.deltaTime;
				if (!(stateTimer < 15f))
				{
					stateTimer = 0f;
					Rigidbody[] array3 = ragdollRigidbodies;
					foreach (Rigidbody val6 in array3)
					{
						val6.isKinematic = true;
						ragdollFrozen = true;
					}
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void JumpAtPlayerServerRpc(ulong playerObjectId)
		{
			//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(3297439372u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3297439372u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					JumpAtPlayerClientRpc(playerObjectId);
				}
			}
		}

		[ClientRpc]
		public void JumpAtPlayerClientRpc(ulong playerObjectId)
		{
			//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(3646752176u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3646752176u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					JumpAtPlayer(StartOfRound.Instance.allPlayerScripts[(int)(IntPtr)checked((long)playerObjectId)]);
				}
			}
		}

		private void JumpAtPlayer(PlayerControllerB playerScript)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: 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)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			if (!base.isEnemyDead && !isAttached)
			{
				base.agent.speed = 0f;
				creatureModel.transform.localPosition = Vector3.zero;
				base.creatureAnimator.SetBool("Jump", true);
				base.creatureAnimator.SetBool("Attached", false);
				base.creatureAnimator.SetBool("Dead", false);
				isAttached = false;
				base.inSpecialAnimation = true;
				((Behaviour)base.agent).enabled = false;
				base.enemyType.canBeStunned = true;
				((Collider)attachCollider).enabled = true;
				((Collider)physicsCollider).enabled = true;
				physicsRigidbody.isKinematic = false;
				((Collider)hitboxCollider).enabled = true;
				hitboxCollider.radius = 2f;
				Vector3 val = ((Component)playerScript.playerGlobalHead).transform.position;
				if ((Object)(object)base.targetPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)
				{
					val += base.targetPlayer.thisController.velocity / 5f;
				}
				else if (base.targetPlayer.timeSincePlayerMoving < 0.25f)
				{
					val += Vector3.Normalize((base.targetPlayer.serverPlayerPosition - base.targetPlayer.oldPlayerPosition) * 100f);
				}
				Rigidbody obj = physicsRigidbody;
				Vector3 val2 = val - ((Component)this).transform.position + Vector3.up;
				obj.velocity = 33f * ((Vector3)(ref val2)).normalized;
				base.creatureAnimator.SetBool("Grounded", false);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void BeginChasingPlayerServerRpc(int playerObjectId)
		{
			//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(2492932585u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2492932585u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					BeginChasingPlayerClientRpc(playerObjectId);
				}
			}
		}

		[ClientRpc]
		public void BeginChasingPlayerClientRpc(int playerObjectId)
		{
			//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(3529258009u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3529258009u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					BeginChasingPlayer(playerObjectId);
				}
			}
		}

		public void BeginChasingPlayer(int playerObjectId)
		{
			PlayerControllerB movingTowardsTargetPlayer = (base.targetPlayer = StartOfRound.Instance.allPlayerScripts[playerObjectId]);
			if (((NetworkBehaviour)this).OwnerClientId != (ulong)playerObjectId)
			{
				((EnemyAI)this).ChangeOwnershipOfEnemy((ulong)playerObjectId);
			}
			((EnemyAI)this).SetMovingTowardsTargetPlayer(movingTowardsTargetPlayer);
		}

		[ServerRpc(RequireOwnership = false)]
		public void PlayCreatureSFXServerRpc(int index, float volume = 1f)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			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(1656237277u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref volume, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1656237277u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					PlayCreatureSFXClientRpc(index, volume);
				}
			}
		}

		[ClientRpc]
		public void PlayCreatureSFXClientRpc(int index, float volume = 1f)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			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(2720121576u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, index);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref volume, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2720121576u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayCreatureSFX(index, volume);
				}
			}
		}

		private void PlayCreatureSFX(int index, float volume = 1f)
		{
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			base.creatureVoice.pitch = Random.Range(0.8f, 1.1f);
			AttachSFXSource.pitch = Random.Range(0.9f, 1.05f);
			switch (index)
			{
			case 0:
			{
				AudioClip val = spotSFX[Random.Range(0, spotSFX.Length)];
				base.creatureVoice.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(base.creatureVoice, val, volume);
				break;
			}
			case 1:
				base.creatureSFX.PlayOneShot(walkSFX, volume * 0.22f);
				WalkieTalkie.TransmitOneShotAudio(base.creatureSFX, walkSFX, volume * 0.22f);
				break;
			case 2:
				base.creatureSFX.PlayOneShot(runSFX, volume * 0.25f);
				WalkieTalkie.TransmitOneShotAudio(base.creatureSFX, runSFX, volume * 0.25f);
				break;
			case 3:
			{
				AudioClip val = jumpSFX[Random.Range(0, jumpSFX.Length)];
				base.creatureVoice.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(base.creatureVoice, val, volume);
				break;
			}
			case 4:
			{
				AudioClip val = attachSFX[0];
				AttachSFXSource.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(AttachSFXSource, val, volume);
				break;
			}
			case 5:
			{
				AudioClip val = deathSFX[Random.Range(0, deathSFX.Length)];
				base.creatureVoice.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(base.creatureVoice, val, volume);
				break;
			}
			case 6:
			{
				AudioClip val = ejectSFX[Random.Range(0, ejectSFX.Length)];
				base.creatureVoice.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(base.creatureVoice, val, volume);
				break;
			}
			case 7:
			{
				AudioClip val = whisperSFX[Random.Range(0, whisperSFX.Length)];
				AttachSFXSource.PlayOneShot(val, volume);
				WalkieTalkie.TransmitOneShotAudio(AttachSFXSource, val, volume);
				RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, 18f, 0.6f, 0, false, 0);
				break;
			}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void AttachToPlayerServerRpc(ulong playerObjectId)
		{
			//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(2592041692u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2592041692u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					AttachToPlayerClientRpc(playerObjectId);
				}
			}
		}

		[ClientRpc]
		public void AttachToPlayerClientRpc(ulong playerObjectId)
		{
			//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(4096406816u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4096406816u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					AttachToPlayerLocally(StartOfRound.Instance.allPlayerScripts[(int)(IntPtr)checked((long)playerObjectId)]);
				}
			}
		}

		private void AttachToPlayerLocally(PlayerControllerB playerScript)
		{
			//IL_0220: 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_025f: 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_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0418: Unknown result type (might be due to invalid IL or missing references)
			//IL_041d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Unknown result type (might be due to invalid IL or missing references)
			if (base.isEnemyDead || isAttached || playerScript.isPlayerDead)
			{
				return;
			}
			int num = 0;
			foreach (PeeperAI peeper in Peeper.PeeperList)
			{
				if ((Object)(object)peeper.attachedPlayer == (Object)(object)playerScript)
				{
					num++;
				}
			}
			if (num >= 10)
			{
				return;
			}
			isAttached = true;
			base.targetPlayer = playerScript;
			attachedPlayer = playerScript;
			if (!playerScript.isPlayerDead)
			{
				IsWeighted = true;
			}
			if ((Object)(object)playerScript == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
			((EnemyAI)this).ChangeOwnershipOfEnemy(playerScript.actualClientId);
			SwitchBehaviourStateLocally(4);
			PlayCreatureSFX(4);
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			Transform val = null;
			Random.InitState(base.thisEnemyIndex + StartOfRound.Instance.randomMapSeed);
			int num5 = Random.Range(0, 11);
			for (int i = 0; i < 10; i++)
			{
				if (num5 == 6)
				{
					num5++;
				}
				if (!UsedAttachTargets.Contains(attachedPlayer.bodyParts[num5]))
				{
					val = ((num5 != 0 || !((Object)(object)attachedPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)) ? attachedPlayer.bodyParts[num5] : ((Component)attachedPlayer.gameplayCamera).transform);
					UsedAttachTargets.Add(val);
					attachTargetTransform = val;
					break;
				}
				num5 = ((num5 != 10) ? (num5 + 1) : 0);
			}
			if (!((Object)(object)val == (Object)null))
			{
				switch (num5)
				{
				case 0:
					num2 = Random.Range(-30f, -90f);
					num3 = Random.Range(80f, 280f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0.35f, 0.2f);
					break;
				case 1:
					num3 = Random.Range(60f, 160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.075f);
					break;
				case 2:
					num3 = Random.Range(-60f, -160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.075f);
					break;
				case 3:
					num3 = Random.Range(0f, 160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.2f);
					break;
				case 4:
					num3 = Random.Range(0f, -160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.2f);
					break;
				case 5:
					num3 = Random.Range(-30f, 30f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.2f);
					break;
				case 7:
					num3 = Random.Range(0f, 160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.2f);
					break;
				case 8:
					num3 = Random.Range(0f, -160f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.2f);
					break;
				case 9:
					num3 = Random.Range(160f, 280f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.15f);
					break;
				case 10:
					num3 = Random.Range(-20f, 100f);
					num4 = Random.Range(0f, 360f);
					attachTargetTranslationOffset = new Vector3(0f, 0f, 0.15f);
					break;
				default:
					Debug.Log((object)("Peepers have encountered an error when attaching! Report it to the developer! Target Index: " + num5));
					break;
				}
				attachTargetRotationOffset = new Vector3(num2, num3, num4);
				creatureModel.transform.localPosition = Vector3.zero;
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void EjectFromPlayerServerRpc(ulong playerObjectId)
		{
			//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(1104444428u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1104444428u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					EjectFromPlayerClientRpc(playerObjectId);
				}
			}
		}

		[ClientRpc]
		public void EjectFromPlayerClientRpc(ulong playerObjectId)
		{
			//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(280628075u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerObjectId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 280628075u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					EjectFromPlayer(StartOfRound.Instance.allPlayerScripts[(int)(IntPtr)checked((long)playerObjectId)]);
				}
			}
		}

		public void EjectFromPlayer(PlayerControllerB playerScript)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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)
			//IL_0094: 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)
			if (isAttached)
			{
				isAttached = false;
				if (!playerScript.isPlayerDead)
				{
					IsWeighted = false;
				}
				attachedPlayer = null;
				UsedAttachTargets.Remove(attachTargetTransform);
				attachTargetTransform = null;
				if (!base.isEnemyDead)
				{
					SwitchBehaviourStateLocally(6);
				}
				Vector3 val = ((Component)playerScript).transform.position - ((Component)this).transform.position;
				val.y = 0f;
				val = ((Vector3)(ref val)).normalized;
				val.y = -1f;
				physicsRigidbody.AddForce(-10f * val, (ForceMode)1);
				PlayCreatureSFX(6);
			}
		}

		public static bool HasLineOfSightToPeeper(Vector3 position)
		{
			//IL_001e: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			foreach (PeeperAI peeper in Peeper.PeeperList)
			{
				if ((Object)(object)peeper != (Object)null)
				{
					Vector3 val = position - peeper.eyeTransform.position;
					float num = Vector3.Angle(peeper.eyeOriginalTransform.forward, val);
					if (Vector3.Distance(position, peeper.eyeTransform.position) < 10f && num < 60f && !Physics.Linecast(((Component)peeper.eyeTransform).transform.position, position, StartOfRound.Instance.collidersRoomDefaultAndFoliage, (QueryTriggerInteraction)1))
					{
						return true;
					}
				}
			}
			return false;
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_PeeperAI()
		{
			//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(1087886824u, new RpcReceiveHandler(__rpc_handler_1087886824));
			NetworkManager.__rpc_func_table.Add(2756874777u, new RpcReceiveHandler(__rpc_handler_2756874777));
			NetworkManager.__rpc_func_table.Add(316864934u, new RpcReceiveHandler(__rpc_handler_316864934));
			NetworkManager.__rpc_func_table.Add(4022924503u, new RpcReceiveHandler(__rpc_handler_4022924503));
			NetworkManager.__rpc_func_table.Add(3297439372u, new RpcReceiveHandler(__rpc_handler_3297439372));
			NetworkManager.__rpc_func_table.Add(3646752176u, new RpcReceiveHandler(__rpc_handler_3646752176));
			NetworkManager.__rpc_func_table.Add(2492932585u, new RpcReceiveHandler(__rpc_handler_2492932585));
			NetworkManager.__rpc_func_table.Add(3529258009u, new RpcReceiveHandler(__rpc_handler_3529258009));
			NetworkManager.__rpc_func_table.Add(1656237277u, new RpcReceiveHandler(__rpc_handler_1656237277));
			NetworkManager.__rpc_func_table.Add(2720121576u, new RpcReceiveHandler(__rpc_handler_2720121576));
			NetworkManager.__rpc_func_table.Add(2592041692u, new RpcReceiveHandler(__rpc_handler_2592041692));
			NetworkManager.__rpc_func_table.Add(4096406816u, new RpcReceiveHandler(__rpc_handler_4096406816));
			NetworkManager.__rpc_func_table.Add(1104444428u, new RpcReceiveHandler(__rpc_handler_1104444428));
			NetworkManager.__rpc_func_table.Add(280628075u, new RpcReceiveHandler(__rpc_handler_280628075));
		}

		private static void __rpc_handler_1087886824(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;
				((PeeperAI)(object)target).KillEnemyServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2756874777(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;
				((PeeperAI)(object)target).KillEnemyClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_316864934(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 state = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref state);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((PeeperAI)(object)target).SwitchBehaviourStateServerRpc(state);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4022924503(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 state = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref state);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((PeeperAI)(object)target).SwitchBehaviourStateClientRpc(state);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

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

		private static void __rpc_handler_2492932585(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 playerObjectId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerObjectId);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((PeeperAI)(object)target).BeginChasingPlayerServerRpc(playerObjectId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3529258009(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 playerObjectId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerObjectId);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((PeeperAI)(object)target).BeginChasingPlayerClientRpc(playerObjectId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1656237277(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int index = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref index);
				float volume = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref volume, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((PeeperAI)(object)target).PlayCreatureSFXServerRpc(index, volume);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2720121576(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int index = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref index);
				float volume = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref volume, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((PeeperAI)(object)target).PlayCreatureSFXClientRpc(index, volume);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

plugins/ScoopysVarietyMod/ScoopysVarietyMod.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.IO;
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 DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLevelLoader;
using LethalLib.Modules;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LethalExtension")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalExtension")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("94d2de4e-bed1-40e3-b759-cf53352d4930")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace ScoopysVarietyMod
{
	[BepInPlugin("ScoopysVarietyMod", "Scoopy's Variety Mod", "1.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(QuicksandTrigger))]
		internal class QuicksandPatch
		{
			[HarmonyPatch("OnTriggerStay")]
			[HarmonyPrefix]
			private static bool FacilityQuicksand(Collider other, ref QuicksandTrigger __instance)
			{
				//IL_0062: 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_007b: Expected O, but got Unknown
				//IL_007b: Expected O, but got Unknown
				//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0102: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Expected O, but got Unknown
				//IL_010c: Expected O, but got Unknown
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Expected O, but got Unknown
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Expected O, but got Unknown
				//IL_00a2: Expected O, but got Unknown
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				//IL_015a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0168: Unknown result type (might be due to invalid IL or missing references)
				RoundManager obj = Object.FindObjectOfType<RoundManager>();
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if (((Object)obj.dungeonGenerator.Generator.DungeonFlow).name != "SewerFlow" || !GameNetworkManager.Instance.localPlayerController.isInsideFactory)
				{
					return true;
				}
				if (__instance.isWater)
				{
					if (!((Component)other).gameObject.CompareTag("Player"))
					{
						return true;
					}
					if ((Object)component != (Object)GameNetworkManager.Instance.localPlayerController && (Object)component != (Object)null && (Object)component.underwaterCollider != (Object)__instance)
					{
						component.underwaterCollider = ((Component)__instance).gameObject.GetComponent<Collider>();
						return true;
					}
				}
				if (GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom || (!__instance.isWater && !((Component)other).gameObject.CompareTag("Player")))
				{
					return true;
				}
				PlayerControllerB component2 = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)component2 != (Object)GameNetworkManager.Instance.localPlayerController)
				{
					return true;
				}
				if (__instance.isWater && !component2.isUnderwater)
				{
					component2.underwaterCollider = ((Component)__instance).gameObject.GetComponent<Collider>();
					component2.isUnderwater = true;
				}
				component2.statusEffectAudioIndex = __instance.audioClipIndex;
				if (component2.isUnderwater)
				{
					Bounds bounds = component2.underwaterCollider.bounds;
					if (!((Bounds)(ref bounds)).Contains(((Component)component2.gameplayCamera).transform.position))
					{
						component2.statusEffectAudio.volume = component2.statusEffectAudio.volume * 0.25f;
					}
				}
				if (component2.isSinking)
				{
					return false;
				}
				if (__instance.sinkingLocalPlayer)
				{
					if (!component2.CheckConditionsForSinkingInQuicksand())
					{
						__instance.StopSinkingLocalPlayer(component2);
					}
				}
				else if (component2.CheckConditionsForSinkingInQuicksand())
				{
					__instance.sinkingLocalPlayer = true;
					component2.sourcesCausingSinking++;
					component2.isMovementHindered++;
					component2.hinderedMultiplier *= __instance.movementHinderance;
					if (__instance.isWater)
					{
						component2.sinkingSpeedMultiplier = 0f;
					}
					else
					{
						component2.sinkingSpeedMultiplier = __instance.sinkingSpeedMultiplier;
					}
				}
				return false;
			}
		}

		private const string modGUID = "ScoopysVarietyMod";

		private const string modName = "Scoopy's Variety Mod";

		private const string modVersion = "1.2.0";

		private static Plugin Instance;

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

		private ConfigEntry<int> configCastleRarity;

		private ConfigEntry<string> configCastleMoons;

		private ConfigEntry<string> configCastleMoonsList;

		private ConfigEntry<bool> configGuaranteeCastle;

		private ConfigEntry<float> configCastleSizeMultiplierMax;

		private ConfigEntry<float> configCastleSizeMultiplierMin;

		private ConfigEntry<int> configSewerRarity;

		private ConfigEntry<string> configSewerMoons;

		private ConfigEntry<string> configSewerMoonsList;

		private ConfigEntry<bool> configGuaranteeSewer;

		private ConfigEntry<float> configSewerSizeMultiplierMax;

		private ConfigEntry<float> configSewerSizeMultiplierMin;

		private ConfigEntry<int> configGuitarRarity;

		private ConfigEntry<int> configFireaxeRarity;

		private ConfigEntry<int> configFireaxeDamage;

		private string[] configMoonsValues = new string[5] { "vanilla", "modded", "all", "paid", "list" };

		internal ManualLogSource MLS;

		public static AssetBundle Assets;

		private void Awake()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Expected O, but got Unknown
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Expected O, but got Unknown
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Expected O, but got Unknown
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Expected O, but got Unknown
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Expected O, but got Unknown
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Expected O, but got Unknown
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Expected O, but got Unknown
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Expected O, but got Unknown
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Expected O, but got Unknown
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			MLS = Logger.CreateLogSource("ScoopysVarietyMod");
			string? directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			configCastleRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Castle Interior", "CastleDungeonSpawnChance", 300, new ConfigDescription("Adjusts likelihood of the dungeon interior spawning. Higher values increases the chance of spawning. At a value of 300, the spawn chance would be approx 50% on vanilla moons", (AcceptableValueBase)new AcceptableValueRange<int>(0, 99999), Array.Empty<object>()));
			configCastleMoons = ((BaseUnityPlugin)this).Config.Bind<string>("Castle Interior", "CastleDungeonMoons", "vanilla", new ConfigDescription("Specifies the moons that the dungeon interior can spawn on. Vanilla moons can be selected using 'vanilla', or all modded moons using 'modded'. \nAll moons (vanilla & modded) can be selected using 'all'. Paid moons can be selected using 'paid'. \nIndividual moons (including modded) can be specified using 'list' and altering the CastleDungeonMoonsList config entry.", (AcceptableValueBase)new AcceptableValueList<string>(configMoonsValues), Array.Empty<object>()));
			configCastleMoonsList = ((BaseUnityPlugin)this).Config.Bind<string>("Castle Interior", "CastleDungeonMoonsList", (string)null, new ConfigDescription("Note: Requires 'CastleDungeonMoons' to be set to 'list'. \nCan be used to specify a list of moons with individual rarities for moons to spawn on. \nRarity values will override the default rarity value provided in CastleDungeonSpawnChance and will override CastleDungeonGuaranteed. To guarantee dungeon spawning on a moon, assign arbitrarily high rarity value (e.g. 99999). \nMoons and rarities should be provided as a comma seperated list in the following format: 'NameRarity' Example: rend300,dine20,experimentation13 \nNote: Moon names are checked by string matching, i.e. the moon name 'dine' would enable spawning on 'dine', 'diner' and 'undine'. Be careful with modded moon names.", (AcceptableValueBase)null, Array.Empty<object>()));
			configGuaranteeCastle = ((BaseUnityPlugin)this).Config.Bind<bool>("Castle Interior", "CastleDungeonGuaranteed", false, new ConfigDescription("If enabled, the dungeon interior will be effectively guaranteed to spawn on moons where it can spawn as per CastleDungeonMoons. Note: Using ", (AcceptableValueBase)null, Array.Empty<object>()));
			configCastleSizeMultiplierMax = ((BaseUnityPlugin)this).Config.Bind<float>("Castle Interior", "MaxCastleSizeMultiplier", 2f, new ConfigDescription("Defines the maximum castle size multiplier, reducing multipliers above this to this value. \nFor reference, the vanilla modifiers are as follows: Experimentation 1x, Assurance 1x, Vow 1.15x, Rend 1.2x, Offense 1.25x, Dine 1.3x, March 2x, Titan 2.35x, ", (AcceptableValueBase)new AcceptableValueRange<float>(0.1f, 300f), Array.Empty<object>()));
			configCastleSizeMultiplierMin = ((BaseUnityPlugin)this).Config.Bind<float>("Castle Interior", "MinCastleSizeMultiplier", 1f, new ConfigDescription("Defines the minimum castle size multiplier, increasing multipliers below this to this value. \nFor reference, the vanilla modifiers are as follows: Experimentation 1x, Assurance 1x, Vow 1.15x, Rend 1.2x, Offense 1.25x, Dine 1.3x, March 2x, Titan 2.35x, ", (AcceptableValueBase)new AcceptableValueRange<float>(0.1f, 300f), Array.Empty<object>()));
			configSewerRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Sewer Interior", "SewerDungeonSpawnChance", 300, new ConfigDescription("Adjusts likelihood of the sewer interior spawning. Higher values increases the chance of spawning. At a value of 300, the spawn chance would be approx 50% on vanilla moons", (AcceptableValueBase)new AcceptableValueRange<int>(0, 99999), Array.Empty<object>()));
			configSewerMoons = ((BaseUnityPlugin)this).Config.Bind<string>("Sewer Interior", "SewerDungeonMoons", "vanilla", new ConfigDescription("Specifies the moons that the sewer interior can spawn on. Vanilla moons can be selected using 'vanilla', or all modded moons using 'modded'. \nAll moons (vanilla & modded) can be selected using 'all'. Paid moons can be selected using 'paid'. \nIndividual moons (including modded) can be specified using 'list' and altering the SewerDungeonMoonsList config entry.", (AcceptableValueBase)new AcceptableValueList<string>(configMoonsValues), Array.Empty<object>()));
			configSewerMoonsList = ((BaseUnityPlugin)this).Config.Bind<string>("Sewer Interior", "SewerDungeonMoonsList", (string)null, new ConfigDescription("Note: Requires 'SewerDungeonMoons' to be set to 'list'. \nCan be used to specify a list of moons with individual rarities for moons to spawn on. \nRarity values will override the default rarity value provided in sewerDungeonSpawnChance and will override SewerDungeonGuaranteed. To guarantee dungeon spawning on a moon, assign arbitrarily high rarity value (e.g. 99999). \nMoons and rarities should be provided as a comma seperated list in the following format: 'NameRarity' Example: rend300,dine20,experimentation13 \nNote: Moon names are checked by string matching, i.e. the moon name 'dine' would enable spawning on 'dine', 'diner' and 'undine'. Be careful with modded moon names.", (AcceptableValueBase)null, Array.Empty<object>()));
			configGuaranteeSewer = ((BaseUnityPlugin)this).Config.Bind<bool>("Sewer Interior", "SewerDungeonGuaranteed", false, new ConfigDescription("If enabled, the sewer interior will be effectively guaranteed to spawn on moons where it can spawn as per SewerDungeonMoons. Note: Using ", (AcceptableValueBase)null, Array.Empty<object>()));
			configSewerSizeMultiplierMax = ((BaseUnityPlugin)this).Config.Bind<float>("Sewer Interior", "MaxSewerSizeMultiplier", 2f, new ConfigDescription("Defines the maximum sewer size multiplier, reducing multipliers above this to this value. \nFor reference, the vanilla modifiers are as follows: Experimentation 1x, Assurance 1x, Vow 1.15x, Rend 1.2x, Offense 1.25x, Dine 1.3x, March 2x, Titan 2.35x, ", (AcceptableValueBase)new AcceptableValueRange<float>(0.1f, 300f), Array.Empty<object>()));
			configSewerSizeMultiplierMin = ((BaseUnityPlugin)this).Config.Bind<float>("Sewer Interior", "MinSewerSizeMultiplier", 1f, new ConfigDescription("Defines the minimum sewer size multiplier, increasing multipliers below this to this value. \nFor reference, the vanilla modifiers are as follows: Experimentation 1x, Assurance 1x, Vow 1.15x, Rend 1.2x, Offense 1.25x, Dine 1.3x, March 2x, Titan 2.35x, ", (AcceptableValueBase)new AcceptableValueRange<float>(0.1f, 300f), Array.Empty<object>()));
			configGuitarRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "GuitarRarity", 10, new ConfigDescription("Frequency of Guitar scrap spawning. Higher values are more common. Set to 0 to disable spawns.", (AcceptableValueBase)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			configFireaxeRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "FireaxeRarity", 5, new ConfigDescription("Frequency of Fire Axe scrap spawning. Higher values are more common. Set to 0 to disable spawns.", (AcceptableValueBase)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			configFireaxeDamage = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "FireaxeDamage", 4, new ConfigDescription("Damage of Fire Axe scrap spawning. Higher values are more damage. Damage of base game shovel is 1.", (AcceptableValueBase)new AcceptableValueRange<int>(0, 99999), Array.Empty<object>()));
			Assets = AssetBundle.LoadFromFile(Path.Combine(directoryName, "ScoopysVarietyMod"));
			if ((Object)(object)Assets == (Object)null)
			{
				MLS.LogError((object)"Failed to unpack ScoopysVarietyMod assetbundle.");
			}
			Item val = Assets.LoadAsset<Item>("Assets/ScoopysVarietyMod/ScrapAssets/Guitar/WeezerGuitar.asset");
			Item val2 = Assets.LoadAsset<Item>("Assets/ScoopysVarietyMod/ScrapAssets/FireAxe/FireAxe.asset");
			Item val3 = Assets.LoadAsset<Item>("Assets/ScoopysVarietyMod/ScrapAssets/Crown/CrownItem.asset");
			Item[] array = (Item[])(object)new Item[3] { val, val2, val3 };
			foreach (Item val4 in array)
			{
				if ((Object)(object)val4 == (Object)null)
				{
					MLS.LogError((object)"An item prefab failed to load");
				}
				else
				{
					MLS.LogInfo((object)("Successfully loaded " + (object)val4));
				}
			}
			val2.spawnPrefab.GetComponent<Shovel>().shovelHitForce = configFireaxeDamage.Value;
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(val2.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(val3.spawnPrefab);
			Items.RegisterScrap(val, configGuitarRarity.Value, (LevelTypes)(-1));
			Items.RegisterScrap(val2, configFireaxeRarity.Value, (LevelTypes)896);
			MLS.LogInfo((object)"Custom Scrap Loaded Successfully");
			DungeonFlow val5 = Assets.LoadAsset<DungeonFlow>("Assets/ScoopysVarietyMod/CastleAssets/CastleFlow.asset");
			DungeonFlow val6 = Assets.LoadAsset<DungeonFlow>("Assets/ScoopysVarietyMod/SewerAssets/SewerFlow.asset");
			if ((Object)(object)val5 == (Object)null || (Object)(object)val6 == (Object)null)
			{
				MLS.LogError((object)"Failed to load a Dungeon Flow. Did you install the assetbundle correctly?");
				return;
			}
			RegisterDungeon(val5, configCastleRarity.Value, configCastleMoons.Value, configCastleMoonsList.Value, configGuaranteeCastle.Value, configCastleSizeMultiplierMax.Value, configCastleSizeMultiplierMin.Value);
			RegisterDungeon(val6, configSewerRarity.Value, configSewerMoons.Value, configSewerMoonsList.Value, configGuaranteeSewer.Value, configSewerSizeMultiplierMax.Value, configSewerSizeMultiplierMin.Value);
			harmony.PatchAll(typeof(Plugin));
			MLS.LogInfo((object)"Initialised Successfully");
		}

		public static StringWithRarity ParseMoonString(string moonString)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			if (string.IsNullOrEmpty(moonString))
			{
				return null;
			}
			int num = moonString.Length - 1;
			while (num >= 0 && char.IsDigit(moonString[num]))
			{
				num--;
			}
			if (num < 0 || num == moonString.Length - 1)
			{
				return null;
			}
			try
			{
				string text = moonString.Substring(0, num + 1);
				int num2 = int.Parse(moonString.Substring(num + 1));
				return new StringWithRarity(text, num2);
			}
			catch (FormatException)
			{
				return null;
			}
		}

		public void RegisterDungeon(DungeonFlow dungeonFlow, int dungeonRarity, string dungeonMoons, string dungeonMoonsList, bool guaranteeDungeon, float dungeonSizeMax, float dungeonSizeMin)
		{
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Expected O, but got Unknown
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			MLS.LogInfo((object)("Registering flow " + ((Object)dungeonFlow).name + " with:\ndungeonRarity: " + dungeonRarity + "\ndungeonMoons: " + dungeonMoons + "\nguaranteeDungeon: " + guaranteeDungeon + "\ndungeonSizeMax: " + dungeonSizeMax + "\ndungeonSizeMin:" + dungeonSizeMin));
			ExtendedDungeonFlow val = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			val.dungeonFlow = dungeonFlow;
			val.dungeonFirstTimeAudio = null;
			val.dungeonDefaultRarity = 0;
			int num = (guaranteeDungeon ? 99999 : dungeonRarity);
			if (dungeonMoons.ToLowerInvariant() == "all")
			{
				val.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				val.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
				MLS.LogInfo((object)("Registered " + ((Object)dungeonFlow).name + " interior on all moons, including modded with rarity " + num + "."));
			}
			else if (dungeonMoons.ToLowerInvariant() == "vanilla")
			{
				val.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				MLS.LogInfo((object)("Registered " + ((Object)dungeonFlow).name + " dungeon interior on all vanilla moons with rarity" + num + "."));
			}
			else if (dungeonMoons.ToLowerInvariant() == "modded")
			{
				val.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
				MLS.LogInfo((object)("Registered " + ((Object)dungeonFlow).name + " dungeon interior on all modded moons with rarity " + num + "."));
			}
			else if (dungeonMoons.ToLowerInvariant() == "paid")
			{
				val.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(1f, 9999f), num));
				MLS.LogInfo((object)("Registered " + ((Object)dungeonFlow).name + " dungeon interior on all paid moons with rarity" + num + "."));
			}
			else if (dungeonMoons.ToLowerInvariant() == "list" && dungeonMoonsList != null)
			{
				string[] array = dungeonMoonsList.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text in array)
				{
					StringWithRarity val2 = ParseMoonString(text);
					if (val2 != null)
					{
						val.manualPlanetNameReferenceList.Add(val2);
						MLS.LogInfo((object)("Registered " + ((Object)dungeonFlow).name + " on moon name " + val2.Name + " with rarity " + val2.Rarity));
					}
					else
					{
						MLS.LogError((object)("Invalid moon list value!: " + text));
					}
				}
			}
			else
			{
				MLS.LogError((object)("Invalid " + ((object)dungeonFlow).ToString() + " 'DungeonMoons' config value!"));
			}
			val.dungeonSizeMax = dungeonSizeMax;
			val.dungeonSizeMin = dungeonSizeMin;
			val.dungeonSizeLerpPercentage = 0f;
			PatchedContent.RegisterExtendedDungeonFlow(val);
		}
	}
}

plugins/SCPCBDunGen/SCPCBDunGen.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLevelLoader;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SCPCBDunGen")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Adds the SCP Foundation Dungeon to Lethal Company.")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: AssemblyInformationalVersion("2.3.0+7416b5402cf0bbe5e2b8b44e0ac71bc766efcb06")]
[assembly: AssemblyProduct("SCPCBDunGen")]
[assembly: AssemblyTitle("SCPCBDunGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.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 SCPCBDunGen
{
	public struct SCP914Conversion
	{
		public string ItemName;

		public List<string> RoughResults { get; set; }

		public List<string> CoarseResults { get; set; }

		public List<string> OneToOneResults { get; set; }

		public List<string> FineResults { get; set; }

		public List<string> VeryFineResults { get; set; }
	}
	public class SCP914ConversionSet : KeyedCollection<string, SCP914Conversion>
	{
		protected override string GetKeyForItem(SCP914Conversion conversion)
		{
			return conversion.ItemName;
		}
	}
	[BepInPlugin("SCPCBDunGen", "SCPCBDunGen", "2.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class SCPCBDunGen : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("SpawnScrapInLevel")]
			[HarmonyPrefix]
			private static bool SetItemSpawnPoints(ref RuntimeDungeon ___dungeonGenerator)
			{
				if (((Object)___dungeonGenerator.Generator.DungeonFlow).name != "SCPFlow")
				{
					return true;
				}
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Instance.mls.LogError((object)"Failed to get start of round instance. Scrap spawns may not work correctly.");
					return true;
				}
				Item val = instance.allItemsList.itemsList.Find((Item x) => x.itemName == "Bottles");
				if ((Object)(object)val == (Object)null)
				{
					Instance.mls.LogError((object)"Failed to find bottle bin item for reference snatching; scrap spawn may be significantly lower than expected.");
					return true;
				}
				Item val2 = instance.allItemsList.itemsList.Find((Item x) => x.itemName == "Golden cup");
				int num = 0;
				int num2 = 0;
				int num3 = 0;
				ItemGroup spawnableItems = val.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "GeneralItemClass");
				ItemGroup val3 = val.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "TabletopItems");
				ItemGroup spawnableItems2 = (ItemGroup)(((Object)(object)val2 == (Object)null) ? ((object)val3) : ((object)val2.spawnPositionTypes.Find((ItemGroup x) => ((Object)x).name == "SmallItems")));
				RandomScrapSpawn[] array = Object.FindObjectsOfType<RandomScrapSpawn>();
				RandomScrapSpawn[] array2 = array;
				foreach (RandomScrapSpawn val4 in array2)
				{
					switch (((Object)val4.spawnableItems).name)
					{
					case "GeneralItemClassDUMMY":
						val4.spawnableItems = spawnableItems;
						num++;
						break;
					case "TabletopItemsDUMMY":
						val4.spawnableItems = val3;
						num2++;
						break;
					case "SmallItemsDUMMY":
						val4.spawnableItems = spawnableItems2;
						num3++;
						break;
					}
				}
				Instance.mls.LogInfo((object)$"Totals for scrap replacement: General: {num}, Tabletop: {num2}, Small: {num3}");
				if (num + num2 + num3 < 10)
				{
					Instance.mls.LogWarning((object)"Unusually low scrap spawn count; scrap may be sparse.");
				}
				return true;
			}

			public static void AddConversions(SCP914Converter SCP914, List<Item> lItems, string sItem, IEnumerable<string> arROUGH, IEnumerable<string> arCOARSE, IEnumerable<string> arONETOONE, IEnumerable<string> arFINE, IEnumerable<string> arVERYFINE)
			{
				IEnumerable<string>[] array = new IEnumerable<string>[5] { arROUGH, arCOARSE, arONETOONE, arFINE, arVERYFINE };
				Item val = lItems.Find((Item x) => x.itemName.ToLowerInvariant() == sItem);
				if ((Object)(object)val == (Object)null)
				{
					Instance.mls.LogError((object)("Failed to find item for conversion \"" + sItem + "\", skipping."));
					return;
				}
				foreach (SCP914Converter.SCP914Setting value in Enum.GetValues(typeof(SCP914Converter.SCP914Setting)))
				{
					List<Item> list = new List<Item>();
					foreach (string sItemName in array[(int)value])
					{
						if (sItemName == "*")
						{
							list.Add(null);
							continue;
						}
						if (sItemName == "@")
						{
							list.Add(val);
							continue;
						}
						list.Add(lItems.Find((Item x) => x.itemName.ToLowerInvariant() == sItemName));
					}
					SCP914.AddConversion(value, val, list);
				}
			}

			[HarmonyPatch("SpawnSyncedProps")]
			[HarmonyPostfix]
			private static void SCP914Configuration()
			{
				SCP914Converter sCP914Converter = Object.FindObjectOfType<SCP914Converter>();
				if ((Object)(object)sCP914Converter == (Object)null)
				{
					Instance.mls.LogInfo((object)"No 914 room found.");
					return;
				}
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Instance.mls.LogError((object)"Failed to find StartOfRound object.");
					return;
				}
				List<Item> list = instance.allItemsList?.itemsList;
				if (list == null)
				{
					Instance.mls.LogError((object)"Failed to get item list from StartOfRound.");
					return;
				}
				if (list.Count == 0)
				{
					Instance.mls.LogError((object)"Item list was empty from StartOfRound.");
					return;
				}
				foreach (SCP914Conversion sCP914Conversion in Instance.SCP914Conversions)
				{
					AddConversions(sCP914Converter, list, sCP914Conversion.ItemName, sCP914Conversion.RoughResults, sCP914Conversion.CoarseResults, sCP914Conversion.OneToOneResults, sCP914Conversion.FineResults, sCP914Conversion.VeryFineResults);
				}
			}
		}

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

		public static SCPCBDunGen Instance;

		public ManualLogSource mls;

		public static AssetBundle SCPCBAssets;

		private ConfigEntry<int> configSCPRarity;

		private ConfigEntry<string> configMoonsOld;

		private ConfigEntry<string> configMoons;

		private ConfigEntry<bool> configGuaranteedSCP;

		private ConfigEntry<int> configLengthOverride;

		private SCP914ConversionSet SCP914Conversions = new SCP914ConversionSet();

		private void Awake()
		{
			//IL_07e7: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Expected O, but got Unknown
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Expected O, but got Unknown
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Expected O, but got Unknown
			//IL_040d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0417: Expected O, but got Unknown
			//IL_0452: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_0463: Expected O, but got Unknown
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0585: Expected O, but got Unknown
			//IL_060b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0615: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			mls = Logger.CreateLogSource("SCPCBDunGen");
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			SCPCBAssets = AssetBundle.LoadFromFile(Path.Combine(directoryName, "scpcb_dungeon"));
			if ((Object)(object)SCPCBAssets == (Object)null)
			{
				mls.LogError((object)"Failed to load SCPCB Dungeon assets.");
				return;
			}
			DungeonFlow val = SCPCBAssets.LoadAsset<DungeonFlow>("assets/Mods/SCP/data/SCPFlow.asset");
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load SCP:CB Dungeon Flow.");
				return;
			}
			configSCPRarity = ((BaseUnityPlugin)this).Config.Bind<int>("General", "FoundationRarity", 100, new ConfigDescription("How rare it is for the foundation to be chosen. Higher values increases the chance of spawning the foundation. Vanillas' main dungeons use a value of 300. Google Weighted Random if you don't know how it works, as that's how Lethal Company rarities function.", (AcceptableValueBase)null, Array.Empty<object>()));
			configMoonsOld = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FoundationMoons", "NULL", new ConfigDescription("OLD CONFIG SETTING, HAS NO EFFECT. Only here to clear the legacy config from updating.", (AcceptableValueBase)null, Array.Empty<object>()));
			configMoons = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FoundationMoonsList", "Titan,Secret Labs", new ConfigDescription("The moon(s) that the foundation can spawn on, in the form of a comma separated list of selectable level names and optionally a weight value by using an '@' and weight value after it (e.g. \"Titan@300,Dine,Rend@10,Secret Labs@9999\")\nThe name matching is lenient and should pick it up if you use the terminal name or internal mod name. If no rarity is specified, the FoundationRarity parameter is used.\nThe following strings: \"all\", \"vanilla\", \"modded\", \"paid\", \"free\" are dynamic presets which add the dungeon to that specified group (string must only contain one of these, or a manual moon name list).\n", (AcceptableValueBase)null, Array.Empty<object>()));
			configGuaranteedSCP = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "FoundationGuaranteed", false, new ConfigDescription("OLD CONFIG SETTING, HAS NO EFFECT. Only here to clear the legacy config from updating.\nIf you want to effectively guarantee the foundation, use a weight of something like '99999'", (AcceptableValueBase)null, Array.Empty<object>()));
			configLengthOverride = ((BaseUnityPlugin)this).Config.Bind<int>("General", "FoundationLengthOverride", -1, new ConfigDescription(string.Format("If not -1, overrides the foundation length to whatever you'd like. Adjusts how long/large the dungeon generates.\nBe *EXTREMELY* careful not to set this too high (anything too big on a moon with a high dungeon size multipier can cause catastrophic problems, like crashing your computer or worse)\nFor reference, the default value for the current version [{0}] is {1}. If it's too big, make this lower e.g. 6, if it's too small use something like 10 (or higher, but don't go too crazy with it).", "2.3.0", val.Length.Min), (AcceptableValueBase)null, Array.Empty<object>()));
			if (configMoonsOld.Value != "NULL")
			{
				mls.LogWarning((object)"Old config parameters detected for old moon setting; config has changed since 1.3.1, check the config and set FoundationMoons to NULL to suppress this warning (and change FoundationMoonsList if you want)");
			}
			if (configGuaranteedSCP.Value)
			{
				mls.LogWarning((object)"Old config parameters detected for Guaranteed SCP; config has changed since 2.0.2, check the config and set GuaranteedSCP to false to suppress this warning (see uncapped FoundationRarity)");
			}
			if (configLengthOverride.Value != -1)
			{
				mls.LogInfo((object)$"Foundation length override has been set to {configLengthOverride.Value}. Be careful with this value.");
				val.Length.Min = configLengthOverride.Value;
				val.Length.Max = configLengthOverride.Value;
			}
			ExtendedDungeonFlow val2 = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			val2.contentSourceName = "SCP Foundation Dungeon";
			val2.dungeonFlow = val;
			val2.dungeonFirstTimeAudio = SCPCBAssets.LoadAsset<AudioClip>("assets/Mods/SCP/snd/Horror8.ogg");
			val2.dungeonDefaultRarity = 0;
			int num = (configGuaranteedSCP.Value ? 99999 : configSCPRarity.Value);
			switch (configMoons.Value.ToLower())
			{
			case "all":
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
				mls.LogInfo((object)"Registered SCP dungeon for all moons.");
				break;
			case "vanilla":
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				mls.LogInfo((object)"Registered SCP dungeon for all vanilla moons.");
				break;
			case "modded":
				val2.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
				mls.LogInfo((object)"Registered SCP dungeon for all modded moons.");
				break;
			case "paid":
				val2.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(1f, 9999f), num));
				mls.LogInfo((object)"Registered SCP dungeon for all paid moons.");
				break;
			case "free":
				val2.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(0f, 0f), num));
				mls.LogInfo((object)"Registered SCP dungeon for all free moons.");
				break;
			default:
			{
				mls.LogInfo((object)"Registering SCP dungeon for predefined moon list.");
				string[] array3 = configMoons.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
				List<StringWithRarity> list = new List<StringWithRarity>();
				for (int k = 0; k < array3.Length; k++)
				{
					string[] array4 = array3[k].Split('@', StringSplitOptions.RemoveEmptyEntries);
					int num2 = array4.Length;
					int result;
					if (num2 > 2)
					{
						mls.LogError((object)("Invalid setup for moon rarity config: " + array3[k] + ". Skipping."));
					}
					else if (num2 == 1)
					{
						mls.LogInfo((object)$"Registering SCP dungeon for moon {array3[k]} at default rarity {num}");
						list.Add(new StringWithRarity(array3[k], num));
					}
					else if (!int.TryParse(array4[1], out result))
					{
						mls.LogError((object)("Failed to parse rarity value for moon " + array4[0] + ": " + array4[1] + ". Skipping."));
					}
					else
					{
						mls.LogInfo((object)$"Registering SCP dungeon for moon {array3[k]} at default rarity {num}");
						list.Add(new StringWithRarity(array4[0], result));
					}
				}
				val2.manualPlanetNameReferenceList = list;
				break;
			}
			}
			val2.dungeonSizeMin = 1f;
			val2.dungeonSizeMax = 3f;
			val2.dungeonSizeLerpPercentage = 0f;
			AssetBundleLoader.RegisterExtendedDungeonFlow(val2);
			foreach (string item in DiscoverConfiguredRecipeFiles())
			{
				StreamReader streamReader = new StreamReader(item);
				string text = streamReader.ReadToEnd();
				try
				{
					List<SCP914Conversion> list2 = JsonConvert.DeserializeObject<List<SCP914Conversion>>(text);
					foreach (SCP914Conversion item2 in list2)
					{
						if (SCP914Conversions.Contains(item2.ItemName.ToLowerInvariant()))
						{
							SCP914Conversions[item2.ItemName].RoughResults.AddRange(item2.RoughResults);
							SCP914Conversions[item2.ItemName].CoarseResults.AddRange(item2.CoarseResults);
							SCP914Conversions[item2.ItemName].OneToOneResults.AddRange(item2.OneToOneResults);
							SCP914Conversions[item2.ItemName].FineResults.AddRange(item2.FineResults);
							SCP914Conversions[item2.ItemName].VeryFineResults.AddRange(item2.VeryFineResults);
						}
						else
						{
							SCP914Conversions.Add(item2);
						}
					}
					mls.LogInfo((object)("Registed SCP 914 json file successfully: " + item));
				}
				catch (JsonException val3)
				{
					JsonException val4 = val3;
					mls.LogError((object)("Failed to deserialize file: " + item + ". Exception: " + ((Exception)(object)val4).Message));
				}
			}
			harmony.PatchAll(typeof(SCPCBDunGen));
			harmony.PatchAll(typeof(RoundManagerPatch));
			mls.LogInfo((object)"SCP:CB DunGen for Lethal Company [Version 2.3.0] successfully loaded.");
		}

		private IEnumerable<string> DiscoverConfiguredRecipeFiles()
		{
			return from filePath in (from pluginDirectory in Directory.GetDirectories(Paths.PluginPath)
					select Path.Join((ReadOnlySpan<char>)pluginDirectory, (ReadOnlySpan<char>)"badhamknibbs-scp914-recipes")).Where(Directory.Exists).SelectMany(Directory.GetFiles)
				where Path.GetExtension(filePath) == ".json"
				select filePath;
		}
	}
	public class SCP914InputStore : NetworkBehaviour
	{
		public List<GameObject> lContainedItems;

		private void OnTriggerEnter(Collider other)
		{
			if (((NetworkBehaviour)this).NetworkManager.IsServer)
			{
				Debug.Log((object)("SCPCB New thing entered input trigger: " + ((Object)((Component)other).gameObject).name + "."));
				GrabbableObject component = ((Component)other).GetComponent<GrabbableObject>();
				lContainedItems.Add(((Component)other).gameObject);
			}
		}

		private void OnTriggerExit(Collider other)
		{
			if (((NetworkBehaviour)this).NetworkManager.IsServer)
			{
				Debug.Log((object)("SCPCB Thing has left input trigger: " + ((Object)((Component)other).gameObject).name + "."));
				lContainedItems.Remove(((Component)other).gameObject);
			}
		}

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

		protected internal override string __getTypeName()
		{
			return "SCP914InputStore";
		}
	}
	public class SCP914Converter : NetworkBehaviour
	{
		public enum SCP914Setting
		{
			ROUGH,
			COARSE,
			ONETOONE,
			FINE,
			VERYFINE
		}

		public SCP914InputStore InputStore;

		public Collider colliderOutput;

		public InteractTrigger SettingKnobTrigger;

		public GameObject SettingKnobPivot;

		public AudioSource SettingKnobSoundSrc;

		public InteractTrigger ActivateTrigger;

		public AudioSource ActivateAudioSrc;

		public AudioSource RefineAudioSrc;

		public Animator DoorIn;

		public Animator DoorOut;

		private readonly (SCP914Setting, float)[] SCP914SettingRotations = new(SCP914Setting, float)[5]
		{
			(SCP914Setting.ROUGH, 90f),
			(SCP914Setting.COARSE, 45f),
			(SCP914Setting.ONETOONE, 0f),
			(SCP914Setting.FINE, -45f),
			(SCP914Setting.VERYFINE, -90f)
		};

		private Dictionary<Item, List<Item>>[] arItemMappings = new Dictionary<Item, List<Item>>[5]
		{
			new Dictionary<Item, List<Item>>(),
			new Dictionary<Item, List<Item>>(),
			new Dictionary<Item, List<Item>>(),
			new Dictionary<Item, List<Item>>(),
			new Dictionary<Item, List<Item>>()
		};

		private int iCurrentState = 0;

		private bool bActive = false;

		private Transform ScrapTransform;

		private RoundManager roundManager;

		private StartOfRound StartOfRound;

		private EnemyType MaskedType;

		private ManualLogSource mls;

		private void Awake()
		{
			mls = SCPCBDunGen.Instance.mls;
		}

		public void AddConversion(SCP914Setting setting, Item itemInput, List<Item> lItemOutputs)
		{
			Dictionary<Item, List<Item>> dictionary = arItemMappings[(int)setting];
			if (dictionary.TryGetValue(itemInput, out var value))
			{
				value.AddRange(lItemOutputs);
			}
			else
			{
				arItemMappings[(int)setting].Add(itemInput, lItemOutputs);
			}
		}

		private Dictionary<Item, List<Item>> GetItemMapping()
		{
			return arItemMappings[iCurrentState];
		}

		private Vector3 GetRandomNavMeshPositionInCollider(Collider collider)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			Bounds bounds = collider.bounds;
			Vector3 center = ((Bounds)(ref bounds)).center;
			bounds = collider.bounds;
			float x = ((Bounds)(ref bounds)).extents.x;
			bounds = collider.bounds;
			float num = Math.Min(x, ((Bounds)(ref bounds)).extents.z);
			center.x += Random.Range(0f - num, num);
			center.z += Random.Range(0f - num, num);
			ref float y = ref center.y;
			float num2 = y;
			bounds = collider.bounds;
			y = num2 - ((Bounds)(ref bounds)).extents.y / 2f;
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(center, ref val, 10f, -1))
			{
				return ((NavMeshHit)(ref val)).position;
			}
			return center;
		}

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

		[ClientRpc]
		public void TurnStateClientRpc(int iNewState)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			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(301590527u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, iNewState);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 301590527u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					iCurrentState = iNewState;
					Quaternion rotation = SettingKnobPivot.transform.rotation;
					Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles;
					eulerAngles.z = SCP914SettingRotations[iCurrentState].Item2;
					SettingKnobPivot.transform.rotation = Quaternion.Euler(eulerAngles);
					SettingKnobSoundSrc.Play();
				}
			}
		}

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

		[ClientRpc]
		public void ActivateClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3833341719u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3833341719u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					ActivateTrigger.interactable = false;
					SettingKnobTrigger.interactable = false;
					ActivateAudioSrc.Play();
					DoorIn.SetBoolString("open", false);
					DoorOut.SetBoolString("open", false);
				}
			}
		}

		[ClientRpc]
		public void RefineFinishClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4143732333u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4143732333u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					ActivateTrigger.interactable = true;
					SettingKnobTrigger.interactable = true;
					DoorIn.SetBoolString("open", true);
					DoorOut.SetBoolString("open", true);
				}
			}
		}

		[ClientRpc]
		public void SpawnItemsClientRpc(NetworkObjectReference[] arNetworkObjectReferences, int[] arScrapValues, bool bChargeBattery)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: 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_00d3: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: 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_012d: 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_00fd: 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(4044311993u, val, (RpcDelivery)0);
				bool flag = arNetworkObjectReferences != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(arNetworkObjectReferences, default(ForNetworkSerializable));
				}
				bool flag2 = arScrapValues != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(arScrapValues, default(ForPrimitives));
				}
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref bChargeBattery, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4044311993u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			NetworkObject val3 = default(NetworkObject);
			for (int i = 0; i < arNetworkObjectReferences.Length; i++)
			{
				mls.LogInfo((object)$"Item conversion scrap value {i}: {arScrapValues[i]}");
				if (((NetworkObjectReference)(ref arNetworkObjectReferences[i])).TryGet(ref val3, (NetworkManager)null))
				{
					GrabbableObject component = ((Component)val3).GetComponent<GrabbableObject>();
					if (component.itemProperties.isScrap)
					{
						component.SetScrapValue(arScrapValues[i]);
					}
					if (component.itemProperties.requiresBattery)
					{
						component.insertedBattery.charge = (bChargeBattery ? 1f : 0f);
					}
				}
			}
		}

		private IEnumerator ConversionProcess()
		{
			RefineAudioSrc.Play();
			yield return (object)new WaitForSeconds(7f);
			if ((Object)(object)roundManager == (Object)null)
			{
				mls.LogInfo((object)"Getting round manager");
				roundManager = Object.FindObjectOfType<RoundManager>();
				if ((Object)(object)roundManager == (Object)null)
				{
					mls.LogError((object)"Failed to find round manager.");
					yield break;
				}
			}
			if ((Object)(object)ScrapTransform == (Object)null)
			{
				SCP914Converter sCP914Converter = this;
				GameObject obj = GameObject.FindGameObjectWithTag("MapPropsContainer");
				sCP914Converter.ScrapTransform = ((obj != null) ? obj.transform : null);
				if ((Object)(object)ScrapTransform == (Object)null)
				{
					mls.LogError((object)"SCPCB Failed to find props container.");
					yield break;
				}
			}
			List<NetworkObjectReference> lNetworkObjectReferences = new List<NetworkObjectReference>();
			List<int> lScrapValues = new List<int>();
			bool bChargeBatteries = iCurrentState > 1;
			Dictionary<Item, List<Item>> dcCurrentMapping = GetItemMapping();
			mls.LogInfo((object)$"Contained item count: {InputStore.lContainedItems.Count}");
			foreach (GameObject gameObject in InputStore.lContainedItems)
			{
				GrabbableObject grabbable = gameObject.GetComponent<GrabbableObject>();
				if ((Object)(object)grabbable != (Object)null)
				{
					ConvertItem(lNetworkObjectReferences, lScrapValues, dcCurrentMapping, grabbable);
					continue;
				}
				PlayerControllerB playerController = gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)playerController != (Object)null)
				{
					ConvertPlayer(playerController);
				}
			}
			mls.LogInfo((object)"Finished spawning scrap, syncing with clients");
			SpawnItemsClientRpc(lNetworkObjectReferences.ToArray(), lScrapValues.ToArray(), bChargeBatteries);
			InputStore.lContainedItems.Clear();
			yield return (object)new WaitForSeconds(7f);
			RefineFinishClientRpc();
			bActive = false;
		}

		private void ConvertItem(List<NetworkObjectReference> lNetworkObjectReferences, List<int> lScrapValues, Dictionary<Item, List<Item>> dcCurrentMapping, GrabbableObject grabbable)
		{
			//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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_0229: Unknown result type (might be due to invalid IL or missing references)
			if (grabbable.isHeld)
			{
				return;
			}
			mls.LogInfo((object)("Found grabbable item " + ((Object)grabbable.itemProperties).name));
			Vector3 randomNavMeshPositionInCollider = GetRandomNavMeshPositionInCollider(colliderOutput);
			GameObject val = null;
			NetworkObject val2 = null;
			GrabbableObject val3 = null;
			if (dcCurrentMapping.TryGetValue(grabbable.itemProperties, out var value))
			{
				mls.LogInfo((object)"Mapping found");
				Item val4 = value?[roundManager.AnomalyRandom.Next(value.Count)];
				Object.Destroy((Object)(object)((Component)grabbable).gameObject);
				if ((Object)(object)val4 != (Object)null)
				{
					mls.LogInfo((object)"Conversion found");
					val = Object.Instantiate<GameObject>(val4.spawnPrefab, randomNavMeshPositionInCollider, Quaternion.identity, ScrapTransform);
					val2 = val.GetComponent<NetworkObject>();
					val3 = val.GetComponent<GrabbableObject>();
				}
			}
			else
			{
				mls.LogInfo((object)"No conversion, making new item with new scrap value");
				val = Object.Instantiate<GameObject>(grabbable.itemProperties.spawnPrefab, randomNavMeshPositionInCollider, Quaternion.identity, ScrapTransform);
				Object.Destroy((Object)(object)((Component)grabbable).gameObject);
				val2 = val.GetComponent<NetworkObject>();
				val3 = val.GetComponent<GrabbableObject>();
			}
			mls.LogInfo((object)"Preprocessing done");
			if ((Object)(object)val3 == (Object)null)
			{
				mls.LogInfo((object)"Conversion was null, item is intended to be destroyed in process.");
				return;
			}
			Item itemProperties = val3.itemProperties;
			if (itemProperties.isScrap)
			{
				mls.LogInfo((object)"Item is scrap or null, generating a copy with new value");
				GrabbableObject component = val.GetComponent<GrabbableObject>();
				int num = (int)((float)roundManager.AnomalyRandom.Next(itemProperties.minValue, itemProperties.maxValue) * roundManager.scrapValueMultiplier);
				component.SetScrapValue(num);
				mls.LogInfo((object)$"new scrap value: {num}");
				lScrapValues.Add(num);
			}
			else
			{
				mls.LogInfo((object)"Item is not scrap, adding empty scrap value");
				lScrapValues.Add(0);
			}
			val2.Spawn(true);
			lNetworkObjectReferences.Add(NetworkObjectReference.op_Implicit(val2));
		}

		[ClientRpc]
		private void ConvertPlayerTeleportClientRpc(NetworkBehaviourReference netBehaviourRefPlayer, Vector3 vPosition)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00a4: 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_0117: Expected O, but got Unknown
			//IL_0118: 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(3018499267u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref vPosition);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3018499267u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkBehaviour val3 = null;
				((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val3, (NetworkManager)null);
				if ((Object)(object)val3 == (Object)null)
				{
					mls.LogError((object)"Failed to get player controller.");
					return;
				}
				PlayerControllerB val4 = (PlayerControllerB)val3;
				val4.TeleportPlayer(vPosition, false, 0f, false, true);
			}
		}

		[ClientRpc]
		private void ConvertPlayerKillClientRpc(NetworkBehaviourReference netBehaviourRefPlayer)
		{
			//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)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			//IL_010b: 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(1252059581u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1252059581u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkBehaviour val3 = null;
				((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val3, (NetworkManager)null);
				if ((Object)(object)val3 == (Object)null)
				{
					mls.LogError((object)"Failed to get player controller.");
					return;
				}
				PlayerControllerB val4 = (PlayerControllerB)val3;
				val4.KillPlayer(Vector3.zero, true, (CauseOfDeath)6, 0);
			}
		}

		[ClientRpc]
		private void ConvertPlayerAlterHealthClientRpc(NetworkBehaviourReference netBehaviourRefPlayer, int iHealthDelta)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_0120: 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)
			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(527346026u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val2, iHealthDelta);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 527346026u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				NetworkBehaviour val3 = null;
				((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val3, (NetworkManager)null);
				if ((Object)(object)val3 == (Object)null)
				{
					mls.LogError((object)"Failed to get player controller.");
					return;
				}
				PlayerControllerB val4 = (PlayerControllerB)val3;
				val4.DamagePlayer(iHealthDelta, true, true, (CauseOfDeath)8, 0, false, default(Vector3));
			}
		}

		[ClientRpc]
		private void ConvertPlayerRandomSkinClientRpc(NetworkBehaviourReference netBehaviourRefPlayer, int iSuitID)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Expected O, but got Unknown
			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(1669287785u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val2, iSuitID);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1669287785u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			if ((Object)(object)StartOfRound == (Object)null)
			{
				StartOfRound = Object.FindObjectOfType<StartOfRound>();
				if ((Object)(object)StartOfRound == (Object)null)
				{
					mls.LogError((object)"Failed to find StartOfRound.");
					return;
				}
			}
			NetworkBehaviour val3 = null;
			((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val3, (NetworkManager)null);
			if ((Object)(object)val3 == (Object)null)
			{
				mls.LogError((object)"Failed to get player controller.");
				return;
			}
			PlayerControllerB val4 = (PlayerControllerB)val3;
			int num = 0;
			foreach (UnlockableItem unlockable in StartOfRound.unlockablesList.unlockables)
			{
				if ((Object)(object)unlockable.suitMaterial != (Object)null)
				{
					mls.LogInfo((object)$"Found suit at index {num}");
				}
				num++;
			}
			UnlockableItem val5 = StartOfRound.unlockablesList.unlockables[iSuitID];
			if (val5 == null)
			{
				mls.LogError((object)$"Invalid suit ID: {iSuitID}");
				return;
			}
			Material suitMaterial = val5.suitMaterial;
			((Renderer)val4.thisPlayerModel).material = suitMaterial;
			((Renderer)val4.thisPlayerModelLOD1).material = suitMaterial;
			((Renderer)val4.thisPlayerModelLOD2).material = suitMaterial;
			((Renderer)val4.thisPlayerModelArms).material = suitMaterial;
			val4.currentSuitID = iSuitID;
		}

		private void ConvertPlayerRandomSkin(PlayerControllerB playerController)
		{
			//IL_00fb: 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_0103: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)StartOfRound == (Object)null)
			{
				StartOfRound = Object.FindObjectOfType<StartOfRound>();
				if ((Object)(object)StartOfRound == (Object)null)
				{
					mls.LogError((object)"Failed to find StartOfRound.");
					return;
				}
			}
			List<int> list = new List<int>();
			int num = 0;
			foreach (UnlockableItem unlockable in StartOfRound.unlockablesList.unlockables)
			{
				if ((Object)(object)unlockable.suitMaterial != (Object)null && num != playerController.currentSuitID)
				{
					list.Add(num);
				}
				num++;
			}
			int count = list.Count;
			if (count == 0)
			{
				mls.LogError((object)"No suits to swap to found.");
				return;
			}
			int index = roundManager.AnomalyRandom.Next(0, count);
			NetworkBehaviourReference netBehaviourRefPlayer = NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)playerController);
			ConvertPlayerRandomSkinClientRpc(netBehaviourRefPlayer, list[index]);
		}

		private IEnumerator ConvertPlayerMaskedWaitForSpawn(NetworkObjectReference netObjRefMasked, NetworkBehaviourReference netBehaviourRefPlayer)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			NetworkObject netObjMasked = null;
			NetworkBehaviour netBehaviourPlayer = null;
			float fStartTime = Time.realtimeSinceStartup;
			yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - fStartTime > 20f || ((NetworkObjectReference)(ref netObjRefMasked)).TryGet(ref netObjMasked, (NetworkManager)null)));
			yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - fStartTime > 20f || ((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref netBehaviourPlayer, (NetworkManager)null)));
			PlayerControllerB playerController = (PlayerControllerB)netBehaviourPlayer;
			if ((Object)(object)playerController.deadBody == (Object)null)
			{
				yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - fStartTime > 20f || (Object)(object)playerController.deadBody != (Object)null));
			}
			if ((Object)(object)playerController.deadBody != (Object)null)
			{
				playerController.deadBody.DeactivateBody(false);
				if ((Object)(object)netObjMasked != (Object)null)
				{
					MaskedPlayerEnemy maskedPlayerEnemy = ((Component)netObjMasked).GetComponent<MaskedPlayerEnemy>();
					maskedPlayerEnemy.mimickingPlayer = playerController;
					maskedPlayerEnemy.SetSuit(playerController.currentSuitID);
					maskedPlayerEnemy.SetEnemyOutside(false);
					playerController.redirectToEnemy = (EnemyAI)(object)maskedPlayerEnemy;
				}
			}
		}

		[ClientRpc]
		private void ConvertPlayerMaskedClientRpc(NetworkObjectReference netObjRefMasked, NetworkBehaviourReference netBehaviourRefPlayer)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: 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(358260797u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref netObjRefMasked, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 358260797u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			NetworkBehaviour val3 = null;
			((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val3, (NetworkManager)null);
			if ((Object)(object)val3 == (Object)null)
			{
				mls.LogError((object)"Failed to get player controller.");
				return;
			}
			PlayerControllerB val4 = (PlayerControllerB)val3;
			val4.KillPlayer(Vector3.zero, true, (CauseOfDeath)5, 0);
			if ((Object)(object)val4.deadBody != (Object)null)
			{
				val4.deadBody.DeactivateBody(false);
			}
			((MonoBehaviour)this).StartCoroutine(ConvertPlayerMaskedWaitForSpawn(netObjRefMasked, netBehaviourRefPlayer));
		}

		private void ConvertPlayerMasked(NetworkBehaviourReference netBehaviourRefPlayer, Vector3 vMaskedPosition)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: 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_01f0: 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)
			NetworkBehaviour val = null;
			((NetworkBehaviourReference)(ref netBehaviourRefPlayer)).TryGet(ref val, (NetworkManager)null);
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to get player controller.");
				return;
			}
			PlayerControllerB val2 = (PlayerControllerB)val;
			val2.KillPlayer(Vector3.zero, true, (CauseOfDeath)5, 0);
			if ((Object)(object)StartOfRound == (Object)null)
			{
				StartOfRound = Object.FindObjectOfType<StartOfRound>();
				if ((Object)(object)StartOfRound == (Object)null)
				{
					mls.LogError((object)"Failed to find StartOfRound.");
					return;
				}
			}
			if ((Object)(object)MaskedType == (Object)null)
			{
				SelectableLevel val3 = Array.Find(StartOfRound.levels, (SelectableLevel x) => x.PlanetName == "8 Titan");
				if ((Object)(object)val3 == (Object)null)
				{
					mls.LogError((object)"Failed to get Titan level data.");
					return;
				}
				MaskedType = val3.Enemies.Find((SpawnableEnemyWithRarity x) => x.enemyType.enemyName == "Masked")?.enemyType;
				if ((Object)(object)MaskedType == (Object)null)
				{
					mls.LogError((object)"Failed to get masked enemy type.");
					return;
				}
			}
			NetworkObjectReference netObjRefMasked = roundManager.SpawnEnemyGameObject(vMaskedPosition, 0f, -1, MaskedType);
			NetworkObject val4 = default(NetworkObject);
			if (((NetworkObjectReference)(ref netObjRefMasked)).TryGet(ref val4, (NetworkManager)null))
			{
				mls.LogInfo((object)"Got network object for mask enemy");
				MaskedPlayerEnemy component = ((Component)val4).GetComponent<MaskedPlayerEnemy>();
				component.SetSuit(val2.currentSuitID);
				component.mimickingPlayer = val2;
				component.SetEnemyOutside(false);
				val2.redirectToEnemy = (EnemyAI)(object)component;
				if ((Object)(object)val2.deadBody != (Object)null)
				{
					val2.deadBody.DeactivateBody(false);
				}
			}
			ConvertPlayerMaskedClientRpc(netObjRefMasked, netBehaviourRefPlayer);
		}

		private void ConvertPlayer(PlayerControllerB playerController)
		{
			//IL_0020: 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_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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			mls.LogInfo((object)"Player detected, doing player conversion");
			SCP914Setting sCP914Setting = (SCP914Setting)iCurrentState;
			Vector3 randomNavMeshPositionInCollider = GetRandomNavMeshPositionInCollider(colliderOutput);
			NetworkBehaviourReference netBehaviourRefPlayer = NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)playerController);
			ConvertPlayerTeleportClientRpc(netBehaviourRefPlayer, randomNavMeshPositionInCollider);
			switch (sCP914Setting)
			{
			case SCP914Setting.ROUGH:
				ConvertPlayerKillClientRpc(netBehaviourRefPlayer);
				break;
			case SCP914Setting.COARSE:
				ConvertPlayerAlterHealthClientRpc(netBehaviourRefPlayer, 50);
				break;
			case SCP914Setting.ONETOONE:
				ConvertPlayerRandomSkin(playerController);
				break;
			case SCP914Setting.FINE:
				ConvertPlayerAlterHealthClientRpc(netBehaviourRefPlayer, -50);
				break;
			case SCP914Setting.VERYFINE:
				if (!playerController.AllowPlayerDeath())
				{
					mls.LogInfo((object)"Refined player with Very Fine, but player death is prevented. Doing nothing.");
				}
				else
				{
					ConvertPlayerMasked(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)playerController), randomNavMeshPositionInCollider);
				}
				break;
			default:
				mls.LogError((object)"Invalid SCP 914 setting when attempting to convert player.");
				break;
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_SCP914Converter()
		{
			//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
			NetworkManager.__rpc_func_table.Add(2627837757u, new RpcReceiveHandler(__rpc_handler_2627837757));
			NetworkManager.__rpc_func_table.Add(301590527u, new RpcReceiveHandler(__rpc_handler_301590527));
			NetworkManager.__rpc_func_table.Add(1051910848u, new RpcReceiveHandler(__rpc_handler_1051910848));
			NetworkManager.__rpc_func_table.Add(3833341719u, new RpcReceiveHandler(__rpc_handler_3833341719));
			NetworkManager.__rpc_func_table.Add(4143732333u, new RpcReceiveHandler(__rpc_handler_4143732333));
			NetworkManager.__rpc_func_table.Add(4044311993u, new RpcReceiveHandler(__rpc_handler_4044311993));
			NetworkManager.__rpc_func_table.Add(3018499267u, new RpcReceiveHandler(__rpc_handler_3018499267));
			NetworkManager.__rpc_func_table.Add(1252059581u, new RpcReceiveHandler(__rpc_handler_1252059581));
			NetworkManager.__rpc_func_table.Add(527346026u, new RpcReceiveHandler(__rpc_handler_527346026));
			NetworkManager.__rpc_func_table.Add(1669287785u, new RpcReceiveHandler(__rpc_handler_1669287785));
			NetworkManager.__rpc_func_table.Add(358260797u, new RpcReceiveHandler(__rpc_handler_358260797));
		}

		private static void __rpc_handler_2627837757(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;
				((SCP914Converter)(object)target).TurnStateServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_301590527(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 iNewState = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref iNewState);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).TurnStateClientRpc(iNewState);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1051910848(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;
				((SCP914Converter)(object)target).ActivateServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3833341719(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;
				((SCP914Converter)(object)target).ActivateClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4143732333(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;
				((SCP914Converter)(object)target).RefineFinishClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4044311993(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_0074: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				NetworkObjectReference[] arNetworkObjectReferences = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref arNetworkObjectReferences, default(ForNetworkSerializable));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				int[] arScrapValues = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref arScrapValues, default(ForPrimitives));
				}
				bool bChargeBattery = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref bChargeBattery, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).SpawnItemsClientRpc(arNetworkObjectReferences, arScrapValues, bChargeBattery);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3018499267(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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference netBehaviourRefPlayer = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				Vector3 vPosition = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref vPosition);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).ConvertPlayerTeleportClientRpc(netBehaviourRefPlayer, vPosition);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1252059581(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_004f: 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)
			{
				NetworkBehaviourReference netBehaviourRefPlayer = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).ConvertPlayerKillClientRpc(netBehaviourRefPlayer);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_527346026(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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference netBehaviourRefPlayer = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				int iHealthDelta = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref iHealthDelta);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).ConvertPlayerAlterHealthClientRpc(netBehaviourRefPlayer, iHealthDelta);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1669287785(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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference netBehaviourRefPlayer = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				int iSuitID = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref iSuitID);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).ConvertPlayerRandomSkinClientRpc(netBehaviourRefPlayer, iSuitID);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_358260797(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_006e: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkObjectReference netObjRefMasked = default(NetworkObjectReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref netObjRefMasked, default(ForNetworkSerializable));
				NetworkBehaviourReference netBehaviourRefPlayer = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref netBehaviourRefPlayer, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCP914Converter)(object)target).ConvertPlayerMaskedClientRpc(netObjRefMasked, netBehaviourRefPlayer);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "SCP914Converter";
		}
	}
	public class SCPDoorMover : NetworkBehaviour
	{
		public NavMeshObstacle navObstacle;

		public Animator doors;

		public List<AudioClip> doorAudioClips;

		public AudioClip doorAudioClipFast;

		public AudioSource doorSFXSource;

		public InteractTrigger ButtonA;

		public InteractTrigger ButtonB;

		private bool bDoorOpen = false;

		private bool bDoorWaiting = false;

		private List<EnemyAICollisionDetect> EnemiesInCollider = new List<EnemyAICollisionDetect>();

		private void OnTriggerEnter(Collider other)
		{
			if (!((Object)(object)NetworkManager.Singleton == (Object)null) && ((NetworkBehaviour)this).IsServer && ((Component)other).CompareTag("Enemy"))
			{
				EnemyAICollisionDetect component = ((Component)other).GetComponent<EnemyAICollisionDetect>();
				if (!((Object)(object)component == (Object)null))
				{
					SCPCBDunGen.Instance.mls.LogInfo((object)("Enemy entered trigger: " + ((Object)component.mainScript.enemyType).name));
					EnemiesInCollider.Add(component);
				}
			}
		}

		private void OnTriggerExit(Collider other)
		{
			if (!((Object)(object)NetworkManager.Singleton == (Object)null) && ((NetworkBehaviour)this).IsServer && ((Component)other).CompareTag("Enemy"))
			{
				EnemyAICollisionDetect component = ((Component)other).GetComponent<EnemyAICollisionDetect>();
				if (!((Object)(object)component == (Object)null) && !EnemiesInCollider.Remove(component))
				{
					SCPCBDunGen.Instance.mls.LogWarning((object)"Enemy left door trigger but somehow wasn't detected in trigger entry.");
				}
			}
		}

		private void Update()
		{
			if ((Object)(object)NetworkManager.Singleton == (Object)null || !((NetworkBehaviour)this).IsServer || bDoorOpen || bDoorWaiting || EnemiesInCollider.Count == 0)
			{
				return;
			}
			SCPCBDunGen.Instance.mls.LogInfo((object)"Enemy attempting to open door...");
			float num = 0f;
			foreach (EnemyAICollisionDetect item in EnemiesInCollider)
			{
				EnemyAI mainScript = item.mainScript;
				if (!mainScript.isEnemyDead)
				{
					SCPCBDunGen.Instance.mls.LogInfo((object)$"Enemy {((Object)mainScript.enemyType).name} with open mult {mainScript.openDoorSpeedMultiplier}");
					float val = mainScript.openDoorSpeedMultiplier;
					if (((Object)mainScript.enemyType).name == "MaskedPlayerEnemy")
					{
						val = 1f;
					}
					if (((Object)mainScript.enemyType).name == "Crawler")
					{
						val = 2f;
					}
					num = Math.Max(num, val);
				}
			}
			SCPCBDunGen.Instance.mls.LogInfo((object)$"Highest multiplier is {num}.");
			if (num != 0f)
			{
				SCPCBDunGen.Instance.mls.LogInfo((object)"Door being opened.");
				if (num > 1.5f)
				{
					OpenDoorFastServerRpc();
				}
				else
				{
					ToggleDoorServerRpc();
				}
			}
		}

		[ServerRpc]
		public void OpenDoorFastServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(289563691u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 289563691u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				SCPCBDunGen.Instance.mls.LogInfo((object)"Opening door fast [SERVER].");
				bDoorWaiting = true;
				bDoorOpen = true;
				((Behaviour)navObstacle).enabled = false;
				OpenDoorFastClientRpc();
				((MonoBehaviour)this).StartCoroutine(DoorToggleButtonUsable());
			}
		}

		[ClientRpc]
		public void OpenDoorFastClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1678254293u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1678254293u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					SCPCBDunGen.Instance.mls.LogInfo((object)"Opening door fast [CLIENT].");
					bDoorWaiting = true;
					bDoorOpen = true;
					ButtonA.interactable = false;
					ButtonB.interactable = false;
					doorSFXSource.PlayOneShot(doorAudioClipFast);
					doors.SetTrigger("openfast");
				}
			}
		}

		private IEnumerator DoorToggleButtonUsable()
		{
			yield return (object)new WaitForSeconds(1f);
			bDoorWaiting = false;
			yield return (object)new WaitForSeconds(1f);
			EnableDoorButtonClientRpc();
		}

		[ServerRpc(RequireOwnership = false)]
		public void ToggleDoorServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(40313670u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 40313670u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && !bDoorWaiting)
				{
					bool flag = !bDoorOpen;
					string text = (flag ? "opening" : "closing");
					SCPCBDunGen.Instance.mls.LogInfo((object)("Door is " + text + "."));
					bDoorWaiting = true;
					bDoorOpen = flag;
					((Behaviour)navObstacle).enabled = !flag;
					ToggleDoorClientRpc(bDoorOpen);
					((MonoBehaviour)this).StartCoroutine(DoorToggleButtonUsable());
				}
			}
		}

		[ClientRpc]
		public void ToggleDoorClientRpc(bool _bDoorOpen)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(659555206u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref _bDoorOpen, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 659555206u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					bDoorOpen = _bDoorOpen;
					ButtonA.interactable = false;
					ButtonB.interactable = false;
					doorSFXSource.PlayOneShot(doorAudioClips[Random.Range(0, doorAudioClips.Count)]);
					doors.SetTrigger(bDoorOpen ? "open" : "close");
				}
			}
		}

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

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_SCPDoorMover()
		{
			//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
			NetworkManager.__rpc_func_table.Add(289563691u, new RpcReceiveHandler(__rpc_handler_289563691));
			NetworkManager.__rpc_func_table.Add(1678254293u, new RpcReceiveHandler(__rpc_handler_1678254293));
			NetworkManager.__rpc_func_table.Add(40313670u, new RpcReceiveHandler(__rpc_handler_40313670));
			NetworkManager.__rpc_func_table.Add(659555206u, new RpcReceiveHandler(__rpc_handler_659555206));
			NetworkManager.__rpc_func_table.Add(1538705838u, new RpcReceiveHandler(__rpc_handler_1538705838));
		}

		private static void __rpc_handler_289563691(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;
				((SCPDoorMover)(object)target).OpenDoorFastServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1678254293(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;
				((SCPDoorMover)(object)target).OpenDoorFastClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_40313670(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;
				((SCPDoorMover)(object)target).ToggleDoorServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_659555206(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 flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SCPDoorMover)(object)target).ToggleDoorClientRpc(flag);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1538705838(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;
				((SCPDoorMover)(object)target).EnableDoorButtonClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "SCPDoorMover";
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "SCPCBDunGen";

		public const string PLUGIN_NAME = "SCPCBDunGen";

		public const string PLUGIN_VERSION = "2.3.0";
	}
}

plugins/SecretLabs.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SecretLabs.Patches;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SecretLabs")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("SecretLabs")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SecretLabs")]
[assembly: AssemblyTitle("SecretLabs")]
[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 SecretLabs
{
	[Serializable]
	public class Config : SyncedInstance<Config>
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequestSync;

			public static HandleNamedMessageDelegate <1>__OnReceiveSync;
		}

		public bool customPriceEnabled;

		public int moonPrice;

		public Config(ConfigFile cfg)
		{
			InitInstance(this);
			customPriceEnabled = cfg.Bind<bool>("General", "CustomPriceEnabled", false, "Enable this if you wish to configure the moons route price below.").Value;
			moonPrice = cfg.Bind<int>("General", "MoonPrice", 700, "The route price of the Secret Labs moon.").Value;
		}

		public static void RequestSync()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<Config>.MessageManager.SendNamedMessage("SecretLabs_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsHost)
			{
				return;
			}
			byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<Config>.MessageManager.SendNamedMessage("SecretLabs_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogDebug((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
			{
				Plugin.Logger.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				Plugin.Logger.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<Config>.SyncInstance(data);
			Plugin.Logger.LogDebug((object)"Successfully synced config with host.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		public static void InitializeLocalPlayer()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (SyncedInstance<Config>.IsHost)
			{
				CustomMessagingManager messageManager = SyncedInstance<Config>.MessageManager;
				object obj = <>O.<0>__OnRequestSync;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequestSync;
					<>O.<0>__OnRequestSync = val;
					obj = (object)val;
				}
				messageManager.RegisterNamedMessageHandler("SecretLabs_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
				SyncedInstance<Config>.Synced = true;
				return;
			}
			SyncedInstance<Config>.Synced = false;
			CustomMessagingManager messageManager2 = SyncedInstance<Config>.MessageManager;
			object obj2 = <>O.<1>__OnReceiveSync;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = OnReceiveSync;
				<>O.<1>__OnReceiveSync = val2;
				obj2 = (object)val2;
			}
			messageManager2.RegisterNamedMessageHandler("SecretLabs_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
			RequestSync();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<Config>.RevertSync();
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; set; }

		public static T Instance { get; set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	[BepInPlugin("SecretLabs", "SecretLabs", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static ManualLogSource Logger;

		public static Config Config { get; internal set; }

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("SecretLabs");
			Config = new Config(((BaseUnityPlugin)this).Config);
			_harmony.PatchAll(typeof(RoutePatches));
			_harmony.PatchAll(typeof(Config));
			Logger.LogDebug((object)"Plugin SecretLabs is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "SecretLabs";

		public const string PLUGIN_NAME = "SecretLabs";

		public const string PLUGIN_VERSION = "1.0.0";
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "SecretLabs";

		public const string PLUGIN_NAME = "SecretLabs";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace SecretLabs.Patches
{
	[HarmonyPatch(typeof(Terminal))]
	public class RoutePatches
	{
		[HarmonyPatch("LoadNewNode")]
		[HarmonyPrefix]
		private static void LoadNewNodePatchBefore(ref TerminalNode node)
		{
			if (!SyncedInstance<Config>.Instance.customPriceEnabled)
			{
				return;
			}
			Terminal obj = Object.FindObjectOfType<Terminal>();
			Plugin.Logger.LogDebug((object)((Object)node).name);
			CompatibleNoun[] compatibleNouns = obj.terminalNodes.allKeywords.First((TerminalKeyword terminalKeyword) => terminalKeyword.word == "route").compatibleNouns;
			foreach (CompatibleNoun val in compatibleNouns)
			{
				if (!((Object)(object)val.result == (Object)null) && ((Object)val.result).name == "secret labsRoute")
				{
					val.result.itemCost = SyncedInstance<Config>.Instance.moonPrice;
				}
			}
		}

		[HarmonyPatch("LoadNewNodeIfAffordable")]
		[HarmonyPrefix]
		private static void LoadNewNodeIfAffordablePatch(ref TerminalNode node)
		{
			if (SyncedInstance<Config>.Instance.customPriceEnabled)
			{
				Plugin.Logger.LogDebug((object)((Object)node).name);
				if (!((Object)(object)node == (Object)null) && !(((Object)node).name != "secret labsRouteConfirm"))
				{
					node.itemCost = Math.Abs(SyncedInstance<Config>.Instance.moonPrice);
				}
			}
		}
	}
}