Decompiled source of Pizzas Backrooms v1.5.2

BepInEx/patchers/BackroomsDunGenFix/BackroomsDunGenFix.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
public static class BackroomsDunGenFixPatcher
{
	private static readonly ManualLogSource Log = Logger.CreateLogSource("BackroomsDunGenFix");

	public static IEnumerable<string> TargetDLLs => new string[1] { "Assembly-CSharp.dll" };

	public static void Initialize()
	{
		string[] files = Directory.GetFiles(Paths.PluginPath, "*.dll", SearchOption.AllDirectories);
		foreach (string text in files)
		{
			try
			{
				string text2 = LegacyModRewriter.RewriteFile(text, Paths.ManagedPath, Paths.BepInExAssemblyDirectory);
				if (text2 != null)
				{
					Log.LogInfo((object)("Rewrote " + text2));
				}
			}
			catch (BadImageFormatException)
			{
			}
			catch (Exception ex2)
			{
				Log.LogError((object)("Failed to rewrite " + text + ": " + ex2));
			}
		}
	}

	public static void Patch(AssemblyDefinition assembly)
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: 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_0177: 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)
		ModuleDefinition mainModule = assembly.MainModule;
		string text = Path.Combine(Paths.ManagedPath, "DunGen.dll");
		if (!File.Exists(text))
		{
			Log.LogInfo((object)"DunGen.dll not found in Managed folder - game is an older build, nothing to do.");
			return;
		}
		AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text);
		try
		{
			HashSet<string> hashSet = new HashSet<string>();
			Enumerator<TypeDefinition> enumerator = mainModule.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					hashSet.Add(((MemberReference)current).FullName);
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			Enumerator<ExportedType> enumerator2 = mainModule.ExportedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ExportedType current2 = enumerator2.Current;
					hashSet.Add(current2.FullName);
				}
			}
			finally
			{
				((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
			}
			AssemblyNameReference val2 = null;
			Enumerator<AssemblyNameReference> enumerator3 = mainModule.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					AssemblyNameReference current3 = enumerator3.Current;
					if (current3.Name == ((AssemblyNameReference)val.Name).Name)
					{
						val2 = current3;
						break;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
			}
			if (val2 == null)
			{
				val2 = AssemblyNameReference.Parse(((AssemblyNameReference)val.Name).FullName);
				mainModule.AssemblyReferences.Add(val2);
			}
			int count = 0;
			enumerator = val.MainModule.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if (current.IsPublic && !hashSet.Contains(((MemberReference)current).FullName))
					{
						AddForwarder(mainModule, current, (IMetadataScope)(object)val2, null, ref count);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			Log.LogInfo((object)("Forwarded " + count + " DunGen types from Assembly-CSharp to " + ((AssemblyNameReference)val.Name).Name + ".dll"));
		}
		finally
		{
			val.Dispose();
		}
	}

	private static void AddForwarder(ModuleDefinition module, TypeDefinition type, IMetadataScope scope, ExportedType parent, ref int count)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//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)
		ExportedType val = new ExportedType((parent == null) ? ((TypeReference)type).Namespace : string.Empty, ((MemberReference)type).Name, module, scope);
		if (parent == null)
		{
			val.IsForwarder = true;
		}
		else
		{
			val.DeclaringType = parent;
		}
		module.ExportedTypes.Add(val);
		count++;
		Enumerator<TypeDefinition> enumerator = type.NestedTypes.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				TypeDefinition current = enumerator.Current;
				if (current.IsNestedPublic)
				{
					AddForwarder(module, current, scope, val, ref count);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
	}
}
public static class LegacyModRewriter
{
	private class Context
	{
		public readonly ModuleDefinition Module;

		public readonly TypeDefinition Player;

		public readonly TypeDefinition Ragdoll;

		public readonly TypeDefinition Vector3;

		public readonly TypeDefinition NetworkBehaviour;

		public Context(ModuleDefinition module, IAssemblyResolver resolver)
		{
			Module = module;
			ModuleDefinition mainModule = resolver.Resolve(AssemblyNameReference.Parse("Assembly-CSharp")).MainModule;
			Player = mainModule.GetType("GameNetcodeStuff.PlayerControllerB");
			Ragdoll = mainModule.GetType("RagdollGrabbableObject");
			Vector3 = resolver.Resolve(AssemblyNameReference.Parse("UnityEngine.CoreModule")).MainModule.GetType("UnityEngine.Vector3");
			NetworkBehaviour = resolver.Resolve(AssemblyNameReference.Parse("Unity.Netcode.Runtime")).MainModule.GetType("Unity.Netcode.NetworkBehaviour");
		}

		public MethodReference PlayerMethod(string name, int paramCount)
		{
			//IL_000d: 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)
			Enumerator<MethodDefinition> enumerator = Player.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name && ((MethodReference)current).Parameters.Count == paramCount)
					{
						return Module.ImportReference((MethodReference)(object)current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			throw new MissingMethodException("PlayerControllerB", name + "/" + paramCount);
		}

		public MethodReference Import(TypeDefinition type, string name)
		{
			//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)
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return Module.ImportReference((MethodReference)(object)current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			throw new MissingMethodException(((MemberReference)type).FullName, name);
		}
	}

	public const string MarkerResource = "BackroomsDunGenFix.Rewritten.v1";

	public static readonly string[] TargetAssemblies = new string[3] { "Backrooms", "RealBackroomsPatch", "TestAccount666.RealBackroomsPatch" };

	public static string RewriteFile(string path, string managedDir, string coreDir)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bc: Expected O, but got Unknown
		DefaultAssemblyResolver val = new DefaultAssemblyResolver();
		((BaseAssemblyResolver)val).AddSearchDirectory(managedDir);
		((BaseAssemblyResolver)val).AddSearchDirectory(coreDir);
		((BaseAssemblyResolver)val).AddSearchDirectory(Path.GetDirectoryName(path));
		byte[] array = File.ReadAllBytes(path);
		MemoryStream memoryStream = new MemoryStream(array);
		ReaderParameters val2 = new ReaderParameters();
		val2.AssemblyResolver = (IAssemblyResolver)(object)val;
		AssemblyDefinition val3 = AssemblyDefinition.ReadAssembly((Stream)memoryStream, val2);
		try
		{
			if (Array.IndexOf(TargetAssemblies, ((AssemblyNameReference)val3.Name).Name) < 0)
			{
				return null;
			}
			ModuleDefinition mainModule = val3.MainModule;
			Enumerator<Resource> enumerator = mainModule.Resources.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Resource current = enumerator.Current;
					if (current.Name == "BackroomsDunGenFix.Rewritten.v1")
					{
						return null;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			Context ctx = new Context(mainModule, (IAssemblyResolver)(object)val);
			List<string> list = new List<string>();
			foreach (TypeDefinition type in mainModule.GetTypes())
			{
				Enumerator<MethodDefinition> enumerator3 = type.Methods.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						MethodDefinition current3 = enumerator3.Current;
						if (current3.HasBody)
						{
							int num = RewriteBody(ctx, current3);
							if (num > 0)
							{
								list.Add(((MemberReference)type).Name + "." + ((MemberReference)current3).Name + " (" + num + ")");
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
				}
			}
			foreach (TypeDefinition type2 in mainModule.GetTypes())
			{
				int num = ConvertLegacyRpcs(ctx, type2);
				if (num > 0)
				{
					list.Add(((MemberReference)type2).Name + ": " + num + " RPCs re-registered");
				}
			}
			if (list.Count == 0)
			{
				return null;
			}
			mainModule.Resources.Add((Resource)new EmbeddedResource("BackroomsDunGenFix.Rewritten.v1", (ManifestResourceAttributes)2, new byte[1] { 1 }));
			MemoryStream memoryStream2 = new MemoryStream();
			val3.Write((Stream)memoryStream2);
			string path2 = path + ".orig";
			if (!File.Exists(path2))
			{
				File.WriteAllBytes(path2, array);
			}
			File.WriteAllBytes(path, memoryStream2.ToArray());
			return ((AssemblyNameReference)val3.Name).Name + ": " + string.Join(", ", list.ToArray());
		}
		finally
		{
			val3.Dispose();
		}
	}

	private static int RewriteBody(Context ctx, MethodDefinition method)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0327: 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_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Expected O, but got Unknown
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0366: Expected O, but got Unknown
		//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cf: 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_015f: 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_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a9: Expected O, but got Unknown
		//IL_02ce: 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_02ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_048d: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0506: Unknown result type (might be due to invalid IL or missing references)
		MethodBody body = method.Body;
		ILProcessor iLProcessor = body.GetILProcessor();
		MethodBodyRocks.SimplifyMacros(body);
		int num = 0;
		List<Instruction> list = new List<Instruction>((IEnumerable<Instruction>)body.Instructions);
		for (int i = 0; i < list.Count; i++)
		{
			Instruction val = list[i];
			if ((val.OpCode == OpCodes.Call || val.OpCode == OpCodes.Callvirt) && val.Operand is MethodReference)
			{
				MethodReference val2 = (MethodReference)val.Operand;
				if (!(((MemberReference)((MemberReference)val2).DeclaringType).FullName != "GameNetcodeStuff.PlayerControllerB"))
				{
					int count = val2.Parameters.Count;
					OpCode opCode = val.OpCode;
					if (((MemberReference)val2).Name == "DropAllHeldItemsAndSync" && count == 0)
					{
						val.Operand = ctx.PlayerMethod("DropAllHeldItemsAndSyncNonexact", 0);
						num++;
					}
					else if (((MemberReference)val2).Name == "KillPlayer" && count == 4)
					{
						Rewrite(iLProcessor, val, (Instruction[])(object)new Instruction[3]
						{
							iLProcessor.Create(OpCodes.Call, ctx.Import(ctx.Vector3, "get_zero")),
							iLProcessor.Create(OpCodes.Ldc_I4_0),
							iLProcessor.Create(opCode, ctx.PlayerMethod("KillPlayer", 6))
						});
						num++;
					}
					else if (((MemberReference)val2).Name == "KillPlayer" && count == 5)
					{
						Rewrite(iLProcessor, val, (Instruction[])(object)new Instruction[2]
						{
							iLProcessor.Create(OpCodes.Ldc_I4_0),
							iLProcessor.Create(opCode, ctx.PlayerMethod("KillPlayer", 6))
						});
						num++;
					}
					else if (((MemberReference)val2).Name == "HasLineOfSightToPosition" && count == 4)
					{
						Rewrite(iLProcessor, val, (Instruction[])(object)new Instruction[2]
						{
							iLProcessor.Create(OpCodes.Ldc_I4_M1),
							iLProcessor.Create(opCode, ctx.PlayerMethod("HasLineOfSightToPosition", 5))
						});
						num++;
					}
					else if (((MemberReference)val2).Name == "SpawnDeadBody" && count == 7)
					{
						VariableDefinition val3 = new VariableDefinition(ctx.Module.ImportReference((TypeReference)(object)ctx.Vector3));
						body.Variables.Add(val3);
						body.InitLocals = true;
						Rewrite(iLProcessor, val, (Instruction[])(object)new Instruction[4]
						{
							iLProcessor.Create(OpCodes.Stloc, val3),
							iLProcessor.Create(OpCodes.Ldnull),
							iLProcessor.Create(OpCodes.Ldloc, val3),
							iLProcessor.Create(opCode, ctx.PlayerMethod("SpawnDeadBody", 8))
						});
						num++;
					}
				}
			}
			else
			{
				if (!(val.OpCode == OpCodes.Ldfld) || !(val.Operand is FieldReference))
				{
					continue;
				}
				FieldReference val4 = (FieldReference)val.Operand;
				if (((MemberReference)val4).Name != "bodyID" || ((MemberReference)((MemberReference)val4).DeclaringType).FullName != "RagdollGrabbableObject" || !(val4.FieldType is GenericInstanceType))
				{
					continue;
				}
				FieldReference operand = null;
				Enumerator<FieldDefinition> enumerator = ctx.Ragdoll.Fields.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						FieldDefinition current = enumerator.Current;
						if (((MemberReference)current).Name == "bodyID")
						{
							operand = ctx.Module.ImportReference((FieldReference)(object)current);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				for (int j = i + 1; j < list.Count && j <= i + 12; j++)
				{
					object operand2 = list[j].Operand;
					MethodReference val5 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
					if (val5 != null && !(((MemberReference)((MemberReference)val5).DeclaringType).Name != "NetworkVariable`1"))
					{
						if (((MemberReference)val5).Name == "set_Value")
						{
							val.OpCode = OpCodes.Nop;
							val.Operand = null;
							list[j].OpCode = OpCodes.Stfld;
							list[j].Operand = operand;
							num++;
						}
						else if (((MemberReference)val5).Name == "get_Value" && j == i + 1)
						{
							val.Operand = operand;
							list[j].OpCode = OpCodes.Nop;
							list[j].Operand = null;
							num++;
						}
						break;
					}
				}
			}
		}
		MethodBodyRocks.OptimizeMacros(body);
		return num;
	}

	private static void Rewrite(ILProcessor il, Instruction ins, Instruction[] replacement)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		ins.OpCode = replacement[0].OpCode;
		ins.Operand = replacement[0].Operand;
		Instruction val = ins;
		for (int i = 1; i < replacement.Length; i++)
		{
			il.InsertAfter(val, replacement[i]);
			val = replacement[i];
		}
	}

	private static int ConvertLegacyRpcs(Context ctx, TypeDefinition type)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_0215: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b1: Expected O, but got Unknown
		//IL_0164: 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_02d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0307: Unknown result type (might be due to invalid IL or missing references)
		//IL_031b: Unknown result type (might be due to invalid IL or missing references)
		//IL_032a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0343: Unknown result type (might be due to invalid IL or missing references)
		//IL_0375: Unknown result type (might be due to invalid IL or missing references)
		//IL_0382: Unknown result type (might be due to invalid IL or missing references)
		//IL_0391: Unknown result type (might be due to invalid IL or missing references)
		if (type.BaseType == null)
		{
			return 0;
		}
		Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				MethodDefinition current = enumerator.Current;
				if (((MemberReference)current).Name == "__initializeRpcs")
				{
					return 0;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		List<KeyValuePair<uint, MethodDefinition>> list = new List<KeyValuePair<uint, MethodDefinition>>();
		enumerator = type.Methods.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				MethodDefinition current = enumerator.Current;
				if (!current.IsStatic || !current.HasBody)
				{
					continue;
				}
				Collection<Instruction> instructions = current.Body.Instructions;
				for (int i = 0; i + 3 < instructions.Count; i++)
				{
					object operand = instructions[i].Operand;
					FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null);
					if (!(instructions[i].OpCode != OpCodes.Ldsfld) && val != null && !(((MemberReference)val).Name != "__rpc_func_table") && !(((MemberReference)((MemberReference)val).DeclaringType).Name != "NetworkManager"))
					{
						int? num = ConstInt(instructions[i + 1]);
						object operand2 = instructions[i + 3].Operand;
						MethodReference val2 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
						if (num.HasValue && !(instructions[i + 3].OpCode != OpCodes.Ldftn) && val2 != null)
						{
							list.Add(new KeyValuePair<uint, MethodDefinition>((uint)num.Value, val2.Resolve()));
						}
					}
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		if (list.Count == 0)
		{
			return 0;
		}
		ModuleDefinition module = ctx.Module;
		TypeDefinition type2 = null;
		Enumerator<TypeDefinition> enumerator2 = ctx.NetworkBehaviour.NestedTypes.GetEnumerator();
		try
		{
			while (enumerator2.MoveNext())
			{
				TypeDefinition current2 = enumerator2.Current;
				if (((MemberReference)current2).Name == "RpcReceiveHandler")
				{
					type2 = current2;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
		}
		MethodReference val3 = ctx.Import(type2, ".ctor");
		MethodReference val4 = ctx.Import(ctx.NetworkBehaviour, "__registerRpc");
		MethodReference val5 = ctx.Import(ctx.NetworkBehaviour, "__initializeRpcs");
		MethodDefinition val6 = new MethodDefinition("__initializeRpcs", (MethodAttributes)196, module.TypeSystem.Void);
		ILProcessor iLProcessor = val6.Body.GetILProcessor();
		foreach (KeyValuePair<uint, MethodDefinition> item in list)
		{
			iLProcessor.Emit(OpCodes.Ldarg_0);
			iLProcessor.Emit(OpCodes.Ldc_I4, (int)item.Key);
			iLProcessor.Emit(OpCodes.Ldnull);
			iLProcessor.Emit(OpCodes.Ldftn, (MethodReference)(object)item.Value);
			iLProcessor.Emit(OpCodes.Newobj, val3);
			iLProcessor.Emit(OpCodes.Ldstr, ((MemberReference)item.Value).Name);
			iLProcessor.Emit(OpCodes.Call, val4);
		}
		iLProcessor.Emit(OpCodes.Ldarg_0);
		iLProcessor.Emit(OpCodes.Call, val5);
		iLProcessor.Emit(OpCodes.Ret);
		type.Methods.Add(val6);
		return list.Count;
	}

	private static int? ConstInt(Instruction ins)
	{
		//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_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)
		if (ins.OpCode == OpCodes.Ldc_I4)
		{
			return (int)ins.Operand;
		}
		if (ins.OpCode == OpCodes.Ldc_I4_S)
		{
			return (sbyte)ins.Operand;
		}
		return null;
	}
}

BepInEx/plugins/BackroomsExitBeacon/BackroomsExitBeacon.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("private.BackroomsExitBeacon", "Pizza's Backrooms", "1.3.2")]
public class BackroomsExitBeacon : BaseUnityPlugin
{
	private void Awake()
	{
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Expected O, but got Unknown
		BeaconRunner.Logger = ((BaseUnityPlugin)this).Logger;
		BeaconRunner.interval = ((BaseUnityPlugin)this).Config.Bind<float>("Beacon", "Interval seconds", 180f, "How often the exit is revealed while you are in the Backrooms.");
		BeaconRunner.duration = ((BaseUnityPlugin)this).Config.Bind<float>("Beacon", "Duration seconds", 6f, "How long the exit marker stays on screen each time.");
		BeaconRunner.showTip = ((BaseUnityPlugin)this).Config.Bind<bool>("Beacon", "Show tip popup", true, "Also show a HUD tip when the exit is revealed.");
		GameObject val = new GameObject("BackroomsExitBeacon");
		((Object)val).hideFlags = (HideFlags)61;
		Object.DontDestroyOnLoad((Object)(object)val);
		BeaconRunner.Instance = val.AddComponent<BeaconRunner>();
		MaskedToBackrooms.Init(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
		MaskDropOnBackrooms.Init(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
		BackroomsWalkie.Init(val, ((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Pizza's Backrooms loaded (every " + BeaconRunner.interval.Value + "s for " + BeaconRunner.duration.Value + "s)"));
	}
}
public class BeaconRunner : MonoBehaviour
{
	public static BeaconRunner Instance;

	public static ManualLogSource Logger;

	public static ConfigEntry<float> interval;

	public static ConfigEntry<float> duration;

	public static ConfigEntry<bool> showTip;

	private Type backroomsType;

	private Type exitType;

	private FieldInfo instanceField;

	private FieldInfo widthField;

	private FieldInfo heightField;

	private FieldInfo offsetField;

	private float insideSince = -1f;

	private float nextReveal;

	private float revealUntil;

	private Transform exit;

	private GUIStyle style;

	private GUIStyle shadow;

	private bool wasInside;

	private bool ResolveTypes()
	{
		if (backroomsType != null)
		{
			return true;
		}
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			if (!(assembly.GetName().Name != "Backrooms"))
			{
				backroomsType = assembly.GetType("Backrooms.Backrooms");
				exitType = assembly.GetType("Backrooms.Exit");
			}
		}
		if (backroomsType == null || exitType == null)
		{
			backroomsType = null;
			return false;
		}
		instanceField = backroomsType.GetField("Instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		widthField = backroomsType.GetField("Width", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		heightField = backroomsType.GetField("Height", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		offsetField = backroomsType.GetField("Offset", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		Logger.LogInfo((object)("Found Backrooms types (Instance=" + (instanceField != null) + ", Offset=" + (offsetField != null) + ")"));
		return instanceField != null;
	}

	private static PlayerControllerB LocalPlayer()
	{
		if ((Object)(object)GameNetworkManager.Instance == (Object)null)
		{
			return null;
		}
		return GameNetworkManager.Instance.localPlayerController;
	}

	public bool IsInsideBackrooms(PlayerControllerB player)
	{
		//IL_0076: 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)
		if ((Object)(object)player == (Object)null || !ResolveTypes())
		{
			return false;
		}
		float num = ((offsetField != null) ? Convert.ToSingle(offsetField.GetValue(null)) : float.NaN);
		if (float.IsNaN(num))
		{
			object? value = instanceField.GetValue(null);
			Component val = (Component)((value is Component) ? value : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			num = val.transform.position.y;
		}
		return Mathf.Abs(((Component)player).transform.position.y - num) <= 12f;
	}

	private void Update()
	{
		PlayerControllerB player = LocalPlayer();
		bool flag = IsInsideBackrooms(player);
		if (flag != wasInside)
		{
			wasInside = flag;
			Logger.LogInfo((object)(flag ? "Entered the Backrooms" : "Left the Backrooms"));
		}
		if (!flag)
		{
			insideSince = -1f;
			revealUntil = 0f;
			return;
		}
		if (insideSince < 0f)
		{
			insideSince = Time.time;
			nextReveal = Time.time + interval.Value;
		}
		if (Time.time >= nextReveal)
		{
			Reveal(player);
			nextReveal = Time.time + interval.Value;
		}
	}

	private void Reveal(PlayerControllerB player)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		exit = null;
		float num = float.MaxValue;
		Object[] array = Object.FindObjectsOfType(exitType);
		foreach (Object val in array)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if (!((Object)(object)val2 == (Object)null))
			{
				float num2 = Vector3.Distance(val2.transform.position, ((Component)player).transform.position);
				if (num2 < num)
				{
					num = num2;
					exit = val2.transform;
				}
			}
		}
		if ((Object)(object)exit == (Object)null)
		{
			Logger.LogWarning((object)"Could not find the Backrooms exit");
			return;
		}
		Logger.LogInfo((object)string.Concat("Revealing exit at ", exit.position, " (", Mathf.RoundToInt(num), "m away)"));
		revealUntil = Time.time + duration.Value;
		if (showTip.Value && (Object)(object)HUDManager.Instance != (Object)null)
		{
			HUDManager.Instance.DisplayTip("Backrooms", "The exit is marked on your screen!", false, false, "LC_Tip1");
		}
	}

	private void OnGUI()
	{
		//IL_00a0: 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_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: 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_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Expected O, but got Unknown
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: 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_030d: 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)
		if ((Object)(object)exit == (Object)null || Time.time > revealUntil)
		{
			return;
		}
		PlayerControllerB val = LocalPlayer();
		if (!((Object)(object)val == (Object)null) && !((Object)(object)val.gameplayCamera == (Object)null))
		{
			if (style == null)
			{
				style = new GUIStyle(GUI.skin.label);
				style.fontSize = Mathf.Max(18, Screen.height / 30);
				style.fontStyle = (FontStyle)1;
				style.alignment = (TextAnchor)4;
				shadow = new GUIStyle(style);
			}
			Vector3 val2 = exit.position + Vector3.up * 1.5f;
			Vector3 val3 = val.gameplayCamera.WorldToViewportPoint(val2);
			bool flag = val3.z < 0f;
			if (flag)
			{
				val3.x = 1f - val3.x;
				val3.y = 1f - val3.y;
			}
			bool flag2 = flag || val3.x < 0.05f || val3.x > 0.95f || val3.y < 0.08f || val3.y > 0.92f;
			if (flag)
			{
				val3.y = 0.15f;
			}
			val3.x = Mathf.Clamp(val3.x, 0.05f, 0.95f);
			val3.y = Mathf.Clamp(val3.y, 0.08f, 0.92f);
			int num = Mathf.RoundToInt(Vector3.Distance(((Component)val).transform.position, exit.position));
			string text = "";
			if (flag2)
			{
				text = ((val3.x <= 0.06f) ? "<< " : ((val3.x >= 0.94f) ? ">> " : (flag ? "(behind) " : "")));
			}
			string text2 = text + "EXIT\n" + num + "m";
			float num2 = 0.65f + 0.35f * Mathf.Sin(Time.time * 6f);
			float num3 = val3.x * (float)Screen.width;
			float num4 = (1f - val3.y) * (float)Screen.height;
			Rect val4 = default(Rect);
			((Rect)(ref val4))..ctor(num3 - 150f, num4 - 50f, 300f, 100f);
			shadow.normal.textColor = new Color(0f, 0f, 0f, 0.8f * num2);
			GUI.Label(new Rect(((Rect)(ref val4)).x + 2f, ((Rect)(ref val4)).y + 2f, ((Rect)(ref val4)).width, ((Rect)(ref val4)).height), text2, shadow);
			style.normal.textColor = new Color(1f, 0.85f, 0.1f, num2);
			GUI.Label(val4, text2, style);
		}
	}
}
public class BackroomsWalkie : MonoBehaviour
{
	private const string MessageName = "BackroomsExitBeacon.WalkieStatic";

	public static BackroomsWalkie Instance;

	private static ManualLogSource Log;

	private static ConfigEntry<bool> enabledCfg;

	private static ConfigEntry<float> volumeCfg;

	private readonly HashSet<int> transmitting = new HashSet<int>();

	private readonly Dictionary<WalkieTalkie, AudioSource> staticSources = new Dictionary<WalkieTalkie, AudioSource>();

	private CustomMessagingManager registeredOn;

	private AudioClip staticClip;

	private bool localStatic;

	private WalkieTalkie localWalkie;

	public static void Init(GameObject host, ConfigFile cfg, ManualLogSource log)
	{
		//IL_0050: 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_0089: Expected O, but got Unknown
		Log = log;
		enabledCfg = cfg.Bind<bool>("Walkie", "No walkie signal from the Backrooms", true, "In the Backrooms you can still hear others on a walkie-talkie, but talking only sends static (you and everyone else hear static).");
		volumeCfg = cfg.Bind<float>("Walkie", "Static volume", 0.6f, "Volume of the static (0-1).");
		Instance = host.AddComponent<BackroomsWalkie>();
		try
		{
			new Harmony("private.BackroomsExitBeacon.Walkie").Patch((MethodBase)AccessTools.Method(typeof(WalkieTalkie), "SetLocalClientSpeaking", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BackroomsWalkie), "SpeakingPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Log.LogInfo((object)("Backrooms walkie static is " + (enabledCfg.Value ? "on" : "off")));
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Could not set up Backrooms walkie static: " + ex));
		}
	}

	private static bool SpeakingPrefix(WalkieTalkie __instance, bool speaking)
	{
		if ((Object)(object)Instance == (Object)null || !enabledCfg.Value)
		{
			return true;
		}
		PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
		if ((Object)(object)val == (Object)null)
		{
			return true;
		}
		if (speaking && (Object)(object)BeaconRunner.Instance != (Object)null && BeaconRunner.Instance.IsInsideBackrooms(val))
		{
			Instance.SetLocalStatic(on: true, __instance);
			return false;
		}
		if (!speaking && Instance.localStatic)
		{
			Instance.SetLocalStatic(on: false, __instance);
		}
		return true;
	}

	private void SetLocalStatic(bool on, WalkieTalkie walkie)
	{
		if (localStatic != on)
		{
			localStatic = on;
			localWalkie = (on ? walkie : null);
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			int playerId = (int)localPlayerController.playerClientId;
			Apply(playerId, on);
			Broadcast(playerId, on);
			if (on)
			{
				Log.LogInfo((object)"Talking on a walkie from the Backrooms - sending static only");
			}
		}
	}

	private void Update()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton != (Object)null && singleton.IsListening && singleton.CustomMessagingManager != null && singleton.CustomMessagingManager != registeredOn)
		{
			registeredOn = singleton.CustomMessagingManager;
			registeredOn.RegisterNamedMessageHandler("BackroomsExitBeacon.WalkieStatic", new HandleNamedMessageDelegate(OnMessage));
			transmitting.Clear();
		}
		else if (((Object)(object)singleton == (Object)null || !singleton.IsListening) && registeredOn != null)
		{
			registeredOn = null;
			transmitting.Clear();
		}
		if (localStatic)
		{
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			if (!((Object)(object)val != (Object)null) || val.isPlayerDead || !((Object)(object)localWalkie != (Object)null) || !((GrabbableObject)localWalkie).isBeingUsed || !localWalkie.isHoldingButton || !((Object)(object)((GrabbableObject)localWalkie).playerHeldBy == (Object)(object)val) || !((Object)(object)BeaconRunner.Instance != (Object)null) || !BeaconRunner.Instance.IsInsideBackrooms(val))
			{
				SetLocalStatic(on: false, localWalkie);
			}
		}
		if (transmitting.Count > 0 && (Object)(object)StartOfRound.Instance != (Object)null)
		{
			List<int> list = new List<int>();
			foreach (int item in transmitting)
			{
				if (item < 0 || item >= StartOfRound.Instance.allPlayerScripts.Length)
				{
					list.Add(item);
					continue;
				}
				PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[item];
				if ((Object)(object)val2 == (Object)null || val2.isPlayerDead || !val2.isPlayerControlled)
				{
					list.Add(item);
				}
			}
			foreach (int item2 in list)
			{
				transmitting.Remove(item2);
			}
		}
		UpdateSources();
	}

	private void Apply(int playerId, bool on)
	{
		if (!(on ? transmitting.Add(playerId) : transmitting.Remove(playerId)))
		{
			return;
		}
		foreach (WalkieTalkie allWalkieTalky in WalkieTalkie.allWalkieTalkies)
		{
			if (!((Object)(object)allWalkieTalky == (Object)null) && ((GrabbableObject)allWalkieTalky).isBeingUsed && !((Object)(object)allWalkieTalky.thisAudio == (Object)null))
			{
				AudioClip[] array = (on ? allWalkieTalky.startTransmissionSFX : allWalkieTalky.stopTransmissionSFX);
				if (array != null && array.Length > 0)
				{
					allWalkieTalky.thisAudio.PlayOneShot(array[Random.Range(0, array.Length)]);
				}
			}
		}
	}

	private void UpdateSources()
	{
		bool flag = transmitting.Count > 0 && enabledCfg.Value;
		foreach (WalkieTalkie allWalkieTalky in WalkieTalkie.allWalkieTalkies)
		{
			if ((Object)(object)allWalkieTalky == (Object)null)
			{
				continue;
			}
			staticSources.TryGetValue(allWalkieTalky, out var value);
			bool flag2 = flag && ((GrabbableObject)allWalkieTalky).isBeingUsed;
			if (flag2 && (Object)(object)value == (Object)null)
			{
				value = CreateSource(allWalkieTalky);
			}
			if (!((Object)(object)value == (Object)null))
			{
				value.volume = volumeCfg.Value;
				if (flag2 && !value.isPlaying)
				{
					value.time = Random.Range(0f, staticClip.length * 0.9f);
					value.Play();
				}
				else if (!flag2 && value.isPlaying)
				{
					value.Stop();
				}
			}
		}
		List<WalkieTalkie> list = null;
		foreach (WalkieTalkie key in staticSources.Keys)
		{
			if ((Object)(object)key == (Object)null)
			{
				if (list == null)
				{
					list = new List<WalkieTalkie>();
				}
				list.Add(key);
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (WalkieTalkie item in list)
		{
			staticSources.Remove(item);
		}
	}

	private AudioSource CreateSource(WalkieTalkie w)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)staticClip == (Object)null)
		{
			staticClip = MakeStatic();
		}
		AudioSource val = ((Component)w).gameObject.AddComponent<AudioSource>();
		AudioSource thisAudio = w.thisAudio;
		val.clip = staticClip;
		val.loop = true;
		val.playOnAwake = false;
		if ((Object)(object)thisAudio != (Object)null)
		{
			val.spatialBlend = thisAudio.spatialBlend;
			val.rolloffMode = thisAudio.rolloffMode;
			val.minDistance = thisAudio.minDistance;
			val.maxDistance = thisAudio.maxDistance;
			val.outputAudioMixerGroup = thisAudio.outputAudioMixerGroup;
			val.dopplerLevel = 0f;
		}
		staticSources[w] = val;
		return val;
	}

	private static AudioClip MakeStatic()
	{
		int num = 88200;
		float[] array = new float[num];
		Random random = new Random(1234);
		float num2 = 0f;
		float num3 = 0f;
		float num4 = 0f;
		for (int i = 0; i < num; i++)
		{
			float num5 = (float)(random.NextDouble() * 2.0 - 1.0);
			num2 += (num5 - num2) * 0.35f;
			num3 = num2 - num4;
			num4 = num2;
			float num6 = num2 * 0.75f + num3 * 0.5f;
			float num7 = 0.7f + 0.3f * (float)Math.Sin((double)i * 2.0 * Math.PI * 7.0 / 44100.0) * (float)Math.Sin((double)i * 2.0 * Math.PI * 0.6 / 44100.0);
			num6 *= num7;
			if (random.NextDouble() < 0.0006)
			{
				num6 += (float)(random.NextDouble() * 2.0 - 1.0) * 0.9f;
			}
			array[i] = Mathf.Clamp(num6 * 0.55f, -1f, 1f);
		}
		AudioClip val = AudioClip.Create("BackroomsWalkieStatic", num, 1, 44100, false);
		val.SetData(array, 0);
		return val;
	}

	private void Broadcast(int playerId, bool on)
	{
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || registeredOn == null)
		{
			return;
		}
		if (singleton.IsServer)
		{
			foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
			{
				if (connectedClientsId != singleton.LocalClientId)
				{
					Send(connectedClientsId, playerId, on);
				}
			}
			return;
		}
		Send(0uL, playerId, on);
	}

	private void Send(ulong clientId, int playerId, bool on)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		byte[] array = new byte[2]
		{
			(byte)playerId,
			(byte)(on ? 1u : 0u)
		};
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1);
		try
		{
			((FastBufferWriter)(ref val)).WriteBytesSafe(array, 2, 0);
			registeredOn.SendNamedMessage("BackroomsExitBeacon.WalkieStatic", clientId, val, (NetworkDelivery)2);
		}
		finally
		{
			((FastBufferWriter)(ref val)).Dispose();
		}
	}

	private void OnMessage(ulong sender, FastBufferReader reader)
	{
		try
		{
			byte[] array = new byte[2];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref array, 2, 0);
			int playerId = array[0];
			bool flag = array[1] != 0;
			Apply(playerId, flag);
			NetworkManager singleton = NetworkManager.Singleton;
			if (!singleton.IsServer)
			{
				return;
			}
			foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
			{
				if (connectedClientsId != singleton.LocalClientId && connectedClientsId != sender)
				{
					Send(connectedClientsId, playerId, flag);
				}
			}
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Bad walkie static message: " + ex.Message));
		}
	}
}
public static class MaskDropOnBackrooms
{
	private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static ManualLogSource Log;

	private static ConfigEntry<bool> enabled;

	private static FieldInfo execStage;

	private static MethodInfo dropHeldItem;

	private static MethodInfo setSpecialGrab;

	private static FieldInfo headMaskField;

	private static FieldInfo attachingField;

	private static FieldInfo finishedAttachingField;

	public static void Init(ConfigFile cfg, ManualLogSource log)
	{
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Expected O, but got Unknown
		Log = log;
		enabled = cfg.Bind<bool>("Masks", "Drop masks when sent to Backrooms", true, "When you are sent to the Backrooms, Comedy / Tragedy masks in your inventory drop on the floor where you were instead of coming with you.");
		try
		{
			Type type = FindType("Backrooms", "Backrooms.Backrooms");
			if (type == null)
			{
				Log.LogWarning((object)"Backrooms not loaded - mask drop is off");
				return;
			}
			MethodInfo method = type.GetMethod("TeleportToBackroomsClientRpc", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			execStage = typeof(NetworkBehaviour).GetField("__rpc_exec_stage", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			dropHeldItem = AccessTools.Method(typeof(PlayerControllerB), "DropHeldItem", (Type[])null, (Type[])null);
			setSpecialGrab = AccessTools.Method(typeof(PlayerControllerB), "SetSpecialGrabAnimationBool", (Type[])null, (Type[])null);
			headMaskField = AccessTools.Field(typeof(HauntedMaskItem), "currentHeadMask");
			attachingField = AccessTools.Field(typeof(HauntedMaskItem), "attaching");
			finishedAttachingField = AccessTools.Field(typeof(HauntedMaskItem), "finishedAttaching");
			if (method == null || execStage == null || dropHeldItem == null)
			{
				Log.LogWarning((object)("Mask drop: game or Backrooms changed (rpc=" + (method != null) + ", stage=" + (execStage != null) + ", drop=" + (dropHeldItem != null) + ") - mask drop is off"));
			}
			else
			{
				new Harmony("private.BackroomsExitBeacon.MaskDrop").Patch((MethodBase)method, new HarmonyMethod(typeof(MaskDropOnBackrooms), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)("Mask drop on Backrooms teleport is " + (enabled.Value ? "on" : "off")));
			}
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Could not set up mask drop: " + ex));
		}
	}

	private static void Prefix(NetworkBehaviour __instance, int __0)
	{
		if (!enabled.Value)
		{
			return;
		}
		try
		{
			if (Convert.ToInt32(execStage.GetValue(__instance)) == 0)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || __0 < 0 || __0 >= instance.allPlayerScripts.Length)
			{
				return;
			}
			PlayerControllerB val = instance.allPlayerScripts[__0];
			if ((Object)(object)val == (Object)null || val.isPlayerDead || ((Object)(object)BeaconRunner.Instance != (Object)null && BeaconRunner.Instance.IsInsideBackrooms(val)))
			{
				return;
			}
			for (int i = 0; i < val.ItemSlots.Length; i++)
			{
				GrabbableObject obj = val.ItemSlots[i];
				HauntedMaskItem val2 = (HauntedMaskItem)(object)((obj is HauntedMaskItem) ? obj : null);
				if ((Object)(object)val2 != (Object)null)
				{
					DropMask(val, i, val2);
				}
			}
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Mask drop failed: " + ex));
		}
	}

	private static void DropMask(PlayerControllerB player, int slot, HauntedMaskItem mask)
	{
		//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_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		if ((headMaskField != null && (Object)/*isinst with value type is only supported in some contexts*/ != (Object)null) || (attachingField != null && (bool)attachingField.GetValue(mask)) || (finishedAttachingField != null && (bool)finishedAttachingField.GetValue(mask)))
		{
			Log.LogInfo((object)("Mask on " + player.playerUsername + " is attaching - not dropping it"));
			return;
		}
		bool flag = (Object)(object)player.currentlyHeldObjectServer == (Object)(object)mask;
		Vector3 zero = Vector3.zero;
		dropHeldItem.Invoke(player, new object[10] { mask, true, false, zero, zero, zero, zero, zero, false, false });
		player.ItemSlots[slot] = null;
		player.carryWeight = Mathf.Clamp(player.carryWeight - (((GrabbableObject)mask).itemProperties.weight - 1f), 1f, 10f);
		if (flag)
		{
			player.isHoldingObject = false;
			player.currentlyHeldObjectServer = null;
			player.activatingItem = false;
			player.twoHanded = false;
			player.twoHandedAnimation = false;
			if (setSpecialGrab != null)
			{
				setSpecialGrab.Invoke(player, new object[2] { false, mask });
			}
			if ((Object)(object)player.playerBodyAnimator != (Object)null)
			{
				player.playerBodyAnimator.SetBool("HoldMask", false);
				player.playerBodyAnimator.SetBool("cancelHolding", true);
				player.playerBodyAnimator.SetTrigger("Throw");
			}
		}
		if (((NetworkBehaviour)player).IsOwner && (Object)(object)HUDManager.Instance != (Object)null)
		{
			if (slot < HUDManager.Instance.itemSlotIcons.Length)
			{
				((Behaviour)HUDManager.Instance.itemSlotIcons[slot]).enabled = false;
			}
			if (flag)
			{
				((Behaviour)HUDManager.Instance.holdingTwoHandedItem).enabled = false;
				HUDManager.Instance.ClearControlTips();
			}
		}
		Log.LogInfo((object)string.Concat("Dropped ", ((GrabbableObject)mask).itemProperties.itemName, " from ", player.playerUsername, "'s slot ", slot + 1, " at ", ((Component)player).transform.position, " before the Backrooms teleport"));
	}

	private static Type FindType(string assemblyName, string typeName)
	{
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			if (!(assembly.GetName().Name != assemblyName))
			{
				Type type = assembly.GetType(typeName);
				if (type != null)
				{
					return type;
				}
			}
		}
		return null;
	}
}
public static class MaskedToBackrooms
{
	private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static ManualLogSource Log;

	private static ConfigEntry<bool> enabled;

	private static ConfigEntry<int> chance;

	private static readonly HashSet<ulong> watchedMimics = new HashSet<ulong>();

	public static void Init(ConfigFile cfg, ManualLogSource log)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Expected O, but got Unknown
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Expected O, but got Unknown
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Expected O, but got Unknown
		Log = log;
		enabled = cfg.Bind<bool>("Masked", "Masked kills send to Backrooms", true, "When a Masked would kill you, you are sent to the Backrooms alive instead, and a Masked wearing your suit is left where you were caught.");
		chance = cfg.Bind<int>("Masked", "Chance percent", 100, "Chance (0-100) that a Masked kill sends you to the Backrooms instead of killing you.");
		try
		{
			Harmony val = new Harmony("private.BackroomsExitBeacon.MaskedToBackrooms");
			MethodInfo methodInfo = AccessTools.Method(typeof(MaskedPlayerEnemy), "killAnimation", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.EnumeratorMoveNext((MethodBase)methodInfo);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(MaskedToBackrooms), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.Method(typeof(MaskedPlayerEnemy), "CreateMimicClientRpc", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MaskedToBackrooms), "CreateMimicPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Log.LogInfo((object)("Masked -> Backrooms is " + (enabled.Value ? ("on (" + chance.Value + "%)") : "off")));
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Could not set up Masked -> Backrooms: " + ex));
		}
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		MethodInfo hook = AccessTools.Method(typeof(MaskedToBackrooms), "KillPlayerHook", (Type[])null, (Type[])null);
		int replaced = 0;
		foreach (CodeInstruction ci in instructions)
		{
			MethodInfo mi = ci.operand as MethodInfo;
			if ((ci.opcode == OpCodes.Callvirt || ci.opcode == OpCodes.Call) && mi != null && mi.Name == "KillPlayer" && mi.DeclaringType == typeof(PlayerControllerB))
			{
				ci.opcode = OpCodes.Call;
				ci.operand = hook;
				replaced++;
			}
			yield return ci;
		}
		if (replaced == 0)
		{
			Log.LogWarning((object)"Masked kill call not found - Masked -> Backrooms will not work on this game version");
		}
		else
		{
			Log.LogInfo((object)("Hooked the Masked kill (" + replaced + " call)"));
		}
	}

	public static void KillPlayerHook(PlayerControllerB player, Vector3 bodyVelocity, bool spawnBody, CauseOfDeath causeOfDeath, int deathAnimation, Vector3 positionOffset, bool setOverrideDropItems)
	{
		//IL_0097: 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_009c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player != (Object)null && enabled.Value)
		{
			if (!((NetworkBehaviour)player).IsOwner)
			{
				return;
			}
			try
			{
				if (CanSendToBackrooms(player) && Random.Range(0, 100) < chance.Value && (Object)(object)BeaconRunner.Instance != (Object)null)
				{
					Log.LogInfo((object)("Masked caught " + player.playerUsername + " - sending them to the Backrooms instead"));
					((MonoBehaviour)BeaconRunner.Instance).StartCoroutine(SendToBackrooms(player));
					return;
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Masked -> Backrooms failed, falling back to a normal death: " + ex));
			}
		}
		player.KillPlayer(bodyVelocity, spawnBody, causeOfDeath, deathAnimation, positionOffset, setOverrideDropItems);
	}

	private static bool CanSendToBackrooms(PlayerControllerB player)
	{
		if (player.isPlayerDead || !player.AllowPlayerDeath())
		{
			return false;
		}
		Type type = FindType("Backrooms", "Backrooms.Backrooms");
		if (type == null)
		{
			return false;
		}
		FieldInfo field = type.GetField("Instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		if (field == null || field.GetValue(null) == null)
		{
			return false;
		}
		if ((Object)(object)BeaconRunner.Instance != (Object)null && BeaconRunner.Instance.IsInsideBackrooms(player))
		{
			return false;
		}
		Type type2 = FindType("Backrooms", "Backrooms.BackroomsHelper");
		if (type2 != null)
		{
			Component component = ((Component)player).GetComponent(type2);
			FieldInfo field2 = type2.GetField("HasBeenInTheBackrooms", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if ((Object)(object)component != (Object)null && field2 != null && (bool)field2.GetValue(component))
			{
				Log.LogInfo((object)(player.playerUsername + " has already been in the Backrooms this round - normal Masked death"));
				return false;
			}
		}
		return true;
	}

	private static IEnumerator SendToBackrooms(PlayerControllerB player)
	{
		yield return null;
		yield return null;
		if ((Object)(object)player == (Object)null || player.isPlayerDead)
		{
			yield break;
		}
		int id = (int)player.playerClientId;
		Type rpcType = FindType("TestAccount666.RealBackroomsPatch", "RealBackroomsPatch.RpcCollection");
		object rpc = null;
		if (rpcType != null)
		{
			PropertyInfo property = rpcType.GetProperty("Instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				rpc = property.GetValue(null, null);
			}
		}
		if (rpc != null)
		{
			MethodInfo method = rpcType.GetMethod("TeleportPlayerToBackroomsServerRpc", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(rpc, new object[8]
			{
				id,
				false,
				Vector3.zero,
				(object)(CauseOfDeath)4,
				4,
				true,
				false,
				false
			});
		}
		else
		{
			Type type = FindType("Backrooms", "Backrooms.Backrooms");
			object value = type.GetField("Instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null);
			type.GetMethod("TeleportToBackroomsServerRpc", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(value, new object[1] { id });
		}
	}

	private static void CreateMimicPostfix(NetworkObjectReference netObjectRef, bool inFactory, int playerKilled)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		if (enabled != null && enabled.Value && !((Object)(object)BeaconRunner.Instance == (Object)null) && watchedMimics.Add(((NetworkObjectReference)(ref netObjectRef)).NetworkObjectId))
		{
			((MonoBehaviour)BeaconRunner.Instance).StartCoroutine(WatchMimic(netObjectRef, inFactory, playerKilled));
		}
	}

	private static IEnumerator WatchMimic(NetworkObjectReference netRef, bool inFactory, int playerId)
	{
		//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)
		if ((Object)(object)StartOfRound.Instance == (Object)null || playerId < 0 || playerId >= StartOfRound.Instance.allPlayerScripts.Length)
		{
			yield break;
		}
		PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerId];
		float start = Time.realtimeSinceStartup;
		bool spared = false;
		while (true)
		{
			if (Time.realtimeSinceStartup - start < 10f)
			{
				if ((Object)(object)player == (Object)null || player.isPlayerDead)
				{
					break;
				}
				if (!BeaconRunner.Instance.IsInsideBackrooms(player))
				{
					yield return (object)new WaitForSeconds(0.1f);
					continue;
				}
				spared = true;
			}
			if (!spared)
			{
				break;
			}
			NetworkObject netObject = null;
			while (true)
			{
				if (!((NetworkObjectReference)(ref netRef)).TryGet(ref netObject, (NetworkManager)null))
				{
					if (!(Time.realtimeSinceStartup - start > 25f))
					{
						yield return null;
						continue;
					}
					break;
				}
				MaskedPlayerEnemy masked = ((Component)netObject).GetComponent<MaskedPlayerEnemy>();
				if ((Object)(object)masked == (Object)null)
				{
					break;
				}
				Log.LogInfo((object)("Masked copy of " + player.playerUsername + " is now walking around"));
				float until = Time.realtimeSinceStartup + 25f;
				bool first = true;
				while ((Object)(object)masked != (Object)null && Time.realtimeSinceStartup < until)
				{
					if (first || (Object)(object)masked.mimickingPlayer == (Object)(object)player)
					{
						masked.mimickingPlayer = null;
						masked.allowSpawningWithoutPlayer = true;
						masked.SetSuit(player.currentSuitID);
						((EnemyAI)masked).SetEnemyOutside(!inFactory);
						first = false;
					}
					if (!player.isPlayerDead && (Object)(object)player.redirectToEnemy == (Object)(object)masked)
					{
						player.redirectToEnemy = null;
					}
					yield return (object)new WaitForSeconds(0.25f);
				}
				break;
			}
			break;
		}
	}

	private static Type FindType(string assemblyName, string typeName)
	{
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			if (!(assembly.GetName().Name != assemblyName))
			{
				Type type = assembly.GetType(typeName);
				if (type != null)
				{
					return type;
				}
			}
		}
		return null;
	}
}